diff --git a/html/arabic/net/rendering-html-documents/_index.md b/html/arabic/net/rendering-html-documents/_index.md index 7d8baa5d7..91adf4454 100644 --- a/html/arabic/net/rendering-html-documents/_index.md +++ b/html/arabic/net/rendering-html-documents/_index.md @@ -45,11 +45,13 @@ url: /ar/net/rendering-html-documents/ ### [كيفية تحويل HTML إلى PNG – دليل C# كامل](./how-to-render-html-as-png-complete-c-guide/) تعلم خطوة بخطوة كيفية تحويل مستندات HTML إلى صور PNG باستخدام Aspose.HTML وC# في هذا الدليل الشامل. + ### [كيفية استخدام Aspose لتحويل HTML إلى PNG – دليل خطوة بخطوة](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) تعلم كيفية تحويل مستندات HTML إلى صور PNG باستخدام Aspose.HTML في .NET خطوة بخطوة. ### [إنشاء PNG من HTML – دليل كامل للتصيير باستخدام C#](./create-png-from-html-full-c-rendering-guide/) تعلم كيفية تحويل صفحات HTML إلى صور PNG باستخدام Aspose.HTML في دليل شامل يوضح كل خطوة في C#. + ### [عرض EPUB بتنسيق XPS في .NET باستخدام Aspose.HTML](./render-epub-as-xps/) تعرف على كيفية إنشاء مستندات HTML وعرضها باستخدام Aspose.HTML لـ .NET في هذا البرنامج التعليمي الشامل. انغمس في عالم معالجة HTML وكشط الويب والمزيد. @@ -68,6 +70,12 @@ url: /ar/net/rendering-html-documents/ ### [كيفية تحويل HTML إلى PNG باستخدام Aspose – دليل كامل](./how-to-render-html-to-png-with-aspose-complete-guide/) تعلم خطوة بخطوة كيفية تحويل مستندات HTML إلى صور PNG باستخدام Aspose.HTML في .NET. +### [تحويل HTML إلى صورة في C# – دليل كامل خطوة بخطوة](./render-html-to-image-in-c-complete-step-by-step-guide/) +تعلم كيفية تحويل مستندات HTML إلى صور باستخدام Aspose.HTML في C# خطوة بخطوة. + +### [تحويل HTML إلى PNG في C# – دليل خطوة بخطوة](./render-html-to-png-in-c-step-by-step-guide/) +تعلم كيفية تحويل مستندات HTML إلى صور PNG باستخدام Aspose.HTML في C# خطوة بخطوة. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/arabic/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/arabic/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..69f12b1d0 --- /dev/null +++ b/html/arabic/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-03-14 +description: قم بتحويل HTML إلى صورة بسرعة باستخدام Aspose.HTML. تعلّم كيفية تحويل + صفحة الويب إلى PNG، وضبط نمط الخط، وحفظ الصورة المُعالجة في بضع أسطر فقط من C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: ar +og_description: تحويل HTML إلى صورة باستخدام Aspose.HTML. يوضح هذا الدليل كيفية تحويل + صفحة الويب إلى PNG، وتعيين نمط الخط، وحفظ الصورة المُعالجة في C#. +og_title: تحويل HTML إلى صورة في C# – دليل سريع وسهل +tags: +- C# +- Aspose.HTML +- Image Rendering +title: تحويل HTML إلى صورة في C# – دليل كامل خطوة بخطوة +url: /ar/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحويل HTML إلى صورة – دليل C# الكامل + +هل احتجت يوماً إلى **تحويل HTML إلى صورة** لكن لم تكن متأكدًا أي مكتبة تختار؟ لست وحدك. في العديد من سيناريوهات أتمتة الويب أو إعداد التقارير قد تحصل على صفحة حية تريد أرشفتها كملف PNG أو JPEG أو حتى BMP. الخبر السار هو أن Aspose.HTML يجعل ذلك سهلًا للغاية، حيث يمكنك **تحويل صفحة ويب إلى PNG** ببضع أسطر من الشيفرة فقط. + +في هذا الدليل سنستعرض العملية بالكامل: من تثبيت حزمة Aspose.HTML، تحميل عنوان URL بعيد، تعديل خيارات التصيير (بما في ذلك **تعيين نمط الخط**)، وأخيرًا **حفظ الصورة المُصَغَّرة** على القرص. في النهاية ستحصل على تطبيق كونسول جاهز للتنفيذ ينتج لقطة شاشة واضحة لأي صفحة ويب. + +## ما ستحتاجه + +قبل أن نبدأ، تأكد من توفر التالي: + +| المتطلب المسبق | السبب | +|--------------|--------| +| .NET 6.0 SDK أو أحدث | Aspose.HTML يستهدف .NET Standard 2.0+، لذا فإن .NET 6 يزودك بأحدث بيئة تشغيل. | +| Visual Studio 2022 (أو VS Code) | بيئة تطوير مريحة تُسرّع عملية التصحيح. | +| حزمة Aspose.HTML for .NET من NuGet | هذه هي المحرك الذي يقوم بالعمل الشاق. | +| رخصة صالحة لـ Aspose.HTML (اختياري) | بدون رخصة ستحصل على علامة مائية على الصورة الناتجة. | + +يمكنك الحصول على الحزمة عبر سطر الأوامر: + +```bash +dotnet add package Aspose.HTML +``` + +إذا كنت تفضّل الواجهة الرسومية، ابحث عن “Aspose.HTML” في مدير حزم NuGet. + +--- + +## الخطوة 1: تحميل صفحة الويب التي تريد تحويلها إلى صورة نقطية + +أول شيء عليك فعله هو تزويد Aspose.HTML بمستند المصدر. يمكن أن يكون ملفًا محليًا، سلسلة نصية، أو عنوان URL بعيد. في معظم السيناريوهات الواقعية ستتعامل مع موقع حي، لذا لنقوم **بتحويل صفحة ويب إلى PNG** بالإشارة إلى `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **لماذا هذا مهم:** تحميل الصفحة كـ `HtmlDocument` يمنحك وصولًا كاملًا إلى DOM، مما يعني أنه يمكنك حقن CSS، تعديل التخطيط، أو حتى تشغيل JavaScript قبل التحويل إلى صورة نقطية. + +--- + +## الخطوة 2: ضبط خيارات تصيير الصورة + +الآن بعد أن أصبح HTML في الذاكرة، نحتاج إلى إخبار المُصِّر كيف نريد أن تبدو الصورة النهائية. هنا يمكنك **تعيين نمط الخط**، تمكين مضاد التعرجات (antialiasing)، أو تعديل DPI. أدناه تكوين افتراضي متوازن بين الجودة والسرعة. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **نصيحة احترافية:** إذا كنت تحتاج فقط إلى وزن عادي، احذف علامات `WebFontStyle`. للعناوين قد تكتفي بـ `WebFontStyle.Bold`، بينما يمكن للتعليقات أن تستخدم `WebFontStyle.Italic`. + +--- + +## الخطوة 3: تصيير الصفحة و **حفظ الصورة المُصَغَّرة** كملف PNG + +مع المستند والخيارات جاهزة، الخطوة الأخيرة هي إنشاء كائن `ImageRenderer` وكتابة ملف الإخراج. يضمن بلوك `using` تحرير الموارد بسرعة. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +عند تشغيل البرنامج، يجب أن ترى ملف `page.png` في مجلد المشروع يحتوي على نسخة دقيقة من *example.com*. افتحه بأي عارض صور وستلاحظ نمط الخط العريض‑المائل الذي طلبناه سابقًا. + +### النتيجة المتوقعة + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +سيكون حجم PNG تقريبًا 800 × 600 بكسل (حسب أبعاد الصفحة الأصلية) مع حواف ناعمة بفضل مضاد التعرجات. + +--- + +## مثال كامل يعمل + +بدمج كل ما سبق، إليك تطبيق كونسول بسيط يمكنك نسخه‑ولصقه في `Program.cs`. يتضمن كل ما يلزم للتجميع والتشغيل فورًا. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +شغّله باستخدام: + +```bash +dotnet run +``` + +…وستحصل على ملف PNG جديد جاهز للأرشفة أو الإرسال بالبريد أو تضمينه في تقرير. + +--- + +## تنويعات وحالات خاصة + +### 1. التحويل إلى JPEG بدلاً من PNG + +إذا كان نظامك المستقبلي يفضّل JPEG (حجم أصغر، ضغط فقدان)، فقط غيّر امتداد الملف في `Save`. Aspose.HTML يكتشف الصيغة تلقائيًا من المسار. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +يمكنك أيضًا تعديل جودة الضغط عبر `JpegRenderingOptions`. + +### 2. تغيير أبعاد الصورة + +أحيانًا تحتاج إلى صورة مصغرة بدلاً من لقطة شاشة كاملة. اضبط `ImageSize` في الخيارات: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. التعامل مع الصفحات المحمية بالمصادقة + +إذا كان عنوان URL المستهدف يتطلب مصادقة أساسية، زوّد الاعتمادات عبر `HttpWebRequest` قبل إنشاء `HtmlDocument`. بدلاً من ذلك، حمّل HTML بنفسك (باستخدام `HttpClient`) ومرره كسلسلة نصية: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. استخدام خط مخصص + +يمكن لـ Aspose.HTML تضمين الخطوط المحلية. سجّل مجلد الخطوط قبل تحميل المستند: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +الآن أي تعريفات `font-family` في الصفحة ستُحل إلى ملفاتك المخصصة. + +### 5. تصيير صفحات متعددة في حلقة + +إذا كنت بحاجة إلى معالجة مجموعة من عناوين URL دفعة واحدة: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## الأخطاء الشائعة وكيفية تجنّبها + +| العَرَض | السبب المحتمل | الحل | +|---------|--------------|-----| +| ملف PNG فارغ | `HtmlDocument.IsEmpty` يساوي true (فشل تحميل الصفحة) | تحقق من العنوان، افحص بروكسي الشبكة، تأكد من تمكين TLS 1.2. | +| نص مشوّه على لينكس | تعطيل تلميحات الخط (hinting) | عيّن `renderingOptions.TextOptions.UseHinting = true;`. | +| علامة مائية على الإخراج | عدم توفير رخصة | سجّل رخصة مؤقتة أو كاملة عبر `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| صورة منخفضة الدقة | DPI الافتراضي 96 غير كافٍ للطباعة | زد قيم `renderingOptions.DpiX` و `DpiY` إلى 150‑300. | + +--- + +## 🎉 الخلاصة + +لقد غطينا كل ما تحتاجه **لتحويل HTML إلى صورة** باستخدام Aspose.HTML في C#. من تحميل صفحة بعيدة، ضبط مضاد التعرجات و**تعيين نمط الخط**، إلى **حفظ الصورة المُصَغَّرة** كملف PNG، يتماشى سير العمل بالكامل مع بضع خطوات مختصرة. + +الآن يمكنك **تحويل صفحة ويب إلى PNG** في الوقت الفعلي، تضمين لقطات الشاشة في التقارير، أو إنشاء صور مصغرة لكاتالوج—دون الحاجة إلى أتمتة المتصفح. + +### ما التالي؟ + +- جرّب **تحويل HTML إلى PNG** لأحجام شاشات مختلفة (موبايل مقابل ديسكتوب). +- جرب التصدير إلى PDF باستخدام `PdfRenderer` إذا احتجت مستندًا قابلًا للطباعة. +- استكشف واجهات Aspose.HTML للتلاعب بـ DOM لإضافة علامات مائية أو CSS مخصص قبل التصيير. + +هل لديك أسئلة حول الحالات الخاصة، الترخيص، أو تحسين الأداء؟ اترك تعليقًا أدناه، وتمنياتنا لك ببرمجة سعيدة! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/arabic/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..159d5faf3 --- /dev/null +++ b/html/arabic/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-03-14 +description: قم بتحويل HTML إلى PNG بسرعة باستخدام Aspose.HTML. تعلّم كيفية إنشاء + PNG من HTML، وتطبيق نمط الخط العريض والمائل، وحفظ HTML إلى تدفق. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: ar +og_description: تحويل HTML إلى PNG باستخدام Aspose.HTML. يوضح هذا الدليل كيفية إنشاء + PNG من HTML، واستخدام نمط الخط العريض المائل، وحفظ HTML إلى تدفق. +og_title: تحويل HTML إلى PNG في C# – دليل برمجي كامل +tags: +- Aspose.HTML +- C# +- Image Rendering +title: تحويل HTML إلى PNG في C# – دليل خطوة بخطوة +url: /ar/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +keep all markdown formatting, code block placeholders unchanged. + +Now produce final output.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحويل HTML إلى PNG باستخدام C# – دليل برمجة كامل + +هل احتجت يومًا إلى **render HTML to PNG** لكن لم تكن متأكدًا أي مكتبة ستعطيك نتائج دقيقة على مستوى البكسل؟ لست وحدك. في العديد من خطوط عمل تحويل الويب إلى صورة يواجه المطورون مشاكل مثل الخطوط المفقودة، النص الضبابي، أو السؤال المخيف “كيف ألتقط الـ HTML دون كتابته إلى القرص أولاً؟” + +الأمر هو أن Aspose.HTML تجعل العملية بأكملها سهلة للغاية. في هذا الدرس سنقوم **generate PNG from HTML**، وتطبيق **bold italic font style**، وحتى **save HTML to a stream** حتى تتمكن من الاحتفاظ بكل شيء في الذاكرة. في النهاية ستحصل على تطبيق console جاهز للتشغيل يحول مقتطف HTML صغير إلى ملف PNG واضح. + +--- + +## ما ستحتاجه + +- **.NET 6+** (الكود يعمل مع .NET Core و .NET Framework على حد سواء) +- حزمة NuGet **Aspose.HTML for .NET** – `Install-Package Aspose.HTML` +- بيئة تطوير مفضلة (Visual Studio، Rider، أو VS Code) – أيًا كانت. + +لا خطوط إضافية، لا أدوات خارجية، وبالتأكيد لا ملفات مؤقتة. مجرد C# نقي. + +--- + +## الخطوة 1: إنشاء مستند HTML بسيط + +أول شيء نقوم به هو بناء مستند HTML في الذاكرة. فكر فيه كصفحة ويب افتراضية تعيش فقط داخل عمليتك. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **لماذا هذا مهم:** من خلال بناء DOM برمجيًا تتجنب عبء إدخال/إخراج الملفات ويمكنك حقن البيانات الديناميكية في الوقت الفعلي. فئة `HtmlDocument` هي نقطة الدخول لكل عملية في Aspose.HTML. + +--- + +## الخطوة 2: حفظ HTML إلى Stream + +بدلاً من كتابة العلامات إلى القرص، نلتقطها في `ResourceHandler` مخصص. هذا هو جزء **save html to stream** من سير العمل. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **نصيحة احترافية:** `MemoryHandler` صغير لكنه قوي. إذا احتجت لاحقًا إلى تضمين صور أو CSS أو خطوط، ما عليك سوى توسيع `HandleResource` لإرجاع الـ streams المناسبة. + +--- + +## الخطوة 3: تكوين نمط الخط الغامق المائل + +عند عرض النص، غالبًا ما تريد أن يبدو تمامًا كما هو في المتصفح. Aspose.HTML يتيح لك تعيين **bold italic font style** مباشرةً في خيارات العرض. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **ما يحدث:** +> * `UseAntialiasing` ينعم حواف الأشكال. +> * `UseHinting` يحسن تموضع الحروف، وهو أمر حاسم للنص الصغير. +> * `FontStyle` يجمع بين علمي `Bold` و `Italic`، لذا كل قطعة نص في المستند ترث هذا النمط ما لم يتم تجاوزه. + +--- + +## الخطوة 4: تحويل مستند HTML إلى صورة PNG + +الآن الجزء الممتع – تحويل ذلك الـ HTML إلى ملف صورة. `ImageRenderer` يقوم بكل العمل الشاق. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +إذا شغلت البرنامج، سترى ملفًا باسم `output.png` في دليل العمل. يحتوي على عنوان `
` يصبح لدينا بنية HTML صالحة جاهزة للحفظ. + +> **نصيحة احترافية:** إذا احتجت إلى هيكل HTML كامل (``, `
`، إلخ)، فإن Aspose.HTML يولده تلقائيًا عند حفظ المستند، حتى لو أضفت محتوى فقط إلى الـ body. + +## الخطوة 2: تنفيذ **معالج موارد مخصص** – التقاط HTML في الذاكرة + +*معالج الموارد* يخبر Aspose.HTML أين يكتب كل مورد (HTML، CSS، صور، إلخ). عبر تجاوز `HandleResource` يمكننا توجيه مخرجات HTML إلى `MemoryStream` بدلاً من ملف. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**لماذا نستخدم معالجًا مخصصًا:** +- **الأداء:** لا عمليات إدخال/إخراج على القرص، كل شيء يبقى في الذاكرة. +- **الأمان:** لا ملفات مؤقتة يمكن أن تُستغل. +- **المرونة:** يمكنك لاحقًا تمرير الـ stream إلى استجابة، قاعدة بيانات، أو API آخر. + +## الخطوة 3: حفظ المستند باستخدام المعالج – قلب **Generate HTML Programmatically** + +الآن نربط المستند بالمعالج. عندما يتم استدعاء `htmlDoc.Save(handler)`، يقوم Aspose.HTML باستدعاء `HandleResource`، ويعطينا الـ stream للكتابة فيه. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +في هذه المرحلة يحتوي `handler.HtmlStream` على بايتات HTML الخام. لم يُكتب شيء إلى القرص، ويمكنك إعادة استخدام الـ stream عدة مرات (فقط تذكر إعادة ضبط موقعه). + +## الخطوة 4: قراءة HTML المُولد من الذاكرة – التحقق من النتيجة + +للتأكد من أن كل شيء عمل، نعيد ضبط موضع الـ stream إلى البداية ونقرأ النص مرة أخرى. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**الناتج المتوقع** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +إذا رأيت العلامات أعلاه، تهانينا — لقد نجحت في **generate html programmatically** باستخدام Aspose.HTML و**معالج موارد مخصص**. + +## الاختلافات الشائعة وحالات الحافة + +### التعامل مع CSS أو الصور + +العينة تتجاهل الموارد غير الـ HTML بإرجاع `Stream.Null`. في سيناريو واقعي قد ترغب في التقاط ملفات CSS أو الصور أيضًا: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### إعادة استخدام نفس المعالج لحفظات متعددة + +إذا احتجت إلى توليد عدة قطع HTML داخل حلقة، أنشئ `MemoryHtmlHandler` جديدًا في كل تكرار أو امسح الـ stream الحالي: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### الحفظ غير المتزامن (Aspose.HTML 23.4+) + +الإصدارات الأحدث تدعم الحفظ غير المتزامن: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +تذكر استخدام `await` وجعل الطريقة `async`. + +## مثال كامل يعمل + +فيما يلي البرنامج الكامل الذي يمكنك نسخه ولصقه في تطبيق console. يتضمن جميع الأجزاء التي ناقشناها، بالإضافة إلى بعض التعليقات للتوضيح. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +شغّل البرنامج (`dotnet run`) ويجب أن ترى HTML مطبوعًا في وحدة التحكم، تمامًا كما ظهر سابقًا. + +## الخلاصة + +لقد أوضحنا كيف **تنشئ مستند HTML C#** باستخدام Aspose.HTML، تلتقط المخرجات بـ **معالج موارد مخصص**، وت **generate HTML programmatically** دون لمس نظام الملفات. النمط قابل للتوسع — سواء كنت تبني قوالب بريد إلكتروني، تقارير فورية، أو خدمة مصغرة تُعيد قطع HTML. + +ما الخطوة التالية؟ جرّب إضافة ورقة أنماط CSS عبر المعالج، أو بث الـ HTML مباشرةً إلى استجابة ASP.NET Core (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). يمكنك أيضًا توصيل المخرجات إلى محول PDF أو مكتبة تحويل HTML إلى صورة لتوسيع سير العمل. + +هل لديك أسئلة حول التعامل مع الصور، الحفظ غير المتزامن، أو التكامل مع مكتبات أخرى؟ اترك تعليقًا، ونتمنى لك برمجة سعيدة! + +{{< /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/rendering-html-documents/_index.md b/html/chinese/net/rendering-html-documents/_index.md index 320ef98cc..71095def8 100644 --- a/html/chinese/net/rendering-html-documents/_index.md +++ b/html/chinese/net/rendering-html-documents/_index.md @@ -66,9 +66,16 @@ Aspose.HTML for .NET 凭借其丰富的功能、出色的文档和活跃的社 ### [使用 Aspose.HTML 在 .NET 中将 SVG 文档渲染为 PNG](./render-svg-doc-as-png/) 解锁 Aspose.HTML for .NET 的强大功能!了解如何轻松将 SVG Doc 渲染为 PNG。深入了解分步示例和常见问题解答。立即开始! + ### [使用 Aspose.HTML 在 .NET 中从 HTML 创建 PNG – 完整 C# 渲染指南](./create-png-from-html-full-c-rendering-guide/) 完整的 C# 示例,展示如何使用 Aspose.HTML 将 HTML 渲染为 PNG,涵盖所有关键步骤和最佳实践。 +### [在 C# 中将 HTML 渲染为图像 – 完整分步指南](./render-html-to-image-in-c-complete-step-by-step-guide/) +学习使用 Aspose.HTML for .NET 在 C# 中将 HTML 渲染为图像的完整分步教程,涵盖关键设置和最佳实践。 + +### [在 C# 中将 HTML 渲染为 PNG – 完整分步指南](./render-html-to-png-in-c-step-by-step-guide/) +学习使用 Aspose.HTML for .NET 在 C# 中将 HTML 渲染为 PNG 的完整步骤和最佳实践。 + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/chinese/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/chinese/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..da6d3914a --- /dev/null +++ b/html/chinese/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-03-14 +description: 使用 Aspose.HTML 快速将 HTML 渲染为图像。了解如何将网页转换为 PNG、设置字体样式,并仅用几行 C# 代码保存渲染后的图像。 +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: zh +og_description: 使用 Aspose.HTML 将 HTML 渲染为图像。本教程展示了如何将网页转换为 PNG,设置字体样式,以及在 C# 中保存渲染后的图像。 +og_title: 在 C# 中将 HTML 渲染为图像 – 快速简易指南 +tags: +- C# +- Aspose.HTML +- Image Rendering +title: 在 C# 中将 HTML 渲染为图像 – 完整的逐步指南 +url: /zh/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +. They should be left unchanged. + +We must translate tables content. + +Let's produce translation. + +We need to keep bullet lists, etc. + +Proceed. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 将 HTML 渲染为图像 – 完整 C# 教程 + +是否曾经需要 **将 HTML 渲染为图像**,却不确定该选哪个库?你并不孤单。在许多网页自动化或报表场景中,你会得到一个实时页面,想要将其存档为 PNG、JPEG,甚至 BMP。好消息是 Aspose.HTML 能让这变得轻而易举,只需几行代码即可 **将网页转换为 PNG**。 + +在本指南中,我们将完整演示整个过程:从安装 Aspose.HTML 包、加载远程 URL、调整渲染选项(包括如何 **设置字体样式**),到最终 **保存渲染后的图像** 到磁盘。完成后,你将拥有一个可直接运行的控制台应用程序,能够生成任意网页的清晰截图。 + +## 你需要准备的内容 + +在开始之前,请确保拥有以下条件: + +| 前置条件 | 原因 | +|--------------|--------| +| .NET 6.0 SDK 或更高版本 | Aspose.HTML 目标为 .NET Standard 2.0+,使用 .NET 6 可获得最新运行时。 | +| Visual Studio 2022(或 VS Code) | 舒适的 IDE 能加快调试速度。 | +| Aspose.HTML for .NET NuGet 包 | 这就是完成核心工作的引擎。 | +| 有效的 Aspose.HTML 许可证(可选) | 若未提供许可证,输出图像会带有水印。 | + +你可以通过 CLI 获取该包: + +```bash +dotnet add package Aspose.HTML +``` + +如果更喜欢图形界面,只需在 NuGet 包管理器中搜索 “Aspose.HTML”。 + +--- + +## 第一步:加载要栅格化的网页 + +首先,需要为 Aspose.HTML 提供一个源文档。它可以是本地文件、字符串,或远程 URL。在大多数真实场景下,你会处理一个实时站点,所以我们通过指向 `https://example.com` 来 **将网页转换为 PNG**。 + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **为什么重要:** 将页面加载为 `HtmlDocument` 能让你完整访问 DOM,这意味着可以在栅格化前注入 CSS、操作布局,甚至执行 JavaScript。 + +--- + +## 第二步:配置图像渲染选项 + +HTML 已经在内存中后,需要告诉渲染器最终图片的外观。这里可以 **设置字体样式**、启用抗锯齿或调整 DPI。下面的配置在质量与速度之间取得了良好平衡。 + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **专业提示:** 如果只需要常规粗细,去掉 `WebFontStyle` 标志即可。标题可以仅使用 `WebFontStyle.Bold`,而说明文字则可使用 `WebFontStyle.Italic`。 + +--- + +## 第三步:渲染页面并 **保存渲染后的图像** 为 PNG + +文档和选项准备就绪后,最后一步是实例化 `ImageRenderer` 并写入输出文件。`using` 代码块可确保资源及时释放。 + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +运行程序后,你应在项目文件夹中看到一个 `page.png`,它是 *example.com* 的忠实快照。使用任意图像查看器打开,你会看到之前请求的粗斜体样式。 + +### 预期输出 + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +该 PNG 大约为 800 × 600 px(取决于页面原始尺寸),并因抗锯齿而拥有平滑边缘。 + +--- + +## 完整工作示例 + +将所有内容整合后,下面是一个可以直接复制到 `Program.cs` 的最小控制台应用程序。它开箱即用。 + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +使用以下命令运行: + +```bash +dotnet run +``` + +…即可得到一张全新的 PNG,适合归档、邮件发送或嵌入报告。 + +--- + +## 变体与边缘情况 + +### 1. 将输出改为 JPEG 而非 PNG + +如果下游系统更倾向于 JPEG(文件更小、采用有损压缩),只需在 `Save` 中更改文件扩展名。Aspose.HTML 会自动根据路径检测格式。 + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +还可以通过 `JpegRenderingOptions` 调整压缩质量。 + +### 2. 更改图像尺寸 + +有时需要缩略图而非全尺寸截图。只需在选项上设置 `ImageSize`: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. 处理需要身份验证的页面 + +如果目标 URL 需要基本认证,可在创建 `HtmlDocument` 前通过 `HttpWebRequest` 提供凭据。或者自行使用 `HttpClient` 下载 HTML 并以字符串形式传入: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. 使用自定义字体 + +Aspose.HTML 能嵌入本地字体。加载文档前先注册字体文件夹: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +此后页面中的 `font-family` 声明将解析为你的自定义字体文件。 + +### 5. 在循环中渲染多个页面 + +如果需要批量处理一系列 URL: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## 常见陷阱及规避方法 + +| 症状 | 可能原因 | 解决方案 | +|---------|--------------|-----| +| PNG 文件为空 | `HtmlDocument.IsEmpty` 为 true(页面加载失败) | 检查 URL、网络代理,确保启用 TLS 1.2。 | +| Linux 上文字乱码 | 字体 hinting 被禁用 | 设置 `renderingOptions.TextOptions.UseHinting = true;`。 | +| 输出带水印 | 未提供许可证 | 通过 `License license = new License(); license.SetLicense("Aspose.Total.lic");` 注册临时或正式许可证。 | +| 图像分辨率低 | 默认 DPI 为 96,打印时不足 | 将 `renderingOptions.DpiX` 与 `DpiY` 提升至 150‑300。 | + +--- + +## 🎉 结论 + +我们已经完整演示了如何使用 Aspose.HTML 在 C# 中 **将 HTML 渲染为图像**。从加载远程页面、配置抗锯齿与 **设置字体样式**,到最终 **保存渲染后的图像** 为 PNG,整个工作流仅需几步即可实现。 + +现在,你可以在运行时 **将网页转换为 PNG**,将截图嵌入报告,或为目录生成缩略图——无需浏览器自动化。 + +### 接下来可以做什么? + +- 试着对不同屏幕尺寸(移动端 vs 桌面端)进行 **convert html to png**。 +- 若需要可打印文档,可使用 `PdfRenderer` 导出为 PDF。 +- 深入了解 Aspose.HTML 的 DOM 操作 API,在渲染前注入水印或自定义 CSS。 + +对边缘情况、许可证或性能调优有疑问?欢迎在下方留言,祝编码愉快! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/chinese/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..58900ff4d --- /dev/null +++ b/html/chinese/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-03-14 +description: 使用 Aspose.HTML 快速将 HTML 渲染为 PNG。了解如何从 HTML 生成 PNG、应用粗体斜体字体样式,以及将 HTML + 保存到流中。 +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: zh +og_description: 使用 Aspose.HTML 将 HTML 渲染为 PNG。本指南展示了如何从 HTML 生成 PNG、使用粗体斜体字体样式以及将 + HTML 保存到流。 +og_title: 在 C# 中将 HTML 渲染为 PNG – 完整编程演练 +tags: +- Aspose.HTML +- C# +- Image Rendering +title: 在 C# 中将 HTML 渲染为 PNG – 步骤指南 +url: /zh/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +Image alt text. + +Ok. + +Let's craft final answer.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中将 HTML 渲染为 PNG – 完整编程演练 + +是否曾经需要**将 HTML 渲染为 PNG**,却不确定哪个库能提供像素级完美的效果?你并不孤单。在许多 Web 转图片的流水线中,开发者常常会遇到缺少字体、文字模糊,或者最让人头疼的“如何在不先写入磁盘的情况下捕获 HTML?”的问题。 + +事实是:Aspose.HTML 让整个过程变得轻而易举。在本教程中,我们将**从 HTML 生成 PNG**,应用**粗斜体字体样式**,甚至**将 HTML 保存到流**,从而全部在内存中完成。完成后,你将拥有一个可直接运行的控制台应用程序,能够把一小段 HTML 代码转换为清晰的 PNG 文件。 + +--- + +## 你需要准备的环境 + +- **.NET 6+**(代码在 .NET Core 和 .NET Framework 上均可运行) +- **Aspose.HTML for .NET** NuGet 包 – `Install-Package Aspose.HTML` +- 任意常用的 IDE(Visual Studio、Rider 或 VS Code)均可。 + +无需额外字体、外部工具,更不需要临时文件。纯粹的 C#。 + +--- + +## 第一步:创建一个简单的 HTML 文档 + +我们首先在内存中构建一个 HTML 文档。可以把它想象成只存在于进程内部的虚拟网页。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **为什么重要:** 通过以编程方式构造 DOM,你可以避免文件 I/O 开销,并且能够在运行时即时注入动态数据。`HtmlDocument` 类是所有 Aspose.HTML 操作的入口。 + +--- + +## 第二步:将 HTML 保存到流 + +我们不把标记写入磁盘,而是捕获到自定义的 `ResourceHandler` 中。这就是工作流中的**将 HTML 保存到流**环节。 + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **小技巧:** `MemoryHandler` 虽小却强大。如果以后需要嵌入图片、CSS 或字体,只需扩展 `HandleResource`,返回相应的流即可。 + +--- + +## 第三步:配置粗斜体字体样式 + +在渲染文本时,你通常希望它的外观与浏览器完全一致。Aspose.HTML 允许你直接在渲染选项上设置**粗斜体字体样式**。 + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **正在发生的事:** +> * `UseAntialiasing` 平滑形状边缘。 +> * `UseHinting` 改善字形定位,对小字号文本尤为关键。 +> * `FontStyle` 将 `Bold` 与 `Italic` 标志组合在一起,因此文档中的所有文本默认继承该样式,除非另行覆盖。 + +--- + +## 第四步:将 HTML 文档渲染为 PNG 图像 + +现在进入有趣的环节——把 HTML 转换为图像文件。`ImageRenderer` 完成所有繁重的工作。 + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +运行程序后,你会在工作目录看到名为 `output.png` 的文件。它包含使用粗斜体样式渲染的 `` 元素,我们已经拥有了一个可以保存的有效 HTML 结构。 + +> **专业提示:** 如果需要完整的 HTML 骨架(``、`
` 等),Aspose.HTML 在保存文档时会自动生成,即使你只添加了 body 内容。 + +## 第二步:实现 **自定义资源处理程序** – 将 HTML 捕获到内存 + +*资源处理程序* 告诉 Aspose.HTML 将每个资源(HTML、CSS、图片等)写到哪里。通过重写 `HandleResource`,我们可以将 HTML 输出定向到 `MemoryStream` 而不是文件。 + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**为何使用自定义处理程序:** +- **性能:** 无磁盘 I/O,全部驻留在 RAM 中。 +- **安全性:** 没有可能被暴露的临时文件。 +- **灵活性:** 之后可以将流传递给响应、数据库或其他 API。 + +## 第三步:使用处理程序保存文档 – **以编程方式生成 HTML** 的核心 + +现在把文档和处理程序绑定在一起。当 `htmlDoc.Save(handler)` 执行时,Aspose.HTML 会调用 `HandleResource`,把我们提供的流作为写入目标。 + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +此时 `handler.HtmlStream` 已包含原始的 HTML 字节。没有任何内容写入磁盘,你可以根据需要多次复用该流(只需记得重置其位置)。 + +## 第四步:从内存读取生成的 HTML – 验证输出 + +为了证明一切正常,我们将流的位置重置到起始点并读取文本。 + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**预期输出** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +如果看到上面的标记,恭喜你——已经成功使用 Aspose.HTML 和 **自定义资源处理程序** **以编程方式生成 HTML**。 + +## 常见变体与边缘情况 + +### 处理 CSS 或图片 + +演示代码通过返回 `Stream.Null` 忽略了非 HTML 资源。在实际项目中,你可能需要捕获 CSS 文件或图片: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### 为多次保存复用同一处理程序 + +如果需要在循环中生成多个 HTML 片段,请在每次迭代时创建新的 `MemoryHtmlHandler`,或清空已有流: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### 异步保存(Aspose.HTML 23.4+) + +新版支持异步保存: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +记得使用 `await` 并将方法声明为 `async`。 + +## 完整工作示例 + +下面是可以直接复制到控制台应用的完整程序。它包含了我们讨论的所有部分,并附带了一些说明性注释。 + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +运行程序(`dotnet run`),你应该会在控制台看到与前面示例完全相同的 HTML 输出。 + +## 结论 + +我们已经演示了如何使用 Aspose.HTML **创建 HTML 文档 C#**,通过 **自定义资源处理程序** 捕获输出,并 **以编程方式生成 HTML** 而无需触及文件系统。该模式具备可扩展性——无论是构建邮件模板、即时报告,还是返回 HTML 片段的微服务,都适用。 + +下一步可以尝试通过处理程序添加 CSS 样式表,或直接将 HTML 流写入 ASP.NET Core 响应(`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`)。你也可以将输出接入 PDF 转换器或 HTML‑to‑image 库,以实现更丰富的工作流。 + +对图片处理、异步保存或与其他库集成有疑问?欢迎留言,祝编码愉快! + +{{< /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/rendering-html-documents/_index.md b/html/czech/net/rendering-html-documents/_index.md index 5e42f8047..eb0155906 100644 --- a/html/czech/net/rendering-html-documents/_index.md +++ b/html/czech/net/rendering-html-documents/_index.md @@ -66,9 +66,16 @@ Naučte se, jak pomocí Aspose.HTML v .NET převést HTML do PNG pomocí podrobn ### [Jak vykreslit HTML do PNG pomocí Aspose – Kompletní průvodce](./how-to-render-html-to-png-with-aspose-complete-guide/) Kompletní návod, jak pomocí Aspose.HTML v .NET převést HTML soubory do PNG s podrobnými kroky a tipy. + ### [Vytvořte PNG z HTML – Kompletní průvodce renderováním v C#](./create-png-from-html-full-c-rendering-guide/) Naučte se, jak pomocí Aspose.HTML pro .NET převést HTML do PNG pomocí kompletního C# průvodce. +### [Vykreslení HTML do obrázku v C# – Kompletní průvodce krok za krokem](./render-html-to-image-in-c-complete-step-by-step-guide/) +Kompletní průvodce v C#, jak pomocí Aspose.HTML převést HTML do obrázku s podrobnými ukázkami a tipy. + +### [Renderujte HTML do PNG v C# – krok za krokem průvodce](./render-html-to-png-in-c-step-by-step-guide/) +Naučte se pomocí Aspose.HTML v C# převést HTML soubory do PNG pomocí podrobného krok‑za‑krokem průvodce. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/czech/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/czech/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3e08e4618 --- /dev/null +++ b/html/czech/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-03-14 +description: Rychle renderujte HTML do obrázku pomocí Aspose.HTML. Naučte se, jak + převést webovou stránku na PNG, nastavit styl písma a uložit vykreslený obrázek + pomocí několika řádků C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: cs +og_description: Vykreslete HTML do obrázku pomocí Aspose.HTML. Tento tutoriál ukazuje, + jak převést webovou stránku na PNG, nastavit styl písma a uložit vykreslený obrázek + v C#. +og_title: Vykreslení HTML do obrázku v C# – Rychlý a snadný návod +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Vykreslení HTML do obrázku v C# – Kompletní průvodce krok za krokem +url: /cs/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML do obrázku – Kompletní C# tutoriál + +Už jste někdy potřebovali **renderovat HTML do obrázku**, ale nebyli jste si jisti, kterou knihovnu zvolit? Nejste v tom sami. V mnoha scénářích web‑automatizace nebo reportování skončíte s živou stránkou, kterou chcete archivovat jako PNG, JPEG nebo dokonce BMP. Dobrou zprávou je, že Aspose.HTML to dělá hračkou a umožňuje vám **převést webovou stránku na PNG** pomocí několika řádků kódu. + +V tomto průvodci projdeme celý proces: od instalace balíčku Aspose.HTML, načtení vzdálené URL, úpravy možností renderování (včetně toho, jak **nastavit styl písma**), až po **uložení vykresleného obrázku** na disk. Na konci budete mít připravenou konzolovou aplikaci, která vytvoří ostrý snímek libovolné webové stránky. + +## Co budete potřebovat + +| Požadavek | Důvod | +|--------------|--------| +| .NET 6.0 SDK nebo novější | Aspose.HTML cílí na .NET Standard 2.0+, takže .NET 6 vám poskytuje nejnovější runtime. | +| Visual Studio 2022 (nebo VS Code) | Pohodlné IDE urychluje ladění. | +| Aspose.HTML for .NET NuGet package | Toto je engine, který provádí těžkou práci. | +| Platná licence Aspose.HTML (volitelné) | Bez licence se na výstupním obrázku objeví vodoznak. | + +Balíček můžete získat přes CLI: + +```bash +dotnet add package Aspose.HTML +``` + +Pokud dáváte přednost GUI, stačí vyhledat „Aspose.HTML“ v NuGet Package Manageru. + +--- + +## Krok 1: Načtěte webovou stránku, kterou chcete rasterizovat + +První věc, kterou musíte udělat, je poskytnout Aspose.HTML zdrojový dokument. Může to být lokální soubor, řetězec nebo vzdálená URL. Ve většině reálných scénářů budete pracovat s živým webem, takže **převést webovou stránku na PNG** uděláme tím, že ukážeme na `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Proč je to důležité:** Načtení stránky jako `HtmlDocument` vám dává plný přístup k DOM, což znamená, že můžete injektovat CSS, manipulovat s rozvržením nebo dokonce spustit JavaScript před rasterizací. + +## Krok 2: Nakonfigurujte možnosti renderování obrázku + +Nyní, když je HTML v paměti, musíme rendereru říct, jak má vypadat finální obrázek. Zde můžete **nastavit styl písma**, povolit antialiasing nebo upravit DPI. Níže je solidní výchozí konfigurace, která vyvažuje kvalitu a rychlost. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Tip:** Pokud potřebujete jen normální tloušťku, vynechte příznaky `WebFontStyle`. Pro nadpisy můžete použít jen `WebFontStyle.Bold`, zatímco popisky mohou využívat `WebFontStyle.Italic`. + +## Krok 3: Vykreslete stránku a **uložte vykreslený obrázek** jako PNG + +S dokumentem a nastavením připravenými je posledním krokem vytvořit instanci `ImageRenderer` a zapsat výstupní soubor. Blok `using` zajistí, že prostředky jsou uvolněny okamžitě. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +Po spuštění programu by se ve složce projektu měl objevit soubor `page.png` obsahující věrný snímek *example.com*. Otevřete jej v libovolném prohlížeči obrázků a všimnete si tučného‑kurzívy stylu, který jsme požadovali dříve. + +### Očekávaný výstup + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +PNG bude mít přibližně 800 × 600 px (v závislosti na původních rozměrech stránky) s hladkými hranami díky antialiasingu. + +## Kompletní funkční příklad + +Sestavte vše dohromady, zde je minimální konzolová aplikace, kterou můžete zkopírovat do `Program.cs`. Kompiluje se a běží ihned. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Spusťte ji pomocí: + +```bash +dotnet run +``` + +…a budete mít čerstvé PNG připravené k archivaci, e‑mailování nebo vložení do zprávy. + +## Varianty a okrajové případy + +### 1. Převod na JPEG místo PNG + +Pokud váš downstream systém preferuje JPEG (menší velikost souboru, ztrátová komprese), stačí změnit příponu souboru v `Save`. Aspose.HTML automaticky detekuje formát podle cesty. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +Kvalitu komprese můžete také upravit pomocí `JpegRenderingOptions`. + +### 2. Změna rozměrů obrázku + +Někdy potřebujete miniaturu místo plno‑velikostního snímku. Nastavte `ImageSize` v možnostech: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Zpracování stránek chráněných autentizací + +Pokud cílová URL vyžaduje základní autentizaci, poskytněte přihlašovací údaje přes `HttpWebRequest` před vytvořením `HtmlDocument`. Alternativně si HTML stáhněte sami (pomocí `HttpClient`) a předávejte jej jako řetězec: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Použití vlastního písma + +Aspose.HTML může vkládat lokální písma. Zaregistrujte složku s fonty před načtením dokumentu: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Nyní se jakékoli deklarace `font-family` na stránce vyřeší na vaše vlastní soubory. + +### 5. Renderování více stránek ve smyčce + +Pokud potřebujete dávkově zpracovat seznam URL: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +## Časté problémy a jak je řešit + +| Problém | Pravděpodobná příčina | Řešení | +|---------|-----------------------|--------| +| Prázdný PNG soubor | `HtmlDocument.IsEmpty` true (stránka se nepodařilo načíst) | Ověřte URL, zkontrolujte síťový proxy, ujistěte se, že je povolen TLS 1.2. | +| Poškozený text na Linuxu | Hintování fontů je vypnuto | Nastavte `renderingOptions.TextOptions.UseHinting = true;`. | +| Vodoznak na výstupu | Nebyla poskytnuta licence | Zaregistrujte dočasnou nebo plnou licenci pomocí `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Nízké rozlišení obrázku | Výchozí DPI 96 není dostatečné pro tisk | Zvyšte `renderingOptions.DpiX` a `DpiY` na 150‑300. | + +## 🎉 Závěr + +Právě jsme probrali vše, co potřebujete k **renderování HTML do obrázku** s Aspose.HTML v C#. Od načtení vzdálené stránky, konfigurace antialiasingu a **nastavení stylu písma**, až po konečné **uložení vykresleného obrázku** jako PNG, celý workflow se vejde do několika stručných kroků. + +Nyní můžete **převést webovou stránku na PNG** za běhu, vkládat snímky do reportů nebo generovat miniatury pro katalog – bez nutnosti automatizace prohlížeče. + +### Co dál? + +- Experimentujte s **convert html to png** pro různé velikosti obrazovky (mobile vs desktop). +- Vyzkoušejte export do PDF pomocí `PdfRenderer`, pokud potřebujete tisknutelný dokument. +- Prozkoumejte Aspose.HTML DOM manipulation API a injektujte vodoznaky nebo vlastní CSS před renderováním. + +Máte otázky ohledně okrajových případů, licencování nebo ladění výkonu? Zanechte komentář níže a šťastné kódování! + +--- + + + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/czech/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/czech/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..6d0b669ed --- /dev/null +++ b/html/czech/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-03-14 +description: Rychle renderujte HTML do PNG pomocí Aspose.HTML. Naučte se, jak generovat + PNG z HTML, použít tučný kurzívní styl písma a uložit HTML do proudu. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: cs +og_description: Vykreslete HTML do PNG pomocí Aspose.HTML. Tento průvodce ukazuje, + jak generovat PNG z HTML, použít tučný kurzívní styl písma a uložit HTML do proudu. +og_title: Vykreslení HTML do PNG v C# – Kompletní programovací průvodce +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Vykreslení HTML do PNG v C# – průvodce krok za krokem +url: /cs/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +produce final output.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vykreslení HTML do PNG v C# – Kompletní programovací průvodce + +Už jste někdy potřebovali **render HTML to PNG**, ale nebyli jste si jisti, která knihovna vám poskytne pixel‑dokonalé výsledky? Nejste sami. V mnoha pipelinech web‑na‑obrázek vývojáři narazí na chybějící fonty, rozmazaný text nebo na děsivou otázku „jak zachytit HTML, aniž bych ho nejprve zapisoval na disk?“ + +Zde je pravda: Aspose.HTML dělá celý proces hračkou. V tomto tutoriálu **vygenerujeme PNG z HTML**, použijeme **tučný kurzívní styl písma** a dokonce **uložíme HTML do streamu**, abyste vše mohli držet v paměti. Na konci budete mít připravenou konzolovou aplikaci, která z malého úryvku HTML vytvoří ostrý PNG soubor. + +--- + +## Co budete potřebovat + +- **.NET 6+** (kód funguje jak s .NET Core, tak s .NET Framework) +- **Aspose.HTML for .NET** NuGet balíček – `Install-Package Aspose.HTML` +- Oblíbené IDE (Visual Studio, Rider nebo VS Code) – jakékoliv bude stačit. + +Žádné extra fonty, žádné externí nástroje a rozhodně žádné dočasné soubory. Pouze čistý C#. + +--- + +## Krok 1: Vytvořte jednoduchý HTML dokument + +První, co uděláme, je vytvořit HTML dokument v paměti. Představte si ho jako virtuální webovou stránku, která existuje jen uvnitř vašeho procesu. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Proč je to důležité:** Konstrukcí DOM programově se vyhnete zátěži souborového I/O a můžete za běhu vkládat dynamická data. Třída `HtmlDocument` je vstupním bodem pro každou operaci Aspose.HTML. + +--- + +## Krok 2: Uložte HTML do streamu + +Místo zápisu značkování na disk jej zachytíme v uživatelském `ResourceHandler`. Toto je část workflow **save html to stream**. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Tip:** `MemoryHandler` je malý, ale výkonný. Pokud později potřebujete vložit obrázky, CSS nebo fonty, stačí rozšířit `HandleResource`, aby vracel příslušné streamy. + +--- + +## Krok 3: Nastavte tučný kurzívní styl písma + +Když vykreslujete text, často chcete, aby vypadal přesně jako v prohlížeči. Aspose.HTML vám umožní nastavit **bold italic font style** přímo v možnostech vykreslování. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **Co se děje:** +> * `UseAntialiasing` vyhlazuje hrany tvarů. +> * `UseHinting` zlepšuje umístění glyfů, což je klíčové pro malý text. +> * `FontStyle` kombinuje příznaky `Bold` a `Italic`, takže každý kus textu v dokumentu dědí tento styl, pokud není přepsán. + +--- + +## Krok 4: Vykreslete HTML dokument do PNG obrázku + +Teď ta zábavná část – převést HTML na soubor obrázku. `ImageRenderer` udělá veškerou těžkou práci. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Pokud spustíte program, uvidíte soubor pojmenovaný `output.png` v pracovním adresáři. Obsahuje nadpis `` již máme platnou HTML strukturu připravenou k uložení. + +> **Tip:** Pokud potřebujete kompletní HTML kostru (``, `
` atd.), Aspose.HTML ji automaticky vygeneruje při uložení dokumentu, i když jste přidali jen obsah těla. + +## Krok 2: Implementace **Custom Resource Handler** – Zachycení HTML v paměti + +*Resource handler* říká Aspose.HTML, kam zapisovat každý zdroj (HTML, CSS, obrázky atd.). Přepsáním `HandleResource` můžeme směrovat výstup HTML do `MemoryStream` místo souboru. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Proč používáme vlastní handler:** +- **Výkon:** Žádné diskové I/O, vše zůstává v RAM. +- **Bezpečnost:** Žádné dočasné soubory, které by mohly být odhaleny. +- **Flexibilita:** Později můžete stream přesměrovat do odpovědi, databáze nebo jiného API. + +## Krok 3: Uložení dokumentu pomocí handleru – Srdce **Generate HTML Programmatically** + +Nyní propojujeme dokument a handler. Když se spustí `htmlDoc.Save(handler)`, Aspose.HTML zavolá `HandleResource` a předá nám stream, do kterého zapisovat. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +V tomto okamžiku `handler.HtmlStream` obsahuje surové HTML bajty. Nic nebylo zapsáno na disk a můžete stream používat opakovaně (jen nezapomeňte resetovat jeho pozici). + +## Krok 4: Přečtení vygenerovaného HTML z paměti – Ověření výstupu + +Abychom dokázali, že vše funguje, resetujeme pozici streamu na začátek a přečteme text zpět. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Očekávaný výstup** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Pokud vidíte výše uvedený markup, gratulujeme—úspěšně jste **generate html programmatically** pomocí Aspose.HTML a **custom resource handler**. + +## Běžné varianty a okrajové případy + +### Zpracování CSS nebo obrázků + +Demo ignoruje ne‑HTML zdroje tím, že vrací `Stream.Null`. V reálném scénáři můžete chtít zachytit také soubory CSS nebo obrázky: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Opětovné použití stejného handleru pro více uložení + +Pokud potřebujete v cyklu generovat několik HTML úryvků, vytvořte pro každou iteraci nový `MemoryHtmlHandler` nebo vyčistěte existující stream: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Asynchronní ukládání (Aspose.HTML 23.4+) + +Novější verze podporují asynchronní ukládání: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Nezapomeňte použít `await` a označit vaši metodu jako `async`. + +## Kompletní funkční příklad + +Níže je kompletní program, který můžete zkopírovat a vložit do konzolové aplikace. Obsahuje všechny části, o kterých jsme mluvili, a několik komentářů pro přehlednost. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Spusťte program (`dotnet run`) a měli byste vidět HTML vytištěné do konzole, přesně tak, jak bylo ukázáno dříve. + +## Závěr + +Právě jsme ukázali, jak **create HTML document C#** pomocí Aspose.HTML, zachytit výstup pomocí **custom resource handler** a **generate HTML programmatically** bez zásahu do souborového systému. Tento vzor je škálovatelný – ať už vytváříte e‑mailové šablony, reporty za běhu nebo mikro‑službu, která vrací HTML úryvky. + +Další kroky? Zkuste přidat CSS stylopis přes handler, nebo streamovat HTML přímo do odpovědi ASP.NET Core (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Můžete také výstup připojit k PDF konvertoru nebo knihovně HTML‑to‑image pro komplexnější workflow. + +Máte otázky ohledně zpracování obrázků, asynchronního ukládání nebo integrace s dalšími knihovnami? Zanechte komentář a šťastné programování! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/dutch/net/rendering-html-documents/_index.md b/html/dutch/net/rendering-html-documents/_index.md index 088e7bab1..6b20ccbd4 100644 --- a/html/dutch/net/rendering-html-documents/_index.md +++ b/html/dutch/net/rendering-html-documents/_index.md @@ -60,6 +60,10 @@ Leer hoe u met Aspose.HTML HTML naar PNG kunt renderen met een duidelijke stap Leer stap voor stap hoe u HTML naar PNG converteert met Aspose.HTML in deze volledige gids. ### [PNG maken vanuit HTML – Volledige C# Renderinggids](./create-png-from-html-full-c-rendering-guide/) Leer hoe u met Aspose.HTML voor .NET HTML naar PNG converteert met een volledige C#-renderinggids. +### [HTML renderen naar afbeelding in C# – Complete stapsgewijze gids](./render-html-to-image-in-c-complete-step-by-step-guide/) +Leer hoe u HTML naar afbeelding converteert met C# en Aspose.HTML in deze volledige gids. +### [HTML renderen naar PNG in C# – Stapsgewijze gids](./render-html-to-png-in-c-step-by-step-guide/) +Leer stap voor stap hoe u HTML naar PNG converteert in C# met Aspose.HTML. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/dutch/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/dutch/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..f14346273 --- /dev/null +++ b/html/dutch/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-03-14 +description: Render HTML snel naar afbeelding met Aspose.HTML. Leer hoe je een webpagina + naar PNG converteert, de lettertype‑stijl instelt en de gerenderde afbeelding opslaat + in slechts een paar regels C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: nl +og_description: Render HTML naar afbeelding met Aspose.HTML. Deze tutorial laat zien + hoe je een webpagina naar PNG converteert, de lettertype‑stijl instelt en de gerenderde + afbeelding opslaat in C#. +og_title: HTML renderen naar afbeelding in C# – Snelle en eenvoudige gids +tags: +- C# +- Aspose.HTML +- Image Rendering +title: HTML renderen naar afbeelding in C# – Complete stap‑voor‑stap gids +url: /nl/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML naar Afbeelding – Complete C# Tutorial + +Heb je ooit **HTML naar afbeelding renderen** nodig gehad maar wist je niet welke bibliotheek je moest kiezen? Je bent niet de enige. In veel web‑automatisering- of rapportagescenario's eindig je met een live pagina die je wilt archiveren als een PNG, JPEG of zelfs een BMP. Het goede nieuws is dat Aspose.HTML dit kinderspel maakt, waardoor je **webpagina naar PNG converteren** met slechts een paar regels code. + +In deze gids lopen we het volledige proces door: van het installeren van het Aspose.HTML‑pakket, het laden van een externe URL, het aanpassen van renderopties (inclusief hoe je **fontstijl instelt**), tot uiteindelijk **gerenderde afbeelding opslaan** op schijf. Aan het einde heb je een kant‑klaar console‑applicatie die een scherpe screenshot van elke webpagina produceert. + +## Wat je nodig hebt + +| Voorwaarde | Reden | +|--------------|--------| +| .NET 6.0 SDK of later | Aspose.HTML richt zich op .NET Standard 2.0+, dus .NET 6 geeft je de nieuwste runtime. | +| Visual Studio 2022 (of VS Code) | Een comfortabele IDE versnelt het debuggen. | +| Aspose.HTML for .NET NuGet‑pakket | Dit is de motor die het zware werk doet. | +| Een geldige Aspose.HTML‑licentie (optioneel) | Zonder licentie krijg je een watermerk op de uitvoerafbeelding. | + +Je kunt het pakket ophalen via de CLI: + +```bash +dotnet add package Aspose.HTML +``` + +Als je de GUI verkiest, zoek dan gewoon naar “Aspose.HTML” in de NuGet Package Manager. + +--- + +## Stap 1: Laad de webpagina die je wilt rasteren + +Het eerste wat je moet doen is Aspose.HTML een brondocument geven. Dit kan een lokaal bestand, een string of een externe URL zijn. In de meeste praktijksituaties werk je met een live site, dus laten we **webpagina naar PNG converteren** door te wijzen naar `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Waarom dit belangrijk is:** Het laden van de pagina als een `HtmlDocument` geeft je volledige toegang tot de DOM, wat betekent dat je CSS kunt injecteren, de lay-out kunt manipuleren, of zelfs JavaScript kunt uitvoeren voordat je rastert. + +--- + +## Stap 2: Configureer afbeeldingsrenderopties + +Nu de HTML in het geheugen staat, moeten we de renderer vertellen hoe we de uiteindelijke afbeelding willen hebben. Hier kun je **fontstijl instellen**, antialiasing inschakelen, of de DPI aanpassen. Hieronder staat een degelijke standaardconfiguratie die kwaliteit en snelheid in balans brengt. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Pro tip:** Als je alleen een normale dikte nodig hebt, laat dan de `WebFontStyle`‑vlaggen weg. Voor koppen wil je misschien alleen `WebFontStyle.Bold`, terwijl bijschriften `WebFontStyle.Italic` kunnen gebruiken. + +--- + +## Stap 3: Render de pagina en **gerenderde afbeelding opslaan** als PNG + +Met het document en de opties klaar, is de laatste stap het instantieren van `ImageRenderer` en het schrijven van het uitvoerbestand. Het `using`‑blok zorgt ervoor dat bronnen direct worden vrijgegeven. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +Wanneer je het programma uitvoert, zou je een `page.png`‑bestand in je projectmap moeten zien dat een getrouwe snapshot van *example.com* bevat. Open het met een willekeurige afbeeldingsviewer en je zult de vet‑cursieve opmaak zien die we eerder hebben gevraagd. + +### Verwachte output + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +De PNG zal ongeveer 800 × 600 px zijn (afhankelijk van de oorspronkelijke afmetingen van de pagina) met gladde randen dankzij antialiasing. + +--- + +## Volledig werkend voorbeeld + +Alles bij elkaar genomen, hier is een minimale console‑app die je kunt kopiëren‑plakken in `Program.cs`. Hij compileert en draait direct. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Voer het uit met: + +```bash +dotnet run +``` + +…en je hebt een verse PNG klaar voor archivering, e‑mailen, of insluiten in een rapport. + +--- + +## Variaties & Randgevallen + +### 1. Converteren naar JPEG in plaats van PNG + +Als je downstream‑systeem JPEG verkiest (kleinere bestandsgrootte, verliesgevende compressie), wijzig dan gewoon de bestandsextensie in `Save`. Aspose.HTML detecteert automatisch het formaat vanuit het pad. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +Je kunt ook de compressiekwaliteit aanpassen via `JpegRenderingOptions`. + +### 2. Afbeeldingsafmetingen wijzigen + +Soms heb je een thumbnail nodig in plaats van een volledige screenshot. Stel `ImageSize` in op de opties: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Pagina's met authenticatie afhandelen + +Als de doel‑URL basis‑authenticatie vereist, lever dan de inloggegevens via `HttpWebRequest` vóór het aanmaken van het `HtmlDocument`. Als alternatief kun je de HTML zelf downloaden (met `HttpClient`) en als een string aanleveren: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Een aangepast lettertype gebruiken + +Aspose.HTML kan lokale lettertypen insluiten. Registreer de lettertype‑map vóór het laden van het document: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Nu zullen alle `font-family`‑verklaringen in de pagina naar jouw aangepaste bestanden verwijzen. + +### 5. Meerdere pagina's in een lus renderen + +Als je een lijst met URL's in batch wilt verwerken: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Veelvoorkomende valkuilen & hoe ze te vermijden + +| Symptoom | Waarschijnlijke oorzaak | Oplossing | +|----------|--------------------------|-----------| +| Lege PNG‑file | `HtmlDocument.IsEmpty` true (pagina kon niet geladen worden) | Controleer de URL, controleer netwerk‑proxy, zorg dat TLS 1.2 is ingeschakeld. | +| Vervormde tekst op Linux | Lettertype‑hinting uitgeschakeld | Stel `renderingOptions.TextOptions.UseHinting = true;` in. | +| Watermerk op output | Geen licentie opgegeven | Registreer een tijdelijke of volledige licentie via `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Lage resolutie afbeelding | Standaard DPI 96 is onvoldoende voor afdrukken | Verhoog `renderingOptions.DpiX` en `DpiY` naar 150‑300. | + +--- + +## 🎉 Conclusie + +We hebben zojuist alles behandeld wat je nodig hebt om **HTML naar afbeelding te renderen** met Aspose.HTML in C#. Van het laden van een externe pagina, het configureren van antialiasing en **fontstijl instellen**, tot uiteindelijk **gerenderde afbeelding opslaan** als een PNG, de volledige workflow past netjes in een paar beknopte stappen. + +Nu kun je **webpagina naar PNG converteren** on‑the‑fly, screenshots in rapporten insluiten, of thumbnails voor een catalogus genereren — zonder browserautomatisering. + +### Wat is het volgende? + +- Experimenteer met **html naar png converteren** voor verschillende schermgroottes (mobiel vs desktop). +- Probeer te exporteren naar PDF met `PdfRenderer` als je een afdrukbaar document nodig hebt. +- Duik in de DOM‑manipulatie‑API's van Aspose.HTML om watermerken of aangepaste CSS in te voegen vóór het renderen. + +Heb je vragen over randgevallen, licenties, of prestatie‑afstemming? Laat een reactie achter hieronder, en happy coding! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/dutch/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..3eca1a586 --- /dev/null +++ b/html/dutch/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2026-03-14 +description: Render HTML snel naar PNG met Aspose.HTML. Leer hoe je PNG uit HTML genereert, + vet en cursief lettertype toepast en HTML naar een stream opslaat. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: nl +og_description: Render HTML naar PNG met Aspose.HTML. Deze gids laat zien hoe je PNG + genereert vanuit HTML, vet en cursief lettertype gebruikt, en HTML opslaat naar + een stream. +og_title: HTML renderen naar PNG in C# – Complete programmeerhandleiding +tags: +- Aspose.HTML +- C# +- Image Rendering +title: HTML renderen naar PNG in C# – Stapsgewijze handleiding +url: /nl/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML naar PNG in C# – Complete Programmeerhandleiding + +Heb je ooit **HTML naar PNG moeten renderen** maar wist je niet welke bibliotheek pixel‑perfecte resultaten levert? Je bent niet de enige. In veel web‑naar‑afbeelding‑pijplijnen lopen ontwikkelaars tegen ontbrekende lettertypen, onscherpe tekst of de gevreesde “hoe capture ik de HTML zonder deze eerst naar schijf te schrijven?” aan. + +Het punt is: Aspose.HTML maakt het hele proces een eitje. In deze tutorial zullen we **PNG genereren vanuit HTML**, een **vet cursief lettertype‑stijl** toepassen, en zelfs **HTML naar een stream opslaan** zodat je alles in het geheugen kunt houden. Aan het einde heb je een kant‑klaar console‑appje dat een klein HTML‑fragment omzet in een scherpe PNG‑afbeelding. + +--- + +## Wat je nodig hebt + +- **.NET 6+** (de code werkt zowel met .NET Core als .NET Framework) +- **Aspose.HTML for .NET** NuGet‑pakket – `Install-Package Aspose.HTML` +- Een favoriete IDE (Visual Studio, Rider, of VS Code) – elke werkt. + +Geen extra lettertypen, geen externe tools, en zeker geen tijdelijke bestanden. Gewoon pure C#. + +--- + +## Stap 1: Maak een eenvoudig HTML‑document + +Het eerste dat we doen is een in‑memory HTML‑document opbouwen. Beschouw het als een virtuele webpagina die alleen binnen je proces bestaat. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Waarom dit belangrijk is:** Door het DOM programmatisch te construeren vermijd je bestands‑IO‑overhead en kun je dynamische gegevens on‑the‑fly injecteren. De `HtmlDocument`‑klasse is het toegangspunt voor elke Aspose.HTML‑bewerking. + +--- + +## Stap 2: Sla HTML op naar een stream + +In plaats van de markup naar schijf te schrijven, vangen we deze op in een aangepaste `ResourceHandler`. Dit is het **save html to stream**‑deel van de workflow. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Pro‑tip:** De `MemoryHandler` is klein maar krachtig. Als je later afbeeldingen, CSS of lettertypen moet insluiten, breid dan `HandleResource` uit om de juiste streams te retourneren. + +--- + +## Stap 3: Configureer vet cursief lettertype‑stijl + +Wanneer je tekst rendert, wil je vaak dat deze er precies zo uitziet als in een browser. Aspose.HTML laat je **bold italic font style** direct instellen via de rendering‑opties. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **Wat er gebeurt:** +> * `UseAntialiasing` verzacht de randen van vormen. +> * `UseHinting` verbetert de positionering van glyphs, wat cruciaal is voor kleine tekst. +> * `FontStyle` combineert de `Bold`‑ en `Italic`‑vlaggen, zodat elk stuk tekst in het document die stijl erft tenzij overschreven. + +--- + +## Stap 4: Render het HTML‑document naar een PNG‑afbeelding + +Nu het leuke deel – het HTML‑document omzetten naar een afbeeldingsbestand. De `ImageRenderer` doet al het zware werk. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Als je het programma uitvoert, zie je een bestand genaamd `output.png` in de werkmap. Het bevat de ``‑element toe te voegen, hebben we al een geldige HTML‑structuur die klaar is om opgeslagen te worden. + +> **Pro tip:** Als je een volledige HTML‑skelet (``, `
`, etc.) nodig hebt, genereert Aspose.HTML die automatisch bij het opslaan van het document, zelfs als je alleen body‑content hebt toegevoegd. + +## Stap 2: Implementeer een **aangepaste resource‑handler** – HTML in‑geheugen vastleggen + +Een *resource‑handler* vertelt Aspose.HTML waar elke resource (HTML, CSS, afbeeldingen, etc.) moet worden weggeschreven. Door `HandleResource` te overschrijven kunnen we de HTML‑output naar een `MemoryStream` sturen in plaats van naar een bestand. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Waarom we een aangepaste handler gebruiken:** +- **Performance:** Geen schijf‑I/O, alles blijft in RAM. +- **Beveiliging:** Geen tijdelijke bestanden die blootgesteld kunnen worden. +- **Flexibiliteit:** Je kunt de stream later doorsturen naar een response, een database of een andere API. + +## Stap 3: Sla het document op met de handler – Het hart van **Generate HTML Programmatically** + +Nu koppelen we het document en de handler. Wanneer `htmlDoc.Save(handler)` wordt uitgevoerd, roept Aspose.HTML `HandleResource` aan en geeft ons de stream om in te schrijven. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +Op dit moment bevat `handler.HtmlStream` de ruwe HTML‑bytes. Er is niets naar schijf geschreven, en je kunt de stream zo vaak hergebruiken als je wilt (vergeet alleen niet de positie te resetten). + +## Stap 4: Lees de gegenereerde HTML uit het geheugen – Controleer de output + +Om te bewijzen dat alles werkt, resetten we de positie van de stream naar het begin en lezen we de tekst terug. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Verwachte output** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Als je de markup hierboven ziet, gefeliciteerd — je hebt succesvol **generate html programmatically** uitgevoerd met Aspose.HTML en een **custom resource handler**. + +## Veelvoorkomende variaties & randgevallen + +### CSS of afbeeldingen verwerken + +De demo negeert niet‑HTML‑resources door `Stream.Null` te retourneren. In een real‑world scenario wil je misschien CSS‑bestanden of afbeeldingen ook vastleggen: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Dezelfde handler hergebruiken voor meerdere saves + +Als je meerdere HTML‑fragmenten in een lus moet genereren, maak je elke iteratie een nieuwe `MemoryHtmlHandler` aan of maak je de bestaande stream leeg: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Asynchroon opslaan (Aspose.HTML 23.4+) + +Nieuwere versies ondersteunen asynchroon opslaan: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Vergeet niet te `await` en je methode `async` te maken. + +## Volledig werkend voorbeeld + +Hieronder staat het complete programma dat je kunt kopiëren en plakken in een console‑app. Het bevat alle besproken onderdelen, plus een paar commentaren voor de duidelijkheid. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Voer het programma uit (`dotnet run`) en je zou de HTML in de console moeten zien, precies zoals eerder getoond. + +## Conclusie + +We hebben zojuist laten zien hoe je **HTML document C#** maakt met Aspose.HTML, de output vastlegt met een **custom resource handler**, en **HTML programmatically** genereert zonder het bestandssysteem aan te raken. Het patroon schaalt — of je nu e‑mail‑templates, on‑the‑fly rapporten of een micro‑service bouwt die HTML‑fragmenten retourneert. + +Volgende stappen? Probeer een CSS‑stylesheet toe te voegen via de handler, of stream de HTML direct naar een ASP.NET Core‑response (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Je kunt de output ook doorgeven aan een PDF‑converter of een HTML‑naar‑afbeelding‑bibliotheek voor uitgebreidere workflows. + +Heb je vragen over het verwerken van afbeeldingen, asynchroon opslaan, of integratie met andere libraries? Laat een reactie achter, en happy coding! + +{{< /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/rendering-html-documents/_index.md b/html/english/net/rendering-html-documents/_index.md index e7f281cce..644263479 100644 --- a/html/english/net/rendering-html-documents/_index.md +++ b/html/english/net/rendering-html-documents/_index.md @@ -60,6 +60,11 @@ Learn how to control rendering timeouts effectively in Aspose.HTML for .NET. Exp Learn to render multiple HTML documents using Aspose.HTML for .NET. Boost your document processing capabilities with this powerful library. ### [Render SVG Doc as PNG in .NET with Aspose.HTML](./render-svg-doc-as-png/) Unlock the power of Aspose.HTML for .NET! Learn how to Render SVG Doc as PNG effortlessly. Dive into step-by-step examples and FAQs. Get started now! +### [Render HTML to Image in C# – Complete Step‑by‑Step Guide](./render-html-to-image-in-c-complete-step-by-step-guide/) +Step‑by‑step guide to render HTML to images using C# and Aspose.HTML for .NET, covering setup, options, and best practices. +### [Render HTML to PNG in C# – Step‑by‑Step Guide](./render-html-to-png-in-c-step-by-step-guide/) +Step‑by‑step guide to render HTML to PNG using C# and Aspose.HTML for .NET, covering setup, options, and best practices. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/english/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/english/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..2cfe592f5 --- /dev/null +++ b/html/english/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-03-14 +description: Render HTML to image quickly using Aspose.HTML. Learn how to convert + webpage to PNG, set font style, and save rendered image in just a few lines of C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: en +og_description: Render HTML to image with Aspose.HTML. This tutorial shows how to + convert webpage to PNG, set font style, and save the rendered image in C#. +og_title: Render HTML to Image in C# – Quick and Easy Guide +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Render HTML to Image in C# – Complete Step‑by‑Step Guide +url: /net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to Image – Complete C# Tutorial + +Ever needed to **render HTML to image** but weren't sure which library to pick? You're not the only one. In many web‑automation or reporting scenarios you end up with a live page that you want to archive as a PNG, JPEG, or even a BMP. The good news is that Aspose.HTML makes this a piece of cake, letting you **convert webpage to PNG** with just a few lines of code. + +In this guide we’ll walk through the entire process: from installing the Aspose.HTML package, loading a remote URL, tweaking rendering options (including how to **set font style**), and finally **save rendered image** to disk. By the end you’ll have a ready‑to‑run console app that produces a crisp screenshot of any web page. + +## What You’ll Need + +Before we dive in, make sure you have: + +| Prerequisite | Reason | +|--------------|--------| +| .NET 6.0 SDK or later | Aspose.HTML targets .NET Standard 2.0+, so .NET 6 gives you the freshest runtime. | +| Visual Studio 2022 (or VS Code) | A comfortable IDE speeds up debugging. | +| Aspose.HTML for .NET NuGet package | This is the engine that does the heavy lifting. | +| A valid Aspose.HTML license (optional) | Without a license you’ll get a watermark on the output image. | + +You can grab the package via the CLI: + +```bash +dotnet add package Aspose.HTML +``` + +If you prefer the GUI, just search for “Aspose.HTML” in the NuGet Package Manager. + +--- + +## Step 1: Load the Web Page You Want to Rasterize + +The first thing you have to do is give Aspose.HTML a source document. It can be a local file, a string, or a remote URL. In most real‑world scenarios you’ll be dealing with a live site, so let’s **convert webpage to PNG** by pointing at `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Why this matters:** Loading the page as an `HtmlDocument` gives you full access to the DOM, which means you can inject CSS, manipulate the layout, or even run JavaScript before rasterizing. + +--- + +## Step 2: Configure Image Rendering Options + +Now that the HTML is in memory, we need to tell the renderer how we want the final picture to look. This is where you can **set font style**, enable antialiasing, or tweak the DPI. Below is a solid default configuration that balances quality and speed. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Pro tip:** If you only need a regular weight, drop the `WebFontStyle` flags. For headlines you might want `WebFontStyle.Bold` alone, while captions could use `WebFontStyle.Italic`. + +--- + +## Step 3: Render the Page and **Save Rendered Image** as PNG + +With the document and options ready, the final step is to instantiate `ImageRenderer` and write the output file. The `using` block ensures resources are released promptly. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +When you run the program, you should see a `page.png` file in your project folder containing a faithful snapshot of *example.com*. Open it with any image viewer and you’ll notice the bold‑italic styling we requested earlier. + +### Expected Output + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +The PNG will be roughly 800 × 600 px (depending on the page’s original dimensions) with smooth edges thanks to antialiasing. + +--- + +## Full Working Example + +Putting everything together, here’s a minimal console app you can copy‑paste into `Program.cs`. It compiles and runs out of the box. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Run it with: + +```bash +dotnet run +``` + +…and you’ll have a fresh PNG ready for archiving, emailing, or embedding in a report. + +--- + +## Variations & Edge Cases + +### 1. Converting to JPEG Instead of PNG + +If your downstream system prefers JPEG (smaller file size, lossy compression), just change the file extension in `Save`. Aspose.HTML automatically detects the format from the path. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +You can also tweak compression quality via `JpegRenderingOptions`. + +### 2. Changing Image Dimensions + +Sometimes you need a thumbnail rather than a full‑size screenshot. Set `ImageSize` on the options: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Handling Authentication‑Protected Pages + +If the target URL requires basic auth, supply credentials through `HttpWebRequest` before creating the `HtmlDocument`. Alternatively, download the HTML yourself (using `HttpClient`) and feed it as a string: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Using a Custom Font + +Aspose.HTML can embed local fonts. Register the font folder before loading the document: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Now any `font-family` declarations in the page will resolve to your custom files. + +### 5. Rendering Multiple Pages in a Loop + +If you need to batch‑process a list of URLs: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Common Pitfalls & How to Avoid Them + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Blank PNG file | `HtmlDocument.IsEmpty` true (page failed to load) | Verify URL, check network proxy, ensure TLS 1.2 is enabled. | +| Garbled text on Linux | Font hinting disabled | Set `renderingOptions.TextOptions.UseHinting = true;`. | +| Watermark on output | No license provided | Register a temporary or full license via `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Low‑resolution image | Default DPI 96 is insufficient for print | Increase `renderingOptions.DpiX` and `DpiY` to 150‑300. | + +--- + +## 🎉 Conclusion + +We’ve just covered everything you need to **render HTML to image** with Aspose.HTML in C#. From loading a remote page, configuring antialiasing and **set font style**, to finally **save rendered image** as a PNG, the whole workflow fits neatly into a few concise steps. + +Now you can **convert webpage to PNG** on the fly, embed screenshots in reports, or generate thumbnails for a catalog—no browser automation required. + +### What’s Next? + +- Experiment with **convert html to png** for different screen sizes (mobile vs desktop). +- Try exporting to PDF using `PdfRenderer` if you need a printable document. +- Dive into Aspose.HTML’s DOM manipulation APIs to inject watermarks or custom CSS before rendering. + +Got questions about edge cases, licensing, or performance tuning? Drop a comment below, and happy coding! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/english/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..edc32694f --- /dev/null +++ b/html/english/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-03-14 +description: Render HTML to PNG quickly with Aspose.HTML. Learn how to generate PNG + from HTML, apply bold italic font style, and save HTML to a stream. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: en +og_description: Render HTML to PNG with Aspose.HTML. This guide shows how to generate + PNG from HTML, use bold italic font style, and save HTML to a stream. +og_title: Render HTML to PNG in C# – Complete Programming Walkthrough +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Render HTML to PNG in C# – Step‑by‑Step Guide +url: /net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG in C# – Complete Programming Walkthrough + +Ever needed to **render HTML to PNG** but weren’t sure which library would give you pixel‑perfect results? You’re not alone. In many web‑to‑image pipelines developers stumble over missing fonts, blurry text, or the dreaded “how do I capture the HTML without writing it to disk first?” + +Here’s the thing: Aspose.HTML makes the whole process a piece of cake. In this tutorial we’ll **generate PNG from HTML**, apply a **bold italic font style**, and even **save HTML to a stream** so you can keep everything in memory. By the end you’ll have a ready‑to‑run console app that turns a tiny HTML snippet into a crisp PNG file. + +--- + +## What You’ll Need + +- **.NET 6+** (the code works with .NET Core and .NET Framework alike) +- **Aspose.HTML for .NET** NuGet package – `Install-Package Aspose.HTML` +- A favorite IDE (Visual Studio, Rider, or VS Code) – any will do. + +No extra fonts, no external tools, and definitely no temporary files. Just pure C#. + +--- + +## Step 1: Create a Simple HTML Document + +The first thing we do is build an in‑memory HTML document. Think of it as a virtual web page that lives only inside your process. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Why this matters:** By constructing the DOM programmatically you avoid file‑IO overhead and you can inject dynamic data on the fly. The `HtmlDocument` class is the entry point for every Aspose.HTML operation. + +--- + +## Step 2: Save HTML to a Stream + +Instead of writing the markup to disk, we capture it in a custom `ResourceHandler`. This is the **save html to stream** part of the workflow. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Pro tip:** The `MemoryHandler` is tiny but powerful. If you later need to embed images, CSS, or fonts, just extend `HandleResource` to return the appropriate streams. + +--- + +## Step 3: Configure Bold Italic Font Style + +When you render text, you often want it to look exactly like it does in a browser. Aspose.HTML lets you set **bold italic font style** directly on the rendering options. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **What’s happening:** +> * `UseAntialiasing` smooths the edges of shapes. +> * `UseHinting` improves glyph positioning, which is crucial for small text. +> * `FontStyle` combines `Bold` and `Italic` flags, so every piece of text in the document inherits that style unless overridden. + +--- + +## Step 4: Render the HTML Document to a PNG Image + +Now the fun part – turning that HTML into an image file. The `ImageRenderer` does all the heavy lifting. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +If you run the program, you’ll see a file called `output.png` in the working directory. It contains the `` element we already have a valid HTML structure ready to be saved. + +> **Pro tip:** If you need a full HTML skeleton (``, `
`, etc.), Aspose.HTML automatically generates it when you save the document, even if you only added body content. + +## Step 2: Implement a **Custom Resource Handler** – Capture HTML In‑Memory + +A *resource handler* tells Aspose.HTML where to write each resource (HTML, CSS, images, etc.). By overriding `HandleResource` we can direct the HTML output to a `MemoryStream` instead of a file. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Why we use a custom handler:** +- **Performance:** No disk I/O, everything stays in RAM. +- **Security:** No temporary files that could be exposed. +- **Flexibility:** You can later pipe the stream to a response, a database, or another API. + +## Step 3: Save the Document Using the Handler – The Heart of **Generate HTML Programmatically** + +Now we tie the document and handler together. When `htmlDoc.Save(handler)` runs, Aspose.HTML calls `HandleResource`, handing us the stream to write into. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +At this point `handler.HtmlStream` contains the raw HTML bytes. Nothing has been written to disk, and you can reuse the stream as many times as you like (just remember to reset its position). + +## Step 4: Read the Generated HTML from Memory – Verify the Output + +To prove that everything worked, we reset the stream’s position to the beginning and read the text back. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Expected output** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +If you see the markup above, congratulations—you’ve successfully **generate html programmatically** using Aspose.HTML and a **custom resource handler**. + +## Common Variations & Edge Cases + +### Handling CSS or Images + +The demo ignores non‑HTML resources by returning `Stream.Null`. In a real‑world scenario you might want to capture CSS files or images as well: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Re‑using the Same Handler for Multiple Saves + +If you need to generate several HTML snippets in a loop, create a fresh `MemoryHtmlHandler` each iteration or clear the existing stream: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Async Saving (Aspose.HTML 23.4+) + +Newer versions support async saving: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Remember to `await` and make your method `async`. + +## Full Working Example + +Below is the complete program you can copy‑paste into a console app. It includes all the pieces we discussed, plus a few comments for clarity. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Run the program (`dotnet run`) and you should see the HTML printed to the console, exactly as shown earlier. + +## Conclusion + +We’ve just shown how to **create HTML document C#** using Aspose.HTML, capture the output with a **custom resource handler**, and **generate HTML programmatically** without touching the file system. The pattern scales—whether you’re building email templates, on‑the‑fly reports, or a micro‑service that returns HTML snippets. + +Next steps? Try adding a CSS stylesheet via the handler, or stream the HTML directly into an ASP.NET Core response (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). You could also plug the output into a PDF converter or an HTML‑to‑image library for richer workflows. + +Got questions about handling images, async saving, or integrating with other libraries? Drop a comment, and happy coding! + +{{< /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/rendering-html-documents/_index.md b/html/french/net/rendering-html-documents/_index.md index b8ecffbeb..ace3e20d0 100644 --- a/html/french/net/rendering-html-documents/_index.md +++ b/html/french/net/rendering-html-documents/_index.md @@ -45,6 +45,7 @@ Apprenez à travailler avec Aspose.HTML pour .NET : manipulez du HTML, converti ### [Comment utiliser Aspose pour rendre du HTML en PNG – Guide étape par étape](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) Apprenez à convertir du HTML en images PNG avec Aspose.HTML pour .NET grâce à ce guide détaillé étape par étape. + ### [Créer un PNG à partir de HTML – Guide complet de rendu C#](./create-png-from-html-full-c-rendering-guide/) Apprenez à générer des images PNG à partir de HTML en utilisant Aspose.HTML pour .NET avec un guide complet en C#. @@ -65,9 +66,16 @@ Libérez la puissance d'Aspose.HTML pour .NET ! Apprenez à restituer un docume ### [Comment rendre HTML au format PNG – Guide complet C#](./how-to-render-html-as-png-complete-c-guide/) Apprenez à convertir du HTML en PNG avec C# grâce à ce guide complet et pratique. + ### [Comment rendre le HTML en PNG avec Aspose – Guide complet](./how-to-render-html-to-png-with-aspose-complete-guide/) Apprenez à convertir du HTML en images PNG avec Aspose grâce à ce guide complet et détaillé. +### [Rendre le HTML en image en C# – Guide complet étape par étape](./render-html-to-image-in-c-complete-step-by-step-guide/) +Apprenez à convertir du HTML en images avec C# grâce à ce guide complet et détaillé. + +### [Rendre le HTML au format PNG en C# – Guide étape par étape](./render-html-to-png-in-c-step-by-step-guide/) +Apprenez à convertir du HTML en PNG avec C# grâce à ce guide complet étape par étape. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/french/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/french/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..869735c62 --- /dev/null +++ b/html/french/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-03-14 +description: Rendre le HTML en image rapidement avec Aspose.HTML. Apprenez à convertir + une page Web en PNG, à définir le style de police et à enregistrer l'image rendue + en quelques lignes de C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: fr +og_description: Rendre le HTML en image avec Aspose.HTML. Ce tutoriel montre comment + convertir une page Web en PNG, définir le style de police et enregistrer l'image + rendue en C#. +og_title: Rendre le HTML en image en C# – Guide rapide et facile +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Rendu du HTML en image en C# – Guide complet étape par étape +url: /fr/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +Now produce final content with same shortcodes and placeholders. + +Check for any other text: At top there are three opening shortcodes, then content, then closing shortcodes and a backtop button shortcode. + +We must keep them unchanged. + +Now produce final answer.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Rendu HTML en image – Tutoriel complet C# + +Ever needed to **render HTML to image** but weren't sure which library to pick? You're not the only one. In many web‑automation or reporting scenarios you end up with a live page that you want to archive as a PNG, JPEG, or even a BMP. The good news is that Aspose.HTML makes this a piece of cake, letting you **convert webpage to PNG** with just a few lines of code. + +In this guide we’ll walk through the entire process: from installing the Aspose.HTML package, loading a remote URL, tweaking rendering options (including how to **set font style**), and finally **save rendered image** to disk. By the end you’ll have a ready‑to‑run console app that produces a crisp screenshot of any web page. + +## Ce dont vous avez besoin + +| Prérequis | Raison | +|--------------|--------| +| .NET 6.0 SDK or later | Aspose.HTML targets .NET Standard 2.0+, so .NET 6 gives you the freshest runtime. | +| Visual Studio 2022 (or VS Code) | Un IDE confortable accélère le débogage. | +| Aspose.HTML for .NET NuGet package | C'est le moteur qui effectue le travail lourd. | +| A valid Aspose.HTML license (optional) | Sans licence, vous obtiendrez un filigrane sur l'image de sortie. | + +You can grab the package via the CLI: + +```bash +dotnet add package Aspose.HTML +``` + +If you prefer the GUI, just search for “Aspose.HTML” in the NuGet Package Manager. + +## Étape 1 : Charger la page web que vous souhaitez rasteriser + +The first thing you have to do is give Aspose.HTML a source document. It can be a local file, a string, or a remote URL. In most real‑world scenarios you’ll be dealing with a live site, so let’s **convert webpage to PNG** by pointing at `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Pourquoi c'est important :** Loading the page as an `HtmlDocument` gives you full access to the DOM, which means you can inject CSS, manipulate the layout, or even run JavaScript before rasterizing. + +## Étape 2 : Configurer les options de rendu d'image + +Now that the HTML is in memory, we need to tell the renderer how we want the final picture to look. This is where you can **set font style**, enable antialiasing, or tweak the DPI. Below is a solid default configuration that balances quality and speed. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Astuce :** If you only need a regular weight, drop the `WebFontStyle` flags. For headlines you might want `WebFontStyle.Bold` alone, while captions could use `WebFontStyle.Italic`. + +## Étape 3 : Rendre la page et **Save Rendered Image** en PNG + +With the document and options ready, the final step is to instantiate `ImageRenderer` and write the output file. The `using` block ensures resources are released promptly. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +When you run the program, you should see a `page.png` file in your project folder containing a faithful snapshot of *example.com*. Open it with any image viewer and you’ll notice the bold‑italic styling we requested earlier. + +### Sortie attendue + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +The PNG will be roughly 800 × 600 px (depending on the page’s original dimensions) with smooth edges thanks to antialiasing. + +## Exemple complet fonctionnel + +Putting everything together, here’s a minimal console app you can copy‑paste into `Program.cs`. It compiles and runs out of the box. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Run it with: + +```bash +dotnet run +``` + +…and you’ll have a fresh PNG ready for archiving, emailing, or embedding in a report. + +## Variantes et cas limites + +### 1. Conversion en JPEG au lieu de PNG + +If your downstream system prefers JPEG (smaller file size, lossy compression), just change the file extension in `Save`. Aspose.HTML automatically detects the format from the path. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +You can also tweak compression quality via `JpegRenderingOptions`. + +### 2. Modification des dimensions de l'image + +Sometimes you need a thumbnail rather than a full‑size screenshot. Set `ImageSize` on the options: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Gestion des pages protégées par authentification + +If the target URL requires basic auth, supply credentials through `HttpWebRequest` before creating the `HtmlDocument`. Alternatively, download the HTML yourself (using `HttpClient`) and feed it as a string: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Utilisation d'une police personnalisée + +Aspose.HTML can embed local fonts. Register the font folder before loading the document: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Now any `font-family` declarations in the page will resolve to your custom files. + +### 5. Rendu de plusieurs pages dans une boucle + +If you need to batch‑process a list of URLs: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +## Pièges courants et comment les éviter + +| Symptôme | Cause probable | Solution | +|----------|----------------|----------| +| Fichier PNG vide | `HtmlDocument.IsEmpty` vrai (la page n'a pas pu être chargée) | Vérifiez l'URL, le proxy réseau, assurez-vous que TLS 1.2 est activé. | +| Texte illisible sous Linux | L'optimisation des polices désactivée | Définissez `renderingOptions.TextOptions.UseHinting = true;`. | +| Filigrane sur la sortie | Aucune licence fournie | Enregistrez une licence temporaire ou complète via `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Image basse résolution | Le DPI par défaut de 96 est insuffisant pour l'impression | Augmentez `renderingOptions.DpiX` et `DpiY` à 150‑300. | + +## 🎉 Conclusion + +We’ve just covered everything you need to **render HTML to image** with Aspose.HTML in C#. From loading a remote page, configuring antialiasing and **set font style**, to finally **save rendered image** as a PNG, the whole workflow fits neatly into a few concise steps. + +Now you can **convert webpage to PNG** on the fly, embed screenshots in reports, or generate thumbnails for a catalog—no browser automation required. + +### Et après ? + +- Expérimentez avec **convert html to png** pour différentes tailles d'écran (mobile vs desktop). +- Essayez d'exporter en PDF avec `PdfRenderer` si vous avez besoin d'un document imprimable. +- Plongez dans les API de manipulation du DOM d'Aspose.HTML pour injecter des filigranes ou du CSS personnalisé avant le rendu. + +Des questions sur les cas limites, la licence ou l'optimisation des performances ? Laissez un commentaire ci‑dessous, et bon codage ! + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/french/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..3e169aeb3 --- /dev/null +++ b/html/french/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-03-14 +description: Rendre le HTML en PNG rapidement avec Aspose.HTML. Apprenez à générer + un PNG à partir du HTML, à appliquer le style de police gras et italique, et à enregistrer + le HTML dans un flux. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: fr +og_description: Rendre le HTML en PNG avec Aspose.HTML. Ce guide montre comment générer + un PNG à partir du HTML, utiliser le style de police gras italique et enregistrer + le HTML dans un flux. +og_title: Rendu de HTML en PNG en C# – Guide complet de programmation +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Convertir le HTML en PNG en C# – Guide étape par étape +url: /fr/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +sure to keep them. + +Now produce final content.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG in C# – Guide complet de programmation + +Vous avez déjà eu besoin de **render HTML to PNG** mais vous n'étiez pas sûr de la bibliothèque qui vous offrirait des résultats pixel‑parfait ? Vous n'êtes pas seul. Dans de nombreux pipelines web‑to‑image, les développeurs sont confrontés à des polices manquantes, du texte flou, ou la redoutable question « comment capturer le HTML sans l'écrire d'abord sur le disque ? » + +Voici le point : Aspose.HTML rend tout le processus simple comme bonbon. Dans ce tutoriel, nous allons **generate PNG from HTML**, appliquer un **bold italic font style**, et même **save HTML to a stream** afin de tout garder en mémoire. À la fin, vous disposerez d’une application console prête à l’emploi qui transforme un petit extrait HTML en un fichier PNG net. + +--- + +## Ce dont vous aurez besoin + +- **.NET 6+** (le code fonctionne avec .NET Core et .NET Framework) +- **Aspose.HTML for .NET** package NuGet – `Install-Package Aspose.HTML` +- Un IDE préféré (Visual Studio, Rider ou VS Code) – n'importe lequel fera l'affaire. + +Pas de polices supplémentaires, aucun outil externe, et certainement aucun fichier temporaire. Juste du pur C#. + +--- + +## Étape 1 : Créer un document HTML simple + +La première chose que nous faisons est de construire un document HTML en mémoire. Considérez-le comme une page web virtuelle qui n'existe que dans votre processus. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Pourquoi c’est important :** En construisant le DOM de façon programmatique, vous évitez la surcharge d’E/S de fichiers et vous pouvez injecter des données dynamiques à la volée. La classe `HtmlDocument` est le point d’entrée pour chaque opération Aspose.HTML. + +--- + +## Étape 2 : Enregistrer le HTML dans un flux + +Au lieu d’écrire le balisage sur le disque, nous le capturons dans un `ResourceHandler` personnalisé. C’est la partie **save html to stream** du flux de travail. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Pro tip :** Le `MemoryHandler` est petit mais puissant. Si vous avez besoin plus tard d’intégrer des images, du CSS ou des polices, il suffit d’étendre `HandleResource` pour renvoyer les flux appropriés. + +--- + +## Étape 3 : Configurer le style de police gras italique + +Lorsque vous rendez du texte, vous voulez souvent qu’il apparaisse exactement comme dans un navigateur. Aspose.HTML vous permet de définir le **bold italic font style** directement dans les options de rendu. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **What’s happening :** +> * `UseAntialiasing` lisse les bords des formes. +> * `UseHinting` améliore le positionnement des glyphes, ce qui est crucial pour le petit texte. +> * `FontStyle` combine les indicateurs `Bold` et `Italic`, de sorte que chaque morceau de texte du document hérite de ce style sauf s’il est remplacé. + +--- + +## Étape 4 : Rendre le document HTML en image PNG + +Voici la partie amusante – transformer ce HTML en fichier image. Le `ImageRenderer` fait tout le travail lourd. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Si vous exécutez le programme, vous verrez un fichier nommé `output.png` dans le répertoire de travail. Il contient le titre ``, vous avez déjà une structure HTML valide prête à être enregistrée. + +> **Astuce pro :** Si vous avez besoin d’un squelette HTML complet (``, `
`, etc.), Aspose.HTML le génère automatiquement lors de l’enregistrement du document, même si vous n’avez ajouté que du contenu dans le corps. + +## Étape 2 : Implémenter un **gestionnaire de ressources personnalisé** – Capturer le HTML en mémoire + +Un *gestionnaire de ressources* indique à Aspose.HTML où écrire chaque ressource (HTML, CSS, images, etc.). En surchargeant `HandleResource`, nous pouvons diriger la sortie HTML vers un `MemoryStream` au lieu d’un fichier. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Pourquoi utiliser un gestionnaire personnalisé :** +- **Performance :** Pas d’E/S disque, tout reste en RAM. +- **Sécurité :** Aucun fichier temporaire pouvant être exposé. +- **Flexibilité :** Vous pouvez ensuite acheminer le flux vers une réponse, une base de données ou une autre API. + +## Étape 3 : Enregistrer le document avec le gestionnaire – Le cœur de **Generate HTML Programmatically** + +Nous associons maintenant le document et le gestionnaire. Lorsque `htmlDoc.Save(handler)` s’exécute, Aspose.HTML appelle `HandleResource`, nous remettant le flux à écrire. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +À ce stade, `handler.HtmlStream` contient les octets bruts du HTML. Aucun fichier n’a été créé sur le disque, et vous pouvez réutiliser le flux autant de fois que nécessaire (n’oubliez pas de réinitialiser sa position). + +## Étape 4 : Lire le HTML généré depuis la mémoire – Vérifier la sortie + +Pour prouver que tout fonctionne, nous réinitialisons la position du flux au début et lisons le texte. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Sortie attendue** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Si vous voyez le balisage ci‑dessus, félicitations — vous avez réussi à **generate html programmatically** avec Aspose.HTML et un **custom resource handler**. + +## Variantes courantes et cas limites + +### Gestion du CSS ou des images + +La démo ignore les ressources non‑HTML en renvoyant `Stream.Null`. Dans un scénario réel, vous pourriez vouloir capturer les fichiers CSS ou les images également : + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Réutiliser le même gestionnaire pour plusieurs enregistrements + +Si vous devez générer plusieurs extraits HTML dans une boucle, créez un nouveau `MemoryHtmlHandler` à chaque itération ou videz le flux existant : + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Enregistrement asynchrone (Aspose.HTML 23.4+) + +Les versions récentes supportent l’enregistrement asynchrone : + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +N’oubliez pas de `await` et de déclarer votre méthode `async`. + +## Exemple complet fonctionnel + +Voici le programme complet que vous pouvez copier‑coller dans une application console. Il inclut toutes les pièces abordées, ainsi que quelques commentaires pour plus de clarté. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Exécutez le programme (`dotnet run`) et vous devriez voir le HTML affiché dans la console, exactement comme précédemment. + +## Conclusion + +Nous venons de montrer comment **create HTML document C#** avec Aspose.HTML, capturer la sortie grâce à un **custom resource handler**, et **generate HTML programmatically** sans toucher au système de fichiers. Le modèle est évolutif—que vous construisiez des modèles d’e‑mail, des rapports à la volée ou un micro‑service renvoyant des extraits HTML. + +Prochaines étapes ? Essayez d’ajouter une feuille de style CSS via le gestionnaire, ou de diffuser le HTML directement dans une réponse ASP.NET Core (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Vous pouvez également brancher la sortie dans un convertisseur PDF ou une bibliothèque HTML‑vers‑image pour des flux de travail plus riches. + +Des questions sur la gestion des images, l’enregistrement asynchrone ou l’intégration avec d’autres bibliothèques ? Laissez un commentaire, et bon codage ! + +{{< /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/rendering-html-documents/_index.md b/html/german/net/rendering-html-documents/_index.md index ad113650f..e65b09045 100644 --- a/html/german/net/rendering-html-documents/_index.md +++ b/html/german/net/rendering-html-documents/_index.md @@ -43,8 +43,12 @@ Nachdem Sie Aspose.HTML für .NET eingerichtet haben, ist es an der Zeit, die Tu ### [Rendern Sie HTML als PNG in .NET mit Aspose.HTML](./render-html-as-png/) Erfahren Sie, wie Sie mit Aspose.HTML für .NET arbeiten: HTML bearbeiten, in verschiedene Formate konvertieren und mehr. Tauchen Sie ein in dieses umfassende Tutorial! +### [HTML in PNG rendern in C# – Schritt‑für‑Schritt‑Leitfaden](./render-html-to-png-in-c-step-by-step-guide/) +Erfahren Sie, wie Sie mit Aspose.HTML HTML nach PNG konvertieren – vollständige C#‑Beispiele und detaillierte Schritt‑für‑Schritt‑Anleitung. + ### [HTML als PNG rendern – Vollständiger C#-Leitfaden](./how-to-render-html-as-png-complete-c-guide/) Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in PNG konvertieren, inklusive vollständigem C#-Beispiel und Schritt‑für‑Schritt‑Anleitung. + ### [Wie Sie Aspose zum Rendern von HTML nach PNG verwenden – Schritt‑für‑Schritt‑Anleitung](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) Erfahren Sie, wie Sie mit Aspose.HTML HTML‑Inhalte in PNG‑Bilder umwandeln – detaillierte Schritt‑für‑Schritt‑Anleitung. @@ -53,6 +57,7 @@ Erfahren Sie, wie Sie HTML‑Inhalte mit Aspose in PNG‑Bilder umwandeln – ei ### [PNG aus HTML erstellen – Vollständiger C#-Rendering-Leitfaden](./create-png-from-html-full-c-rendering-guide/) Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in PNG konvertieren – ein umfassender Leitfaden für C#-Entwickler. + ### [Rendern Sie EPUB als XPS in .NET mit Aspose.HTML](./render-epub-as-xps/) Erfahren Sie in diesem umfassenden Tutorial, wie Sie mit Aspose.HTML für .NET HTML-Dokumente erstellen und rendern. Tauchen Sie ein in die Welt der HTML-Manipulation, des Web Scraping und mehr. @@ -67,6 +72,10 @@ Erfahren Sie, wie Sie mit Aspose.HTML für .NET mehrere HTML-Dokumente rendern. ### [Rendern Sie SVG-Dokumente als PNG in .NET mit Aspose.HTML](./render-svg-doc-as-png/) Entfesseln Sie die Leistungsfähigkeit von Aspose.HTML für .NET! Erfahren Sie, wie Sie SVG-Dokumente mühelos als PNG rendern. Tauchen Sie ein in Schritt‑für‑Schritt‑Beispiele und FAQs. Jetzt loslegen! + +### [HTML in Bild rendern in C# – Vollständiger Schritt‑für‑Schritt‑Leitfaden](./render-html-to-image-in-c-complete-step-by-step-guide/) +Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in verschiedene Bildformate konvertieren – vollständige C#‑Beispiele und Schritt‑für‑Schritt‑Anleitung. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/german/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/german/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..8474716fe --- /dev/null +++ b/html/german/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-03-14 +description: Rendern Sie HTML schnell zu einem Bild mit Aspose.HTML. Erfahren Sie, + wie Sie eine Webseite in PNG konvertieren, den Schriftstil festlegen und das gerenderte + Bild mit nur wenigen Zeilen C# speichern. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: de +og_description: HTML mit Aspose.HTML in ein Bild rendern. Dieses Tutorial zeigt, wie + man eine Webseite in PNG konvertiert, den Schriftstil festlegt und das gerenderte + Bild in C# speichert. +og_title: HTML zu Bild rendern in C# – Schnelle und einfache Anleitung +tags: +- C# +- Aspose.HTML +- Image Rendering +title: HTML in ein Bild rendern in C# – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +blocks/products/products-backtop-button >}} + +All preserved. + +Now ensure we didn't miss any markdown links. There are none besides maybe none. So final output is the translated content. + +Let's assemble.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML in Bild rendern – Vollständiges C#‑Tutorial + +Haben Sie jemals **HTML in Bild rendern** müssen, waren sich aber nicht sicher, welche Bibliothek Sie wählen sollen? Sie sind nicht allein. In vielen Web‑Automatisierungs‑ oder Reporting‑Szenarien erhalten Sie eine Live‑Seite, die Sie als PNG, JPEG oder sogar BMP archivieren möchten. Die gute Nachricht ist, dass Aspose.HTML das zum Kinderspiel macht und Ihnen ermöglicht, **Webseite in PNG zu konvertieren** mit nur wenigen Codezeilen. + +In diesem Leitfaden gehen wir den gesamten Prozess durch: von der Installation des Aspose.HTML‑Pakets, dem Laden einer Remote‑URL, dem Anpassen der Rendering‑Optionen (einschließlich wie man **Schriftstil festlegt**), bis hin zum **Speichern des gerenderten Bildes** auf die Festplatte. Am Ende haben Sie eine sofort ausführbare Konsolen‑App, die einen scharfen Screenshot jeder Webseite erzeugt. + +## Was Sie benötigen + +| Voraussetzung | Grund | +|--------------|--------| +| .NET 6.0 SDK oder neuer | Aspose.HTML zielt auf .NET Standard 2.0+ ab, daher liefert .NET 6 die neuste Laufzeit. | +| Visual Studio 2022 (oder VS Code) | Eine komfortable IDE beschleunigt das Debugging. | +| Aspose.HTML für .NET NuGet‑Paket | Dies ist die Engine, die die schwere Arbeit übernimmt. | +| Eine gültige Aspose.HTML‑Lizenz (optional) | Ohne Lizenz erhalten Sie ein Wasserzeichen im Ausgabebild. | + +Sie können das Paket über die CLI holen: + +```bash +dotnet add package Aspose.HTML +``` + +Wenn Sie die GUI bevorzugen, suchen Sie einfach nach „Aspose.HTML“ im NuGet‑Paket‑Manager. + +--- + +## Schritt 1: Laden Sie die Webseite, die Sie rasterisieren möchten + +Das Erste, was Sie tun müssen, ist Aspose.HTML ein Quelldokument zu geben. Es kann eine lokale Datei, ein String oder eine Remote‑URL sein. In den meisten realen Szenarien arbeiten Sie mit einer Live‑Seite, also lassen Sie uns **Webseite in PNG konvertieren**, indem wir auf `https://example.com` zeigen. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Warum das wichtig ist:** Das Laden der Seite als `HtmlDocument` gibt Ihnen vollen Zugriff auf das DOM, was bedeutet, dass Sie CSS injizieren, das Layout manipulieren oder sogar JavaScript ausführen können, bevor Sie rasterisieren. + +--- + +## Schritt 2: Bild‑Rendering‑Optionen konfigurieren + +Jetzt, wo das HTML im Speicher ist, müssen wir dem Renderer mitteilen, wie das endgültige Bild aussehen soll. Hier können Sie **Schriftstil festlegen**, Antialiasing aktivieren oder die DPI anpassen. Unten ist eine solide Standardkonfiguration, die Qualität und Geschwindigkeit ausbalanciert. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Pro‑Tipp:** Wenn Sie nur ein normales Gewicht benötigen, lassen Sie die `WebFontStyle`‑Flags weg. Für Überschriften möchten Sie vielleicht nur `WebFontStyle.Bold`, während für Bildunterschriften `WebFontStyle.Italic` verwendet werden kann. + +--- + +## Schritt 3: Rendern Sie die Seite und **Speichern Sie das gerenderte Bild** als PNG + +Mit dem Dokument und den Optionen bereit, ist der letzte Schritt, `ImageRenderer` zu instanziieren und die Ausgabedatei zu schreiben. Der `using`‑Block sorgt dafür, dass Ressourcen sofort freigegeben werden. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +Wenn Sie das Programm ausführen, sollten Sie eine `page.png`‑Datei in Ihrem Projektordner sehen, die einen getreuen Schnappschuss von *example.com* enthält. Öffnen Sie sie mit einem beliebigen Bildbetrachter und Sie werden die zuvor angeforderte fett‑kursiv‑Formatierung bemerken. + +### Erwartete Ausgabe + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +Das PNG wird ungefähr 800 × 600 px groß sein (abhängig von den ursprünglichen Abmessungen der Seite) mit glatten Kanten dank Antialiasing. + +--- + +## Vollständiges funktionierendes Beispiel + +Wenn wir alles zusammenfügen, erhalten Sie eine minimale Konsolen‑App, die Sie in `Program.cs` kopieren‑und‑einfügen können. Sie kompiliert und läuft sofort. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Führen Sie sie aus mit: + +```bash +dotnet run +``` + +… und Sie haben ein frisches PNG, das bereit ist zum Archivieren, per E‑Mail zu versenden oder in einen Bericht einzubetten. + +--- + +## Varianten & Sonderfälle + +### 1. Konvertieren zu JPEG anstelle von PNG + +Wenn Ihr nachgelagertes System JPEG bevorzugt (kleinere Dateigröße, verlustbehaftete Kompression), ändern Sie einfach die Dateierweiterung in `Save`. Aspose.HTML erkennt das Format automatisch aus dem Pfad. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +Sie können die Kompressionsqualität auch über `JpegRenderingOptions` anpassen. + +### 2. Bildabmessungen ändern + +Manchmal benötigen Sie ein Thumbnail statt eines Vollbild‑Screenshots. Setzen Sie `ImageSize` in den Optionen: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Umgang mit authentifizierten Seiten + +Wenn die Ziel‑URL eine Basic‑Auth erfordert, übergeben Sie die Anmeldeinformationen über `HttpWebRequest`, bevor Sie das `HtmlDocument` erstellen. Alternativ können Sie das HTML selbst herunterladen (mit `HttpClient`) und es als String übergeben: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Verwendung einer benutzerdefinierten Schriftart + +Aspose.HTML kann lokale Schriftarten einbetten. Registrieren Sie den Schriftordner, bevor Sie das Dokument laden: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Jetzt werden alle `font-family`‑Deklarationen auf der Seite zu Ihren benutzerdefinierten Dateien aufgelöst. + +### 5. Mehrere Seiten in einer Schleife rendern + +Wenn Sie eine Liste von URLs stapelweise verarbeiten müssen: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Häufige Fallstricke & wie man sie vermeidet + +| Symptom | Wahrscheinliche Ursache | Lösung | +|---------|--------------------------|--------| +| Leere PNG‑Datei | `HtmlDocument.IsEmpty` true (Seite konnte nicht geladen werden) | URL überprüfen, Netzwerk‑Proxy prüfen, sicherstellen, dass TLS 1.2 aktiviert ist. | +| Verzerrter Text unter Linux | Font‑Hinting deaktiviert | `renderingOptions.TextOptions.UseHinting = true;` setzen. | +| Wasserzeichen in der Ausgabe | Keine Lizenz angegeben | Eine temporäre oder vollständige Lizenz registrieren via `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Niedrigauflösendes Bild | Standard‑DPI 96 ist für den Druck unzureichend | `renderingOptions.DpiX` und `DpiY` auf 150‑300 erhöhen. | + +--- + +## 🎉 Fazit + +Wir haben gerade alles behandelt, was Sie benötigen, um **HTML in Bild zu rendern** mit Aspose.HTML in C#. Vom Laden einer Remote‑Seite, über das Konfigurieren von Antialiasing und **Schriftstil festlegen**, bis hin zum **Speichern des gerenderten Bildes** als PNG, passt der gesamte Workflow sauber in ein paar prägnante Schritte. + +Jetzt können Sie **Webseite in PNG konvertieren** on‑the‑fly, Screenshots in Berichte einbetten oder Thumbnails für einen Katalog erzeugen — ohne Browser‑Automatisierung. + +### Was kommt als Nächstes? + +- Experimentieren Sie mit **convert html to png** für verschiedene Bildschirmgrößen (Mobil‑ vs. Desktop‑Ansicht). +- Versuchen Sie, mit `PdfRenderer` nach PDF zu exportieren, wenn Sie ein druckbares Dokument benötigen. +- Tauchen Sie in die DOM‑Manipulations‑APIs von Aspose.HTML ein, um Wasserzeichen oder benutzerdefiniertes CSS vor dem Rendering einzufügen. + +Haben Sie Fragen zu Sonderfällen, Lizenzierung oder Performance‑Optimierung? Hinterlassen Sie unten einen Kommentar, und happy coding! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/german/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..bd62488f4 --- /dev/null +++ b/html/german/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-03-14 +description: HTML schnell zu PNG rendern mit Aspose.HTML. Erfahren Sie, wie Sie PNG + aus HTML erzeugen, fette und kursive Schriftstile anwenden und HTML in einen Stream + speichern. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: de +og_description: Rendern Sie HTML zu PNG mit Aspose.HTML. Dieser Leitfaden zeigt, wie + man PNG aus HTML erzeugt, fette und kursive Schriftstile verwendet und HTML in einen + Stream speichert. +og_title: HTML zu PNG rendern in C# – Vollständiger Programmierleitfaden +tags: +- Aspose.HTML +- C# +- Image Rendering +title: HTML zu PNG rendern in C# – Schritt‑für‑Schritt‑Anleitung +url: /de/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML in PNG rendern in C# – Vollständiger Programmierleitfaden + +Haben Sie jemals **HTML in PNG rendern** müssen, waren sich aber nicht sicher, welche Bibliothek pixelgenaue Ergebnisse liefert? Sie sind nicht allein. In vielen Web‑zu‑Bild‑Pipelines stoßen Entwickler auf fehlende Schriftarten, unscharfen Text oder das gefürchtete „Wie erfasse ich das HTML, ohne es zuerst auf die Festplatte zu schreiben?“ + +Hier ist die Sache: Aspose.HTML macht den gesamten Prozess zum Kinderspiel. In diesem Tutorial werden wir **PNG aus HTML erzeugen**, einen **fetten kursiven Schriftstil** anwenden und sogar **HTML in einen Stream speichern**, sodass alles im Speicher bleibt. Am Ende haben Sie eine sofort ausführbare Konsolen‑App, die ein kleines HTML‑Snippet in eine scharfe PNG‑Datei verwandelt. + +--- + +## Was Sie benötigen + +- **.NET 6+** (der Code funktioniert sowohl mit .NET Core als auch mit .NET Framework) +- **Aspose.HTML for .NET** NuGet‑Paket – `Install-Package Aspose.HTML` +- Eine bevorzugte IDE (Visual Studio, Rider oder VS Code) – jede ist geeignet. + +Keine zusätzlichen Schriftarten, keine externen Werkzeuge und definitiv keine temporären Dateien. Einfach reines C#. + +--- + +## Schritt 1: Ein einfaches HTML‑Dokument erstellen + +Das Erste, was wir tun, ist ein HTML‑Dokument im Speicher zu erstellen. Stellen Sie sich das wie eine virtuelle Webseite vor, die nur innerhalb Ihres Prozesses existiert. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Warum das wichtig ist:** Durch das programmgesteuerte Erstellen des DOM vermeiden Sie Date‑I/O‑Overhead und können dynamische Daten on the fly einfügen. Die Klasse `HtmlDocument` ist der Einstiegspunkt für jede Aspose.HTML‑Operation. + +--- + +## Schritt 2: HTML in einen Stream speichern + +Anstatt das Markup auf die Festplatte zu schreiben, erfassen wir es in einem benutzerdefinierten `ResourceHandler`. Das ist der **save html to stream**‑Teil des Workflows. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Pro‑Tipp:** Der `MemoryHandler` ist klein, aber leistungsfähig. Wenn Sie später Bilder, CSS oder Schriftarten einbetten müssen, erweitern Sie einfach `HandleResource`, um die entsprechenden Streams zurückzugeben. + +--- + +## Schritt 3: Fettschrift‑Kursiv‑Schriftstil konfigurieren + +Wenn Sie Text rendern, möchten Sie oft, dass er exakt so aussieht wie im Browser. Aspose.HTML ermöglicht das direkte Setzen des **bold italic font style** in den Rendering‑Optionen. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **Was passiert:** +> * `UseAntialiasing` glättet die Kanten von Formen. +> * `UseHinting` verbessert die Glyphen‑Positionierung, was bei kleinem Text entscheidend ist. +> * `FontStyle` kombiniert die Flags `Bold` und `Italic`, sodass jedes Textelement im Dokument diesen Stil erbt, sofern nicht überschrieben. + +--- + +## Schritt 4: Das HTML‑Dokument in ein PNG‑Bild rendern + +Jetzt kommt der spaßige Teil – das HTML in eine Bilddatei zu verwandeln. Der `ImageRenderer` übernimmt die schwere Arbeit. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Wenn Sie das Programm ausführen, sehen Sie eine Datei namens `output.png` im Arbeitsverzeichnis. Sie enthält die ``‑Elements haben wir bereits eine gültige HTML‑Struktur, die gespeichert werden kann. + +> **Profi‑Tipp:** Wenn Sie ein vollständiges HTML‑Gerüst (``, `
` usw.) benötigen, erzeugt Aspose.HTML dieses automatisch beim Speichern des Dokuments, selbst wenn Sie nur Body‑Inhalte hinzugefügt haben. + +## Schritt 2: Implementieren eines **benutzerdefinierten Ressourcen-Handlers** – HTML im Speicher erfassen + +Ein *Ressourcen‑Handler* teilt Aspose.HTML mit, wohin jede Ressource (HTML, CSS, Bilder usw.) geschrieben werden soll. Durch Überschreiben von `HandleResource` können wir die HTML‑Ausgabe in einen `MemoryStream` anstatt in eine Datei leiten. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Warum wir einen benutzerdefinierten Handler verwenden:** +- **Performance:** Kein Festplatten‑I/O, alles bleibt im RAM. +- **Sicherheit:** Keine temporären Dateien, die offengelegt werden könnten. +- **Flexibilität:** Sie können den Stream später an eine Antwort, eine Datenbank oder eine andere API weiterleiten. + +## Schritt 3: Dokument mit dem Handler speichern – Das Herz von **HTML programmgesteuert erzeugen** + +Jetzt verbinden wir das Dokument und den Handler. Wenn `htmlDoc.Save(handler)` ausgeführt wird, ruft Aspose.HTML `HandleResource` auf und übergibt uns den Stream, in den geschrieben werden soll. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +Zu diesem Zeitpunkt enthält `handler.HtmlStream` die rohen HTML‑Bytes. Es wurde nichts auf die Festplatte geschrieben, und Sie können den Stream beliebig oft wiederverwenden (denken Sie nur daran, seine Position zurückzusetzen). + +## Schritt 4: Das erzeugte HTML aus dem Speicher lesen – Ausgabe überprüfen + +Um zu beweisen, dass alles funktioniert hat, setzen wir die Position des Streams auf den Anfang zurück und lesen den Text erneut. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Erwartete Ausgabe** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Wenn Sie das obige Markup sehen, herzlichen Glückwunsch – Sie haben **HTML programmgesteuert erzeugt** mit Aspose.HTML und einem **benutzerdefinierten Ressourcen-Handler**. + +## Häufige Variationen & Sonderfälle + +### Umgang mit CSS oder Bildern + +Das Demo‑Beispiel ignoriert Nicht‑HTML‑Ressourcen, indem es `Stream.Null` zurückgibt. In einem realen Szenario möchten Sie möglicherweise CSS‑Dateien oder Bilder ebenfalls erfassen: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Wiederverwenden desselben Handlers für mehrere Saves + +Wenn Sie mehrere HTML‑Snippets in einer Schleife erzeugen müssen, erstellen Sie in jeder Iteration einen neuen `MemoryHtmlHandler` oder leeren Sie den bestehenden Stream: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Asynchrones Speichern (Aspose.HTML 23.4+) + +Neuere Versionen unterstützen asynchrones Speichern: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Denken Sie daran, `await` zu verwenden und Ihre Methode `async` zu deklarieren. + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie das komplette Programm, das Sie in eine Konsolen‑App kopieren‑einfügen können. Es enthält alle besprochenen Bausteine sowie einige Kommentare zur Klarheit. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Führen Sie das Programm aus (`dotnet run`) und Sie sollten das HTML in der Konsole ausgegeben sehen, exakt wie zuvor gezeigt. + +## Fazit + +Wir haben gerade gezeigt, wie man **HTML-Dokument in C#** mit Aspose.HTML erstellt, die Ausgabe mit einem **benutzerdefinierten Ressourcen-Handler** erfasst und **HTML programmgesteuert** erzeugt, ohne das Dateisystem zu berühren. Das Muster skaliert – egal, ob Sie E‑Mail‑Vorlagen, on‑the‑fly‑Berichte oder einen Micro‑Service bauen, der HTML‑Snippets zurückgibt. + +Nächste Schritte? Versuchen Sie, ein CSS‑Stylesheet über den Handler hinzuzufügen, oder streamen Sie das HTML direkt in eine ASP.NET Core‑Antwort (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Sie könnten die Ausgabe auch in einen PDF‑Konverter oder eine HTML‑zu‑Image‑Bibliothek einbinden für umfangreichere Workflows. + +Haben Sie Fragen zum Umgang mit Bildern, asynchronem Speichern oder zur Integration mit anderen Bibliotheken? Hinterlassen Sie einen Kommentar, und viel Spaß beim Coden! + +{{< /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/rendering-html-documents/_index.md b/html/greek/net/rendering-html-documents/_index.md index f874e075c..7fe0fdd28 100644 --- a/html/greek/net/rendering-html-documents/_index.md +++ b/html/greek/net/rendering-html-documents/_index.md @@ -42,25 +42,40 @@ url: /el/net/rendering-html-documents/ ### [Αποδώστε το HTML ως PNG στο .NET με το Aspose.HTML](./render-html-as-png/) Μάθετε να εργάζεστε με το Aspose.HTML για .NET: Χειριστείτε HTML, μετατρέψτε σε διάφορες μορφές και πολλά άλλα. Βουτήξτε σε αυτό το ολοκληρωμένο σεμινάριο! + ### [Αποδώστε το EPUB ως XPS σε .NET με Aspose.HTML](./render-epub-as-xps/) Μάθετε πώς να δημιουργείτε και να αποδίδετε έγγραφα HTML με το Aspose.HTML για .NET σε αυτό το ολοκληρωμένο σεμινάριο. Βουτήξτε στον κόσμο της χειραγώγησης HTML, της απόξεσης ιστού και πολλά άλλα. + ### [Χρονικό όριο απόδοσης σε .NET με Aspose.HTML](./rendering-timeout/) Μάθετε πώς να ελέγχετε αποτελεσματικά τα χρονικά όρια απόδοσης στο Aspose.HTML για .NET. Εξερευνήστε τις επιλογές απόδοσης και εξασφαλίστε ομαλή απόδοση εγγράφων HTML. + ### [Αποδώστε το MHTML ως XPS στο .NET με το Aspose.HTML](./render-mhtml-as-xps/) Μάθετε να αποδίδετε το MHTML ως XPS στο .NET με το Aspose.HTML. Βελτιώστε τις δεξιότητές σας στον χειρισμό HTML και ενισχύστε τα έργα ανάπτυξης ιστού σας! + ### [Απόδοση πολλαπλών εγγράφων σε .NET με Aspose.HTML](./render-multiple-documents/) Μάθετε να αποδίδετε πολλά έγγραφα HTML χρησιμοποιώντας το Aspose.HTML για .NET. Ενισχύστε τις δυνατότητες επεξεργασίας εγγράφων σας με αυτήν την ισχυρή βιβλιοθήκη. + ### [Απόδοση SVG Doc ως PNG σε .NET με Aspose.HTML](./render-svg-doc-as-png/) Ξεκλειδώστε τη δύναμη του Aspose.HTML για .NET! Μάθετε πώς να αποδίδετε το Έγγραφο SVG ως PNG χωρίς κόπο. Ανατρέξτε σε παραδείγματα βήμα προς βήμα και συχνές ερωτήσεις. Ξεκινήστε τώρα! + ### [Πώς να αποδώσετε HTML ως PNG – Πλήρης οδηγός C#](./how-to-render-html-as-png-complete-c-guide/) Μάθετε πώς να μετατρέψετε HTML σε PNG χρησιμοποιώντας C# και το Aspose.HTML για .NET σε αυτό το ολοκληρωμένο σεμινάριο! + ### [Πώς να χρησιμοποιήσετε το Aspose για απόδοση HTML σε PNG – Οδηγός βήμα‑βήμα](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) Μάθετε πώς να μετατρέψετε HTML σε PNG χρησιμοποιώντας το Aspose.HTML για .NET με αυτόν τον αναλυτικό οδηγό βήμα‑βήμα. + ### [Πώς να αποδώσετε HTML σε PNG με το Aspose – Πλήρης οδηγός](./how-to-render-html-to-png-with-aspose-complete-guide/) Μάθετε πώς να μετατρέψετε HTML σε PNG χρησιμοποιώντας το Aspose.HTML για .NET σε αυτόν τον πλήρη οδηγό. + ### [Δημιουργία PNG από HTML – Πλήρης Οδηγός Απόδοσης C#](./create-png-from-html-full-c-rendering-guide/) Μάθετε πώς να δημιουργήσετε PNG από HTML χρησιμοποιώντας το Aspose.HTML για .NET με πλήρη οδηγό C#. +### [Απόδοση HTML σε εικόνα με C# – Πλήρης οδηγός βήμα‑βήμα](./render-html-to-image-in-c-complete-step-by-step-guide/) +Μάθετε πώς να μετατρέψετε HTML σε εικόνα χρησιμοποιώντας C# και το Aspose.HTML για .NET σε αυτόν τον πλήρη οδηγό βήμα‑βήμα. + +### [Απόδοση HTML σε PNG με C# – Οδηγός βήμα‑βήμα](./render-html-to-png-in-c-step-by-step-guide/) +Μάθετε πώς να μετατρέψετε HTML σε PNG χρησιμοποιώντας C# και Aspose.HTML με αναλυτικές οδηγίες βήμα‑βήμα. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/greek/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/greek/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..bc4842831 --- /dev/null +++ b/html/greek/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-03-14 +description: Αποδώστε HTML σε εικόνα γρήγορα χρησιμοποιώντας το Aspose.HTML. Μάθετε + πώς να μετατρέψετε μια ιστοσελίδα σε PNG, να ορίσετε το στυλ γραμματοσειράς και + να αποθηκεύσετε την αποδοθείσα εικόνα με λίγες μόνο γραμμές κώδικα C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: el +og_description: Απόδοση HTML σε εικόνα με το Aspose.HTML. Αυτό το σεμινάριο δείχνει + πώς να μετατρέψετε μια ιστοσελίδα σε PNG, να ορίσετε το στυλ γραμματοσειράς και + να αποθηκεύσετε την αποδοθείσα εικόνα σε C#. +og_title: Απόδοση HTML σε Εικόνα σε C# – Γρήγορος και Εύκολος Οδηγός +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Απόδοση HTML σε εικόνα με C# – Πλήρης οδηγός βήμα‑προς‑βήμα +url: /el/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +, tables, etc. + +Let's craft translation. + +Be careful with Greek characters and punctuation. + +Proceed. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Απόδοση HTML σε Εικόνα – Πλήρης Οδηγός C# + +Κάποτε χρειάστηκε να **render HTML to image** αλλά δεν ήξερες ποια βιβλιοθήκη να επιλέξεις; Δεν είσαι ο μόνος. Σε πολλές περιπτώσεις web‑automation ή αναφοράς καταλήγεις με μια ζωντανή σελίδα που θέλεις να αρχειοθετήσεις ως PNG, JPEG ή ακόμα και BMP. Τα καλά νέα είναι ότι το Aspose.HTML κάνει αυτό παιχνιδάκι, επιτρέποντάς σου να **convert webpage to PNG** με λίγες μόνο γραμμές κώδικα. + +Σε αυτόν τον οδηγό θα περάσουμε από όλη τη διαδικασία: από την εγκατάσταση του πακέτου Aspose.HTML, τη φόρτωση μιας απομακρυσμένης URL, τη ρύθμιση των επιλογών απόδοσης (συμπεριλαμβανομένου του πώς να **set font style**), και τέλος **save rendered image** στο δίσκο. Στο τέλος θα έχεις μια έτοιμη για εκτέλεση εφαρμογή console που παράγει ένα καθαρό στιγμιότυπο οποιασδήποτε ιστοσελίδας. + +## Τι Θα Χρειαστείτε + +| Prerequisite | Reason | +|--------------|--------| +| .NET 6.0 SDK ή νεότερο | Το Aspose.HTML στοχεύει στο .NET Standard 2.0+, οπότε το .NET 6 σας δίνει το πιο σύγχρονο runtime. | +| Visual Studio 2022 (ή VS Code) | Ένα άνετο IDE επιταχύνει το debugging. | +| Aspose.HTML for .NET NuGet package | Αυτός είναι ο κινητήρας που κάνει τη βαριά δουλειά. | +| Έγκυρη άδεια Aspose.HTML (προαιρετικό) | Χωρίς άδεια θα εμφανίζεται υδατογράφημα στην έξοδο εικόνας. | + +Μπορείτε να αποκτήσετε το πακέτο μέσω του CLI: + +```bash +dotnet add package Aspose.HTML +``` + +Αν προτιμάτε το GUI, απλώς αναζητήστε “Aspose.HTML” στον NuGet Package Manager. + +--- + +## Βήμα 1: Φορτώστε τη Σελίδα που Θέλετε να Rasterize + +Το πρώτο πράγμα που πρέπει να κάνετε είναι να δώσετε στο Aspose.HTML ένα έγγραφο προέλευσης. Μπορεί να είναι τοπικό αρχείο, μια συμβολοσειρά ή μια απομακρυσμένη URL. Στις περισσότερες πραγματικές περιπτώσεις θα δουλεύετε με μια ζωντανή ιστοσελίδα, οπότε ας **convert webpage to PNG** δείχνοντας στο `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Why this matters:** Η φόρτωση της σελίδας ως `HtmlDocument` σας δίνει πλήρη πρόσβαση στο DOM, πράγμα που σημαίνει ότι μπορείτε να ενσωματώσετε CSS, να τροποποιήσετε τη διάταξη ή ακόμη και να εκτελέσετε JavaScript πριν το rasterizing. + +--- + +## Βήμα 2: Ρυθμίστε τις Επιλογές Απόδοσης Εικόνας + +Τώρα που το HTML είναι στη μνήμη, πρέπει να πείτε στον renderer πώς θέλετε να φαίνεται η τελική εικόνα. Εδώ μπορείτε να **set font style**, να ενεργοποιήσετε antialiasing ή να ρυθμίσετε το DPI. Παρακάτω υπάρχει μια σταθερή προεπιλεγμένη διαμόρφωση που ισορροπεί ποιότητα και ταχύτητα. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Pro tip:** Αν χρειάζεστε μόνο κανονικό βάρος, αφαιρέστε τις σημαίες `WebFontStyle`. Για τίτλους μπορεί να θέλετε μόνο το `WebFontStyle.Bold`, ενώ για λεζάντες το `WebFontStyle.Italic`. + +--- + +## Βήμα 3: Απόδοση Σελίδας και **Save Rendered Image** ως PNG + +Με το έγγραφο και τις επιλογές έτοιμες, το τελευταίο βήμα είναι να δημιουργήσετε ένα `ImageRenderer` και να γράψετε το αρχείο εξόδου. Το μπλοκ `using` εξασφαλίζει ότι οι πόροι απελευθερώνονται άμεσα. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +Όταν εκτελέσετε το πρόγραμμα, θα πρέπει να δείτε ένα αρχείο `page.png` στον φάκελο του έργου σας, το οποίο περιέχει ένα πιστό στιγμιότυπο του *example.com*. Ανοίξτε το με οποιονδήποτε προβολέα εικόνων και θα παρατηρήσετε το έντονο‑πλάγιο στυλ που ζητήσαμε νωρίτερα. + +### Αναμενόμενο Αποτέλεσμα + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +Το PNG θα έχει περίπου 800 × 600 px (ανάλογα με τις αρχικές διαστάσεις της σελίδας) με ομαλές άκρες χάρη στο antialiasing. + +--- + +## Πλήρες Παράδειγμα Εργασίας + +Συνδυάζοντας όλα τα παραπάνω, εδώ είναι μια ελάχιστη εφαρμογή console που μπορείτε να αντιγράψετε‑επικολλήσετε στο `Program.cs`. Συγκεντρώνεται και τρέχει αμέσως. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Τρέξτε το με: + +```bash +dotnet run +``` + +…και θα έχετε ένα φρέσκο PNG έτοιμο για αρχειοθέτηση, αποστολή email ή ενσωμάτωση σε αναφορά. + +--- + +## Παραλλαγές & Ακραίες Περιπτώσεις + +### 1. Μετατροπή σε JPEG Αντί για PNG + +Αν το downstream σύστημα σας προτιμά JPEG (μικρότερο μέγεθος αρχείου, απώλεια συμπίεσης), απλώς αλλάξτε την επέκταση αρχείου στο `Save`. Το Aspose.HTML ανιχνεύει αυτόματα τη μορφή από τη διαδρομή. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +Μπορείτε επίσης να ρυθμίσετε την ποιότητα συμπίεσης μέσω `JpegRenderingOptions`. + +### 2. Αλλαγή Διαστάσεων Εικόνας + +Μερικές φορές χρειάζεστε μια μικρογραφία αντί για πλήρες στιγμιότυπο. Ορίστε το `ImageSize` στις επιλογές: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Διαχείριση Σελίδων με Προστασία Αυθεντικοποίησης + +Αν η στοχευμένη URL απαιτεί βασική αυθεντικοποίηση, παρέχετε τα διαπιστευτήρια μέσω `HttpWebRequest` πριν δημιουργήσετε το `HtmlDocument`. Εναλλακτικά, κατεβάστε το HTML μόνοι σας (χρησιμοποιώντας `HttpClient`) και δώστε το ως συμβολοσειρά: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Χρήση Προσαρμοσμένης Γραμματοσειράς + +Το Aspose.HTML μπορεί να ενσωματώσει τοπικές γραμματοσειρές. Καταχωρίστε το φάκελο γραμματοσειρών πριν φορτώσετε το έγγραφο: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Τώρα οποιεσδήποτε δηλώσεις `font-family` στη σελίδα θα αντιστοιχούν στα προσαρμοσμένα αρχεία σας. + +### 5. Απόδοση Πολλών Σελίδων σε Βρόχο + +Αν χρειάζεστε batch‑processing λίστας URL: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Συνηθισμένα Προβλήματα & Πώς να τα Αποφύγετε + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Blank PNG file | `HtmlDocument.IsEmpty` true (page failed to load) | Επαληθεύστε τη URL, ελέγξτε το proxy δικτύου, βεβαιωθείτε ότι είναι ενεργοποιημένο το TLS 1.2. | +| Garbled text on Linux | Font hinting disabled | Ορίστε `renderingOptions.TextOptions.UseHinting = true;`. | +| Watermark on output | No license provided | Καταχωρίστε προσωρινή ή πλήρη άδεια μέσω `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Low‑resolution image | Default DPI 96 is insufficient for print | Αυξήστε τα `renderingOptions.DpiX` και `DpiY` στα 150‑300. | + +--- + +## 🎉 Συμπέρασμα + +Μόλις καλύψαμε όλα όσα χρειάζεστε για **render HTML to image** με το Aspose.HTML σε C#. Από τη φόρτωση απομακρυσμένης σελίδας, τη ρύθμιση antialiasing και **set font style**, μέχρι το τελικό **save rendered image** ως PNG, όλη η ροή εργασίας χωράει σε λίγα συνοπτικά βήματα. + +Τώρα μπορείτε να **convert webpage to PNG** άμεσα, να ενσωματώσετε στιγμιότυπα σε αναφορές ή να δημιουργήσετε μικρογραφίες για κατάλογο—χωρίς ανάγκη αυτοματοποίησης προγράμματος περιήγησης. + +### Τι Ακολουθεί; + +- Πειραματιστείτε με **convert html to png** για διαφορετικά μεγέθη οθόνης (mobile vs desktop). +- Δοκιμάστε εξαγωγή σε PDF χρησιμοποιώντας `PdfRenderer` αν χρειάζεστε εκτυπώσιμο έγγραφο. +- Εξερευνήστε τα API χειρισμού DOM του Aspose.HTML για να ενσωματώσετε υδατογραφήματα ή προσαρμοσμένο CSS πριν την απόδοση. + +Έχετε ερωτήσεις σχετικά με ακραίες περιπτώσεις, άδειες ή βελτιστοποίηση απόδοσης; Αφήστε ένα σχόλιο παρακάτω, και καλή προγραμματιστική! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/greek/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..31ce135c3 --- /dev/null +++ b/html/greek/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-03-14 +description: Απόδοση HTML σε PNG γρήγορα με το Aspose.HTML. Μάθετε πώς να δημιουργείτε + PNG από HTML, να εφαρμόζετε έντονη πλάγια γραμματοσειρά και να αποθηκεύετε το HTML + σε ροή. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: el +og_description: Απόδοση HTML σε PNG με το Aspose.HTML. Αυτός ο οδηγός δείχνει πώς + να δημιουργήσετε PNG από HTML, να χρησιμοποιήσετε έντονη πλάγια γραμματοσειρά και + να αποθηκεύσετε το HTML σε ροή. +og_title: Απόδοση HTML σε PNG σε C# – Πλήρης Οδηγός Προγραμματισμού +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Απόδοση HTML σε PNG σε C# – Οδηγός βήμα‑προς‑βήμα +url: /el/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Απόδοση HTML σε PNG με C# – Πλήρης Οδηγός Προγραμματισμού + +Κάποτε χρειάστηκε να **αποδώσετε HTML σε PNG** αλλά δεν ήξερες ποια βιβλιοθήκη θα σου έδινε αποτελέσματα pixel‑perfect; Δεν είσαι μόνος/η. Σε πολλές αλυσίδες web‑to‑image οι προγραμματιστές αντιμετωπίζουν ελλιπή fonts, θολό κείμενο ή το τρομακτικό “πώς να καταγράψω το HTML χωρίς να το γράψω πρώτα στο δίσκο;”. + +Το θέμα είναι το εξής: το Aspose.HTML κάνει όλη τη διαδικασία παιχνιδάκι. Σε αυτό το tutorial θα **δημιουργήσουμε PNG από HTML**, θα εφαρμόσουμε **στυλ γραμματοσειράς bold italic** και ακόμη θα **αποθηκεύσουμε το HTML σε stream** ώστε να διατηρήσουμε τα πάντα στη μνήμη. Στο τέλος θα έχεις μια έτοιμη κονσόλα που μετατρέπει ένα μικρό απόσπασμα HTML σε ένα καθαρό αρχείο PNG. + +--- + +## Τι Θα Χρειαστείς + +- **.NET 6+** (ο κώδικας λειτουργεί με .NET Core και .NET Framework) +- **Aspose.HTML for .NET** πακέτο NuGet – `Install-Package Aspose.HTML` +- Ένα αγαπημένο IDE (Visual Studio, Rider ή VS Code) – όποιο και αν είναι. + +Καμία επιπλέον γραμματοσειρά, κανένα εξωτερικό εργαλείο και σίγουρα κανένα προσωρινό αρχείο. Απλώς καθαρό C#. + +--- + +## Βήμα 1: Δημιουργία Απλού Εγγράφου HTML + +Το πρώτο που κάνουμε είναι να χτίσουμε ένα έγγραφο HTML στη μνήμη. Σκέψου το ως μια εικονική ιστοσελίδα που ζει μόνο μέσα στη διαδικασία σου. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Γιατί είναι σημαντικό:** Κατασκευάζοντας το DOM προγραμματιστικά αποφεύγεις το κόστος του file‑IO και μπορείς να ενσωματώνεις δυναμικά δεδομένα άμεσα. Η κλάση `HtmlDocument` είναι το σημείο εισόδου για κάθε λειτουργία του Aspose.HTML. + +--- + +## Βήμα 2: Αποθήκευση HTML σε Stream + +Αντί να γράψουμε το markup στο δίσκο, το συλλαμβάνουμε σε έναν προσαρμοσμένο `ResourceHandler`. Αυτό είναι το τμήμα **save html to stream** της ροής εργασίας. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Pro tip:** Η `MemoryHandler` είναι μικρή αλλά ισχυρή. Αν αργότερα χρειαστεί να ενσωματώσεις εικόνες, CSS ή fonts, απλώς επεκτείνε το `HandleResource` ώστε να επιστρέφει τα κατάλληλα streams. + +--- + +## Βήμα 3: Διαμόρφωση Στυλ Γραμματοσειράς Bold Italic + +Όταν αποδίδεις κείμενο, συχνά θέλεις να φαίνεται ακριβώς όπως σε έναν περιηγητή. Το Aspose.HTML σου επιτρέπει να ορίσεις **bold italic font style** απευθείας στις επιλογές απόδοσης. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **Τι συμβαίνει:** +> * `UseAntialiasing` εξομαλύνει τις άκρες των σχημάτων. +> * `UseHinting` βελτιώνει τη θέση των glyphs, κάτι κρίσιμο για μικρό κείμενο. +> * `FontStyle` συνδυάζει τις σημαίες `Bold` και `Italic`, έτσι κάθε κομμάτι κειμένου στο έγγραφο κληρονομεί αυτό το στυλ εκτός αν το παρακάμψει. + +--- + +## Βήμα 4: Απόδοση του Εγγράφου HTML σε Εικόνα PNG + +Τώρα το διασκεδαστικό μέρος – η μετατροπή του HTML σε αρχείο εικόνας. Η `ImageRenderer` κάνει όλη τη βαριά δουλειά. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Αν τρέξεις το πρόγραμμα, θα δεις ένα αρχείο με όνομα `output.png` στον τρέχοντα φάκελο εργασίας. Περιέχει την ετικέτα `` έχουμε ήδη μια έγκυρη δομή HTML έτοιμη για αποθήκευση. + +> **Συμβουλή Pro:** Αν χρειάζεστε ένα πλήρες σκελετό HTML (``, `
`, κλπ.), το Aspose.HTML το δημιουργεί αυτόματα όταν αποθηκεύετε το έγγραφο, ακόμη και αν προσθέσατε μόνο περιεχόμενο σώματος. + +## Βήμα 2: Υλοποίηση ενός **Custom Resource Handler** – Καταγραφή HTML στη Μνήμη + +Ένας *resource handler* λέει στο Aspose.HTML πού να γράψει κάθε πόρο (HTML, CSS, εικόνες, κλπ.). Υπερκαλύπτοντας το `HandleResource` μπορούμε να κατευθύνουμε την έξοδο HTML σε ένα `MemoryStream` αντί για αρχείο. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Why we use a custom handler:** +- **Performance:** Χωρίς I/O δίσκου, όλα παραμένουν στη RAM. +- **Security:** Δεν υπάρχουν προσωρινά αρχεία που θα μπορούσαν να εκτεθούν. +- **Flexibility:** Μπορείτε αργότερα να διοχετεύσετε το stream σε μια απάντηση, μια βάση δεδομένων ή ένα άλλο API. + +## Βήμα 3: Αποθήκευση του Εγγράφου Χρησιμοποιώντας τον Handler – Η Καρδιά του **Generate HTML Programmatically** + +Τώρα συνδέουμε το έγγραφο και τον handler. Όταν εκτελείται `htmlDoc.Save(handler)`, το Aspose.HTML καλεί το `HandleResource`, παραδίδοντάς μας το stream για εγγραφή. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +Σε αυτό το σημείο το `handler.HtmlStream` περιέχει τα ακατέργαστα bytes του HTML. Δεν έχει γραφτεί τίποτα στο δίσκο, και μπορείτε να επαναχρησιμοποιήσετε το stream όσες φορές θέλετε (απλώς θυμηθείτε να επαναφέρετε τη θέση του). + +## Βήμα 4: Ανάγνωση του Παραγόμενου HTML από τη Μνήμη – Επαλήθευση του Αποτελέσματος + +Για να αποδείξουμε ότι όλα λειτούργησαν, επαναφέρουμε τη θέση του stream στην αρχή και διαβάζουμε ξανά το κείμενο. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Αναμενόμενο αποτέλεσμα** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Αν βλέπετε το markup παραπάνω, συγχαρητήρια—έχετε δημιουργήσει επιτυχώς **generate html programmatically** χρησιμοποιώντας το Aspose.HTML και έναν **custom resource handler**. + +## Συνηθισμένες Παραλλαγές & Ακραίες Περιπτώσεις + +### Διαχείριση CSS ή Εικόνων + +Η demo αγνοεί μη‑HTML πόρους επιστρέφοντας `Stream.Null`. Σε πραγματικό σενάριο μπορεί να θέλετε να καταγράψετε επίσης αρχεία CSS ή εικόνες: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Επαναχρησιμοποίηση του Ίδιου Handler για Πολλαπλές Αποθηκεύσεις + +Αν χρειάζεται να δημιουργήσετε πολλά αποσπάσματα HTML σε βρόχο, δημιουργήστε ένα νέο `MemoryHtmlHandler` σε κάθε επανάληψη ή καθαρίστε το υπάρχον stream: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Ασύγχρονη Αποθήκευση (Aspose.HTML 23.4+) + +Οι νεότερες εκδόσεις υποστηρίζουν ασύγχρονη αποθήκευση: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Θυμηθείτε να χρησιμοποιήσετε `await` και να κάνετε τη μέθοδό σας `async`. + +## Πλήρες Παράδειγμα Λειτουργίας + +Παρακάτω είναι το πλήρες πρόγραμμα που μπορείτε να αντιγράψετε‑και‑επικολλήσετε σε μια εφαρμογή console. Περιλαμβάνει όλα τα μέρη που συζητήσαμε, καθώς και μερικά σχόλια για σαφήνεια. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Εκτελέστε το πρόγραμμα (`dotnet run`) και θα δείτε το HTML να εκτυπώνεται στην κονσόλα, ακριβώς όπως εμφανίστηκε νωρίτερα. + +## Συμπέρασμα + +Μόλις δείξαμε πώς να **create HTML document C#** χρησιμοποιώντας το Aspose.HTML, να καταγράψετε το αποτέλεσμα με έναν **custom resource handler**, και να **generate HTML programmatically** χωρίς να αγγίξετε το σύστημα αρχείων. Το μοτίβο κλιμακώνεται—είτε δημιουργείτε πρότυπα email, αναφορές εν κινήσει, ή μια μικρο‑υπηρεσία που επιστρέφει αποσπάσματα HTML. + +Επόμενα βήματα; Δοκιμάστε να προσθέσετε ένα φύλλο CSS μέσω του handler, ή να ρέξετε το HTML απευθείας σε μια απάντηση ASP.NET Core (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Μπορείτε επίσης να συνδέσετε το αποτέλεσμα με έναν μετατροπέα PDF ή μια βιβλιοθήκη HTML‑to‑image για πιο πλούσιες ροές εργασίας. + +Έχετε ερωτήσεις σχετικά με τη διαχείριση εικόνων, την ασύγχρονη αποθήκευση ή την ενσωμάτωση με άλλες βιβλιοθήκες; Αφήστε ένα σχόλιο, και καλή προγραμματιστική! + +{{< /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/rendering-html-documents/_index.md b/html/hindi/net/rendering-html-documents/_index.md index f656f4636..2c5739da3 100644 --- a/html/hindi/net/rendering-html-documents/_index.md +++ b/html/hindi/net/rendering-html-documents/_index.md @@ -57,6 +57,7 @@ Aspose.HTML for .NET में रेंडरिंग टाइमआउट ### [Aspose.HTML के साथ .NET में SVG दस्तावेज़ को PNG के रूप में प्रस्तुत करें](./render-svg-doc-as-png/) .NET के लिए Aspose.HTML की शक्ति अनलॉक करें! SVG Doc को आसानी से PNG के रूप में रेंडर करना सीखें। चरण-दर-चरण उदाहरणों और FAQ में गोता लगाएँ। अभी शुरू करें! + ### [HTML को PNG के रूप में रेंडर करने का पूर्ण C# गाइड](./how-to-render-html-as-png-complete-c-guide/) C# में Aspose.HTML का उपयोग करके HTML को PNG में बदलने के चरण-दर-चरण निर्देश। @@ -65,9 +66,16 @@ Aspose.HTML के साथ HTML को PNG फ़ॉर्मेट में ### [Aspose के साथ HTML को PNG में रेंडर करने का पूर्ण गाइड](./how-to-render-html-to-png-with-aspose-complete-guide/) Aspose.HTML का उपयोग करके HTML को PNG फ़ॉर्मेट में बदलने की पूरी प्रक्रिया सीखें, कोड उदाहरण और टिप्स के साथ। + ### [HTML से PNG बनाएं – पूर्ण C# रेंडरिंग गाइड](./create-png-from-html-full-c-rendering-guide/) HTML को PNG में बदलने के लिए पूर्ण C# रेंडरिंग चरणों को सीखें और Aspose.HTML का उपयोग करके उच्च गुणवत्ता वाले परिणाम प्राप्त करें। +### [C# में HTML को इमेज में रेंडर करें – पूर्ण चरण‑दर‑चरण गाइड](./render-html-to-image-in-c-complete-step-by-step-guide/) +C# में Aspose.HTML का उपयोग करके HTML को इमेज फ़ॉर्मेट में बदलने की पूरी प्रक्रिया सीखें, कोड उदाहरण और टिप्स के साथ। + +### [C# में HTML को PNG में रेंडर करें – चरण‑दर‑चरण गाइड](./render-html-to-png-in-c-step-by-step-guide/) +C# में Aspose.HTML का उपयोग करके HTML को PNG फ़ॉर्मेट में बदलने की विस्तृत चरण‑दर‑चरण प्रक्रिया सीखें। + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/hindi/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/hindi/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..7a57a0c9a --- /dev/null +++ b/html/hindi/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-03-14 +description: Aspose.HTML का उपयोग करके HTML को तेज़ी से इमेज में रेंडर करें। जानिए + कैसे वेबपेज को PNG में बदलें, फ़ॉन्ट स्टाइल सेट करें, और केवल कुछ ही C# लाइनों में + रेंडर की गई इमेज को सहेजें। +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: hi +og_description: Aspose.HTML के साथ HTML को इमेज में रेंडर करें। यह ट्यूटोरियल दिखाता + है कि वेबपेज को PNG में कैसे बदलें, फ़ॉन्ट स्टाइल सेट करें, और C# में रेंडर की गई + इमेज को सहेजें। +og_title: C# में HTML को इमेज में रेंडर करें – त्वरित और आसान गाइड +tags: +- C# +- Aspose.HTML +- Image Rendering +title: C# में HTML को इमेज में रेंडर करें – पूर्ण चरण‑दर‑चरण गाइड +url: /hi/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +markdown with translations. + +Let's assemble. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML को इमेज में रेंडर करें – पूर्ण C# ट्यूटोरियल + +क्या आपको कभी **HTML को इमेज में रेंडर** करने की ज़रूरत पड़ी है लेकिन यह नहीं पता था कि कौन सी लाइब्रेरी चुनें? आप अकेले नहीं हैं। कई वेब‑ऑटोमेशन या रिपोर्टिंग परिदृश्यों में आपको एक लाइव पेज मिलता है जिसे आप PNG, JPEG, या यहाँ तक कि BMP के रूप में संग्रहित करना चाहते हैं। अच्छी खबर यह है कि Aspose.HTML इसे बहुत आसान बना देता है, जिससे आप सिर्फ कुछ लाइनों के कोड से **वेबपेज को PNG में बदल** सकते हैं। + +इस गाइड में हम पूरी प्रक्रिया को चरण‑दर‑चरण देखेंगे: Aspose.HTML पैकेज को इंस्टॉल करने से लेकर, रिमोट URL लोड करने, रेंडरिंग विकल्पों को समायोजित करने (जिसमें **फ़ॉन्ट स्टाइल सेट** करना भी शामिल है), और अंत में **रेंडर की गई इमेज को** डिस्क पर सहेजने तक। अंत तक आपके पास एक तैयार‑चलाने‑योग्य कंसोल ऐप होगा जो किसी भी वेब पेज का स्पष्ट स्क्रीनशॉट बनाता है। + +## आपको क्या चाहिए + +शुरू करने से पहले, सुनिश्चित करें कि आपके पास ये हैं: + +| पूर्वापेक्षा | कारण | +|--------------|--------| +| .NET 6.0 SDK or later | Aspose.HTML .NET Standard 2.0+ को टार्गेट करता है, इसलिए .NET 6 आपको सबसे नवीन रनटाइम देता है। | +| Visual Studio 2022 (or VS Code) | एक आरामदायक IDE डिबगिंग को तेज़ करता है। | +| Aspose.HTML for .NET NuGet package | यह वह इंजन है जो भारी काम करता है। | +| A valid Aspose.HTML license (optional) | लाइसेंस के बिना आउटपुट इमेज पर वॉटरमार्क मिलेगा। | + +आप पैकेज को CLI के माध्यम से प्राप्त कर सकते हैं: + +```bash +dotnet add package Aspose.HTML +``` + +यदि आप GUI पसंद करते हैं, तो NuGet पैकेज मैनेजर में “Aspose.HTML” खोजें। + +--- + +## चरण 1: वह वेब पेज लोड करें जिसे आप रास्टराइज़ करना चाहते हैं + +पहला कदम यह है कि आप Aspose.HTML को एक स्रोत दस्तावेज़ दें। यह स्थानीय फ़ाइल, स्ट्रिंग, या रिमोट URL हो सकता है। अधिकांश वास्तविक‑दुनिया के परिदृश्यों में आप एक लाइव साइट के साथ काम करेंगे, इसलिए चलिए `https://example.com` को इंगित करके **वेबपेज को PNG में बदलते** हैं। + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **क्यों यह महत्वपूर्ण है:** पेज को `HtmlDocument` के रूप में लोड करने से आपको DOM तक पूरी पहुँच मिलती है, जिसका मतलब है कि आप CSS इंजेक्ट कर सकते हैं, लेआउट को बदल सकते हैं, या रास्टराइज़ करने से पहले JavaScript चला सकते हैं। + +--- + +## चरण 2: इमेज रेंडरिंग विकल्प कॉन्फ़िगर करें + +अब जबकि HTML मेमोरी में है, हमें रेंडरर को बताना है कि हम अंतिम चित्र को कैसे देखना चाहते हैं। यहाँ आप **फ़ॉन्ट स्टाइल सेट** कर सकते हैं, एंटी‑एलियासिंग सक्षम कर सकते हैं, या DPI को समायोजित कर सकते हैं। नीचे एक ठोस डिफ़ॉल्ट कॉन्फ़िगरेशन दिया गया है जो गुणवत्ता और गति के बीच संतुलन बनाता है। + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **प्रो टिप:** यदि आपको केवल सामान्य वजन चाहिए, तो `WebFontStyle` फ़्लैग्स को हटा दें। हेडलाइन के लिए आप केवल `WebFontStyle.Bold` उपयोग कर सकते हैं, जबकि कैप्शन के लिए `WebFontStyle.Italic` उपयोग किया जा सकता है। + +--- + +## चरण 3: पेज को रेंडर करें और **रेंडर की गई इमेज सहेजें** PNG के रूप में + +दस्तावेज़ और विकल्प तैयार होने के बाद, अंतिम कदम `ImageRenderer` को इंस्टैंशिएट करना और आउटपुट फ़ाइल लिखना है। `using` ब्लॉक संसाधनों को तुरंत रिलीज़ कर देता है। + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +जब आप प्रोग्राम चलाते हैं, तो आपको अपने प्रोजेक्ट फ़ोल्डर में एक `page.png` फ़ाइल दिखनी चाहिए जिसमें *example.com* का सटीक स्नैपशॉट हो। इसे किसी भी इमेज व्यूअर से खोलें और आप पहले अनुरोधित बोल्ड‑इटैलिक स्टाइलिंग देखेंगे। + +### अपेक्षित आउटपुट + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +PNG लगभग 800 × 600 px का होगा (पेज के मूल आयामों पर निर्भर) और एंटी‑एलियासिंग के कारण किनारे स्मूद होंगे। + +--- + +## पूर्ण कार्यशील उदाहरण + +सब कुछ मिलाकर, यहाँ एक न्यूनतम कंसोल ऐप है जिसे आप `Program.cs` में कॉपी‑पेस्ट कर सकते हैं। यह बिना किसी अतिरिक्त सेटिंग के कंपाइल और चल जाता है। + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +इसे चलाएँ: + +```bash +dotnet run +``` + +…और आपके पास एक नई PNG तैयार होगी जिसे आप संग्रहित, ईमेल, या रिपोर्ट में एम्बेड कर सकते हैं। + +--- + +## विविधताएँ और किनारे के मामले + +### 1. PNG के बजाय JPEG में बदलना + +यदि आपका डाउनस्ट्रीम सिस्टम JPEG को पसंद करता है (छोटी फ़ाइल आकार, लॉसी कॉम्प्रेशन), तो बस `Save` में फ़ाइल एक्सटेंशन बदल दें। Aspose.HTML पाथ से फ़ॉर्मेट को स्वतः पहचान लेता है। + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +आप `JpegRenderingOptions` के माध्यम से कॉम्प्रेशन क्वालिटी भी समायोजित कर सकते हैं। + +### 2. इमेज के आयाम बदलना + +कभी‑कभी आपको पूर्ण‑आकार स्क्रीनशॉट के बजाय थंबनेल चाहिए। विकल्पों में `ImageSize` सेट करें: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. प्रमाणीकरण‑सुरक्षित पेजों को संभालना + +यदि लक्ष्य URL को बेसिक ऑथेंटिकेशन की आवश्यकता है, तो `HtmlDocument` बनाने से पहले `HttpWebRequest` के माध्यम से क्रेडेंशियल्स प्रदान करें। वैकल्पिक रूप से, स्वयं HTML डाउनलोड करें (`HttpClient` का उपयोग करके) और इसे स्ट्रिंग के रूप में फीड करें: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. कस्टम फ़ॉन्ट का उपयोग करना + +Aspose.HTML स्थानीय फ़ॉन्ट्स को एम्बेड कर सकता है। दस्तावेज़ लोड करने से पहले फ़ॉन्ट फ़ोल्डर को रजिस्टर करें: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +### 5. लूप में कई पेज रेंडर करना + +यदि आपको URL की सूची को बैच‑प्रोसेस करना है: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## सामान्य समस्याएँ और उनके समाधान + +| लक्षण | संभावित कारण | समाधान | +|---------|--------------|-----| +| खाली PNG फ़ाइल | `HtmlDocument.IsEmpty` true (पेज लोड नहीं हुआ) | URL सत्यापित करें, नेटवर्क प्रॉक्सी जांचें, सुनिश्चित करें कि TLS 1.2 सक्षम है। | +| Linux पर गड़बड़ टेक्स्ट | फ़ॉन्ट हिन्टिंग अक्षम है | सेट करें `renderingOptions.TextOptions.UseHinting = true;`। | +| आउटपुट पर वॉटरमार्क | लाइसेंस प्रदान नहीं किया गया | अस्थायी या पूर्ण लाइसेंस को `License license = new License(); license.SetLicense("Aspose.Total.lic");` के माध्यम से रजिस्टर करें। | +| कम‑रिज़ॉल्यूशन इमेज | डिफ़ॉल्ट DPI 96 प्रिंट के लिए अपर्याप्त है | `renderingOptions.DpiX` और `DpiY` को 150‑300 तक बढ़ाएँ। | + +--- + +## 🎉 निष्कर्ष + +हमने अभी-अभी Aspose.HTML के साथ C# में **HTML को इमेज में रेंडर** करने के लिए आवश्यक सभी चीज़ें कवर कर ली हैं। रिमोट पेज लोड करने, एंटी‑एलियासिंग और **फ़ॉन्ट स्टाइल सेट** करने से लेकर अंत में **रेंडर की गई इमेज को** PNG के रूप में **सहेजने** तक, पूरा वर्कफ़्लो कुछ संक्षिप्त चरणों में फिट हो जाता है। + +अब आप तुरंत **वेबपेज को PNG में बदल** सकते हैं, रिपोर्ट में स्क्रीनशॉट एम्बेड कर सकते हैं, या कैटलॉग के लिए थंबनेल बना सकते हैं—बिना किसी ब्राउज़र ऑटोमेशन के। + +### आगे क्या? + +- विभिन्न स्क्रीन आकारों (मोबाइल बनाम डेस्कटॉप) के लिए **convert html to png** के साथ प्रयोग करें। +- यदि आपको प्रिंटेबल दस्तावेज़ चाहिए तो `PdfRenderer` का उपयोग करके PDF निर्यात करने की कोशिश करें। +- रेंडर करने से पहले वॉटरमार्क या कस्टम CSS इंजेक्ट करने के लिए Aspose.HTML के DOM मैनिपुलेशन API में गहराई से जाएँ। + +एज केस, लाइसेंसिंग, या प्रदर्शन ट्यूनिंग के बारे में प्रश्न हैं? नीचे टिप्पणी छोड़ें, और कोडिंग का आनंद लें! + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/hindi/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..15bdf8317 --- /dev/null +++ b/html/hindi/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-03-14 +description: Aspose.HTML के साथ HTML को जल्दी से PNG में रेंडर करें। जानिए कैसे HTML + से PNG जेनरेट करें, बोल्ड इटैलिक फ़ॉन्ट स्टाइल लागू करें, और HTML को स्ट्रीम में + सहेजें। +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: hi +og_description: Aspose.HTML के साथ HTML को PNG में रेंडर करें। यह गाइड दिखाता है कि + HTML से PNG कैसे जनरेट करें, बोल्ड इटैलिक फ़ॉन्ट स्टाइल का उपयोग करें, और HTML को + स्ट्रीम में कैसे सहेजें। +og_title: C# में HTML को PNG में रेंडर करें – पूर्ण प्रोग्रामिंग वॉकथ्रू +tags: +- Aspose.HTML +- C# +- Image Rendering +title: C# में HTML को PNG में रेंडर करें – चरण-दर-चरण मार्गदर्शिका +url: /hi/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में HTML को PNG में रेंडर करें – पूर्ण प्रोग्रामिंग वॉकथ्रू + +क्या आपको **HTML को PNG में रेंडर** करने की ज़रूरत पड़ी है लेकिन सही लाइब्रेरी नहीं मिली जिससे पिक्सेल‑परफेक्ट रिज़ल्ट मिले? आप अकेले नहीं हैं। कई वेब‑टू‑इमेज पाइपलाइन में डेवलपर्स फ़ॉन्ट्स की कमी, धुंधला टेक्स्ट, या “HTML को डिस्क पर लिखे बिना कैसे कैप्चर करें?” जैसी समस्याओं से जूझते हैं। + +बात यह है कि: Aspose.HTML पूरी प्रक्रिया को आसान बना देता है। इस ट्यूटोरियल में हम **HTML से PNG जेनरेट** करेंगे, **बोल्ड इटैलिक फ़ॉन्ट स्टाइल** लागू करेंगे, और **HTML को स्ट्रीम में सेव** करेंगे ताकि सब कुछ मेमोरी में रहे। अंत में आपके पास एक तैयार‑चलाने‑योग्य कंसोल ऐप होगा जो छोटे HTML स्निपेट को एक साफ़ PNG फ़ाइल में बदल देगा। + +--- + +## आपको क्या चाहिए + +- **.NET 6+** (कोड .NET Core और .NET Framework दोनों पर काम करता है) +- **Aspose.HTML for .NET** NuGet पैकेज – `Install-Package Aspose.HTML` +- आपका पसंदीदा IDE (Visual Studio, Rider, या VS Code) – कोई भी चलेगा। + +कोई अतिरिक्त फ़ॉन्ट्स नहीं, कोई बाहरी टूल नहीं, और बिल्कुल भी टेम्पररी फ़ाइलें नहीं। सिर्फ़ शुद्ध C#। + +--- + +## चरण 1: एक साधारण HTML दस्तावेज़ बनाएं + +सबसे पहले हम एक इन‑मेमोरी HTML दस्तावेज़ बनाते हैं। इसे एक वर्चुअल वेब पेज समझें जो केवल आपके प्रोसेस के अंदर रहता है। + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **क्यों महत्वपूर्ण है:** प्रोग्रामेटिकली DOM बनाकर आप फ़ाइल‑IO ओवरहेड से बचते हैं और रन‑टाइम पर डायनामिक डेटा इन्जेक्ट कर सकते हैं। `HtmlDocument` क्लास हर Aspose.HTML ऑपरेशन की एंट्री पॉइंट है। + +--- + +## चरण 2: HTML को स्ट्रीम में सेव करें + +मार्कअप को डिस्क पर लिखने की बजाय, हम इसे एक कस्टम `ResourceHandler` में कैप्चर करते हैं। यही **save html to stream** वर्कफ़्लो का हिस्सा है। + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **प्रो टिप:** `MemoryHandler` छोटा लेकिन शक्तिशाली है। यदि बाद में आपको इमेजेज, CSS, या फ़ॉन्ट्स एम्बेड करने की ज़रूरत पड़े, तो बस `HandleResource` को विस्तारित करके उचित स्ट्रीम रिटर्न करें। + +--- + +## चरण 3: बोल्ड इटैलिक फ़ॉन्ट स्टाइल कॉन्फ़िगर करें + +जब आप टेक्स्ट रेंडर करते हैं, तो अक्सर आप चाहते हैं कि वह ब्राउज़र जैसा ही दिखे। Aspose.HTML आपको **bold italic font style** सीधे रेंडरिंग ऑप्शन में सेट करने की सुविधा देता है। + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **क्या हो रहा है:** +> * `UseAntialiasing` आकारों के किनारों को स्मूद करता है। +> * `UseHinting` ग्लिफ़ पोज़िशनिंग को बेहतर बनाता है, जो छोटे टेक्स्ट के लिए महत्वपूर्ण है। +> * `FontStyle` `Bold` और `Italic` फ़्लैग्स को मिलाता है, इसलिए दस्तावेज़ में हर टेक्स्ट उस स्टाइल को इनहेरिट करता है जब तक कि ओवरराइड न किया गया हो। + +--- + +## चरण 4: HTML दस्तावेज़ को PNG इमेज में रेंडर करें + +अब मज़ेदार हिस्सा – HTML को इमेज फ़ाइल में बदलना। `ImageRenderer` सारी मेहनत करता है। + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +यदि आप प्रोग्राम चलाते हैं, तो कार्य निर्देशिका में `output.png` नाम की फ़ाइल दिखाई देगी। इसमें `` एलिमेंट जोड़ने से हमारे पास एक वैध HTML स्ट्रक्चर तैयार हो जाता है जिसे सेव किया जा सकता है। + +> **Pro tip:** अगर आपको पूरा HTML स्केलेटन (``, `
`, आदि) चाहिए, तो Aspose.HTML स्वचालित रूप से इसे जेनरेट कर देता है जब आप डॉक्यूमेंट को सेव करते हैं, भले ही आपने केवल बॉडी कंटेंट ही जोड़ी हो। + +## Step 2: Implement a **Custom Resource Handler** – Capture HTML In‑Memory + +एक *resource handler* Aspose.HTML को बताता है कि प्रत्येक रिसोर्स (HTML, CSS, इमेजेज़, आदि) कहाँ लिखना है। `HandleResource` को ओवरराइड करके हम HTML आउटपुट को `MemoryStream` में रीडायरेक्ट कर सकते हैं, फ़ाइल की बजाय। + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Why we use a custom handler:** +- **Performance:** डिस्क I/O नहीं, सब कुछ RAM में रहता है। +- **Security:** कोई टेम्पररी फ़ाइल नहीं जो एक्सपोज़ हो सके। +- **Flexibility:** बाद में आप स्ट्रीम को रिस्पॉन्स, डेटाबेस, या किसी अन्य API में पाइप कर सकते हैं। + +## Step 3: Save the Document Using the Handler – The Heart of **Generate HTML Programmatically** + +अब हम डॉक्यूमेंट और हैंडलर को जोड़ते हैं। जब `htmlDoc.Save(handler)` चलता है, तो Aspose.HTML `HandleResource` को कॉल करता है, और हमें स्ट्रीम मिलती है जिसमें लिखना है। + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +इस चरण पर `handler.HtmlStream` में कच्चे HTML बाइट्स होते हैं। कुछ भी डिस्क पर नहीं लिखा गया, और आप इस स्ट्रीम को जितनी बार चाहें री‑यूज़ कर सकते हैं (बस उसकी पोज़िशन रीसेट करना याद रखें)। + +## Step 4: Read the Generated HTML from Memory – Verify the Output + +सभी कुछ सही काम कर रहा है यह साबित करने के लिए, हम स्ट्रीम की पोज़िशन को शुरू में रीसेट करते हैं और टेक्स्ट को वापस पढ़ते हैं। + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Expected output** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +अगर आप ऊपर दिया गया मार्कअप देखते हैं, तो बधाई—आपने सफलतापूर्वक **generate html programmatically** Aspose.HTML और एक **custom resource handler** की मदद से किया है। + +## Common Variations & Edge Cases + +### Handling CSS or Images + +डेमो non‑HTML रिसोर्सेज़ को `Stream.Null` रिटर्न करके इग्नोर करता है। वास्तविक परिदृश्य में आप CSS फ़ाइलें या इमेजेज़ भी कैप्चर करना चाह सकते हैं: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Re‑using the Same Handler for Multiple Saves + +अगर आपको लूप में कई HTML स्निपेट्स जेनरेट करने हैं, तो प्रत्येक इटरशन में एक नया `MemoryHtmlHandler` बनाएं या मौजूदा स्ट्रीम को क्लियर करें: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Async Saving (Aspose.HTML 23.4+) + +नए वर्ज़न async सेविंग को सपोर्ट करते हैं: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +`await` करना याद रखें और अपने मेथड को `async` बनाएं। + +## Full Working Example + +नीचे पूरा प्रोग्राम दिया गया है जिसे आप कंसोल ऐप में कॉपी‑पेस्ट कर सकते हैं। इसमें हमने सभी हिस्से शामिल किए हैं, साथ ही स्पष्टता के लिए कुछ कमेंट्स भी जोड़े हैं। + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +प्रोग्राम चलाएँ (`dotnet run`) और आपको कंसोल में वही HTML प्रिंट होता दिखेगा जैसा पहले दिखाया गया था। + +## Conclusion + +हमने दिखाया कि कैसे **create HTML document C#** Aspose.HTML की मदद से किया जाता है, आउटपुट को एक **custom resource handler** से कैप्चर किया जाता है, और **generate HTML programmatically** बिना फ़ाइल सिस्टम को छुए। यह पैटर्न स्केलेबल है—चाहे आप ईमेल टेम्पलेट्स बना रहे हों, ऑन‑द‑फ़्लाई रिपोर्ट्स, या एक माइक्रो‑सर्विस जो HTML स्निपेट्स रिटर्न करता है। + +अगला कदम? हैंडलर के माध्यम से एक CSS स्टाइलशीट जोड़ें, या HTML को सीधे ASP.NET Core रिस्पॉन्स में स्ट्रीम करें (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`)। आप आउटपुट को PDF कन्वर्टर या HTML‑to‑image लाइब्रेरी में भी फीड कर सकते हैं ताकि वर्कफ़्लो और भी रिच हो जाए। + +इमेजेज़ हैंडलिंग, async सेविंग, या अन्य लाइब्रेरीज़ के इंटीग्रेशन के बारे में सवाल हों तो कमेंट करें, और हैप्पी कोडिंग! + +{{< /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/rendering-html-documents/_index.md b/html/hongkong/net/rendering-html-documents/_index.md index dcea15c4c..092e82022 100644 --- a/html/hongkong/net/rendering-html-documents/_index.md +++ b/html/hongkong/net/rendering-html-documents/_index.md @@ -45,6 +45,7 @@ Aspose.HTML for .NET 因其豐富的功能、優秀的文件和活躍的社群 ### [如何將 HTML 渲染為 PNG – 完整 C# 指南](./how-to-render-html-as-png-complete-c-guide/) 學習使用 Aspose.HTML for .NET 在 C# 中將 HTML 渲染為 PNG,涵蓋完整步驟與最佳實踐。 + ### [從 HTML 建立 PNG – 完整 C# 渲染指南](./create-png-from-html-full-c-rendering-guide/) 學習如何使用 Aspose.HTML for .NET 以 C# 完整渲染 HTML 並將其保存為 PNG 圖像。 @@ -69,6 +70,12 @@ Aspose.HTML for .NET 因其豐富的功能、優秀的文件和活躍的社群 ### [如何使用 Aspose 將 HTML 渲染為 PNG – 完整指南](./how-to-render-html-to-png-with-aspose-complete-guide/) 完整步驟教您使用 Aspose.HTML for .NET 將 HTML 轉換為 PNG 圖像,掌握所有設定與最佳實踐。 +### [在 C# 中將 HTML 渲染為圖像 – 完整步驟指南](./render-html-to-image-in-c-complete-step-by-step-guide/) +一步步教您使用 Aspose.HTML for .NET 在 C# 中將 HTML 渲染為圖像,完整指南與最佳實踐。 + +### [在 C# 中將 HTML 渲染為 PNG – 步驟指南](./render-html-to-png-in-c-step-by-step-guide/) +一步步教您使用 Aspose.HTML for .NET 在 C# 中將 HTML 轉換為 PNG 圖像,掌握渲染技巧與設定。 + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/hongkong/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/hongkong/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..6d60677b2 --- /dev/null +++ b/html/hongkong/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,283 @@ +--- +category: general +date: 2026-03-14 +description: 使用 Aspose.HTML 快速將 HTML 渲染為圖像。了解如何將網頁轉換為 PNG、設定字型樣式,並僅用幾行 C# 程式碼保存渲染後的圖像。 +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: zh-hant +og_description: 使用 Aspose.HTML 將 HTML 渲染為圖像。本教學示範如何將網頁轉換為 PNG、設定字型樣式,並在 C# 中儲存渲染後的圖像。 +og_title: 在 C# 中將 HTML 渲染為圖像 – 快速簡易指南 +tags: +- C# +- Aspose.HTML +- Image Rendering +title: 在 C# 中將 HTML 渲染為圖像 – 完整逐步指南 +url: /zh-hant/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +content. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 將 HTML 轉換為圖像 – 完整 C# 教程 + +是否曾經需要 **render HTML to image** 卻不確定該選擇哪個函式庫?你並非唯一遇到此情況的人。在許多網頁自動化或報告情境中,你會得到一個即時的網頁,想要將其存檔為 PNG、JPEG,甚至 BMP。好消息是 Aspose.HTML 讓這變得輕而易舉,只需幾行程式碼即可 **convert webpage to PNG**。 + +在本指南中,我們將逐步說明整個流程:從安裝 Aspose.HTML 套件、載入遠端 URL、微調渲染選項(包括如何 **set font style**),最後 **save rendered image** 到磁碟。完成後,你將擁有一個可直接執行的主控台應用程式,能產生任何網頁的清晰螢幕截圖。 + +## 需要的條件 + +| Prerequisite | Reason | +|--------------|--------| +| .NET 6.0 SDK or later | Aspose.HTML 目標為 .NET Standard 2.0+,因此 .NET 6 為你提供最新的執行環境。 | +| Visual Studio 2022 (or VS Code) | 舒適的 IDE 能加快除錯速度。 | +| Aspose.HTML for .NET NuGet package | 這是負責執行主要工作的引擎。 | +| A valid Aspose.HTML license (optional) | 若未提供授權,輸出圖像會出現浮水印。 | + +You can grab the package via the CLI: + +```bash +dotnet add package Aspose.HTML +``` + +如果你偏好使用圖形介面,只需在 NuGet 套件管理員中搜尋 “Aspose.HTML”。 + +--- + +## 步驟 1:載入要光柵化的網頁 + +首先,你需要為 Aspose.HTML 提供一個來源文件。它可以是本機檔案、字串,或遠端 URL。在大多數實務情境中,你會處理即時網站,因此讓我們透過指向 `https://example.com` 來 **convert webpage to PNG**。 + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **為什麼這很重要:** 將頁面載入為 `HtmlDocument` 可讓你完整存取 DOM,這意味著你可以在光柵化前注入 CSS、操作版面配置,甚至執行 JavaScript。 + +--- + +## 步驟 2:設定圖像渲染選項 + +現在 HTML 已載入記憶體,我們需要告訴渲染器最終圖像的外觀。此處可 **set font style**、啟用抗鋸齒或調整 DPI。以下是一個兼顧品質與速度的預設配置。 + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **專業提示:** 若只需要一般字重,可省略 `WebFontStyle` 標誌。標題可僅使用 `WebFontStyle.Bold`,而說明文字則可使用 `WebFontStyle.Italic`。 + +--- + +## 步驟 3:渲染頁面並 **Save Rendered Image** 為 PNG + +文件與選項準備就緒後,最後一步是實例化 `ImageRenderer` 並寫入輸出檔案。`using` 區塊可確保資源即時釋放。 + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +執行程式後,你應該會在專案資料夾中看到 `page.png` 檔案,裡面是 *example.com* 的忠實快照。使用任何圖像檢視器開啟,你會看到先前要求的粗斜體樣式。 + +### 預期輸出 + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +此 PNG 大約為 800 × 600 px(視頁面原始尺寸而定),因啟用抗鋸齒而呈現平滑邊緣。 + +--- + +## 完整範例程式 + +將所有步驟整合起來,以下是一個可直接複製貼上至 `Program.cs` 的最小主控台應用程式。它可直接編譯執行。 + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Run it with: + +```bash +dotnet run +``` + +…即可得到一張全新的 PNG,適合用於存檔、電郵或嵌入報告中。 + +--- + +## 變體與特殊情況 + +### 1. 轉換為 JPEG 而非 PNG + +如果下游系統較偏好 JPEG(檔案較小、採用有損壓縮),只需在 `Save` 中更改檔案副檔名。Aspose.HTML 會自動從路徑偵測格式。 + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +亦可透過 `JpegRenderingOptions` 調整壓縮品質。 + +### 2. 調整圖像尺寸 + +有時你需要縮圖而非完整螢幕截圖。於選項中設定 `ImageSize`: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. 處理需要驗證的頁面 + +若目標 URL 需要基本驗證,請在建立 `HtmlDocument` 前透過 `HttpWebRequest` 提供認證資訊。或者自行下載 HTML(使用 `HttpClient`),再以字串方式傳入: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. 使用自訂字型 + +Aspose.HTML 能嵌入本機字型。載入文件前先註冊字型資料夾: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +現在頁面中的任何 `font-family` 宣告都會解析為你的自訂字型檔案。 + +### 5. 於迴圈中渲染多個頁面 + +若需批次處理多個 URL: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## 常見陷阱與避免方法 + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| 空白 PNG 檔案 | `HtmlDocument.IsEmpty` 為 true(頁面載入失敗) | 確認 URL、檢查網路代理,確保已啟用 TLS 1.2。 | +| Linux 上文字亂碼 | 字型 hinting 已停用 | 設定 `renderingOptions.TextOptions.UseHinting = true;`。 | +| 輸出圖像有浮水印 | 未提供授權 | 透過 `License license = new License(); license.SetLicense("Aspose.Total.lic");` 註冊臨時或正式授權。 | +| 低解析度圖像 | 預設 DPI 96 無法滿足列印需求 | 將 `renderingOptions.DpiX` 與 `DpiY` 提升至 150‑300。 | + +--- + +## 🎉 結論 + +我們已完整說明如何在 C# 中使用 Aspose.HTML **render HTML to image**。從載入遠端頁面、設定抗鋸齒與 **set font style**,到最終 **save rendered image** 為 PNG,整個工作流程僅需幾個簡潔步驟即可完成。 + +現在你可以即時 **convert webpage to PNG**,將螢幕截圖嵌入報告,或為目錄產生縮圖——無需瀏覽器自動化。 + +### 接下來? + +- 嘗試不同螢幕尺寸(行動裝置 vs 桌面)下的 **convert html to png**。 +- 若需可列印文件,可嘗試使用 `PdfRenderer` 匯出為 PDF。 +- 深入研究 Aspose.HTML 的 DOM 操作 API,在渲染前注入浮水印或自訂 CSS。 + +對於特殊情況、授權或效能調校有任何疑問嗎?歡迎在下方留言,祝編程愉快! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/hongkong/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..8c10dacf1 --- /dev/null +++ b/html/hongkong/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-03-14 +description: 使用 Aspose.HTML 快速將 HTML 渲染為 PNG。了解如何從 HTML 產生 PNG、套用粗斜體字型樣式,以及將 HTML + 儲存至串流。 +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: zh-hant +og_description: 使用 Aspose.HTML 將 HTML 轉換為 PNG。本指南說明如何從 HTML 產生 PNG、使用粗斜體字型樣式,以及將 HTML + 儲存至串流。 +og_title: 在 C# 中將 HTML 渲染為 PNG – 完整程式教學 +tags: +- Aspose.HTML +- C# +- Image Rendering +title: 在 C# 中將 HTML 轉換為 PNG – 步驟指南 +url: /zh-hant/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中將 HTML 轉換為 PNG – 完整程式教學 + +曾經需要 **render HTML to PNG**,卻不確定哪個函式庫能提供像素完美的結果嗎?你並不孤單。在許多 web‑to‑image 工作流程中,開發人員常會碰到缺少字型、文字模糊,或是那個令人頭疼的「如何在不先寫入磁碟的情況下擷取 HTML?」 + +事實是:Aspose.HTML 讓整個流程變得輕而易舉。在本教學中,我們將 **generate PNG from HTML**、套用 **bold italic font style**,甚至 **save HTML to a stream**,讓你可以將所有資料保留在記憶體中。完成後,你將擁有一個可直接執行的主控台應用程式,將小段 HTML 轉換為清晰的 PNG 檔案。 + +--- + +## 你需要的環境 + +- **.NET 6+**(此程式碼同時支援 .NET Core 與 .NET Framework) +- **Aspose.HTML for .NET** NuGet 套件 – `Install-Package Aspose.HTML` +- 你喜愛的 IDE(Visual Studio、Rider 或 VS Code)– 任意即可。 + +不需要額外字型、外部工具,絕對不會產生暫存檔。純粹使用 C#。 + +--- + +## 步驟 1:建立簡易 HTML 文件 + +我們首先建立一個記憶體中的 HTML 文件。可以把它想像成只存在於程式執行期間的虛擬網頁。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Why this matters:** 透過程式化建構 DOM,你可以避免檔案 I/O 的開銷,並且即時注入動態資料。`HtmlDocument` 類別是所有 Aspose.HTML 操作的入口點。 + +--- + +## 步驟 2:將 HTML 儲存至串流 + +我們不將標記寫入磁碟,而是捕獲到自訂的 `ResourceHandler` 中。這就是工作流程中的 **save html to stream** 部分。 + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Pro tip:** `MemoryHandler` 雖小卻功能強大。如果之後需要嵌入圖片、CSS 或字型,只要擴充 `HandleResource` 以回傳相應的串流即可。 + +--- + +## 步驟 3:設定粗斜體字型樣式 + +當你渲染文字時,通常希望它看起來與瀏覽器中完全相同。Aspose.HTML 允許直接在渲染選項上設定 **bold italic font style**。 + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **What’s happening:** +> * `UseAntialiasing` 平滑形狀的邊緣。 +> * `UseHinting` 改善字形定位,對小字體尤為重要。 +> * `FontStyle` 結合 `Bold` 與 `Italic` 旗標,使文件中所有文字預設繼承此樣式,除非另行覆寫。 + +--- + +## 步驟 4:將 HTML 文件渲染為 PNG 圖片 + +現在最有趣的部分——將 HTML 轉換為影像檔。`ImageRenderer` 負責所有繁重的工作。 + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +執行程式後,你會在工作目錄看到名為 `output.png` 的檔案。裡面包含以粗斜體樣式渲染的 `` 元素,就已經擁有可供儲存的有效 HTML 結構。 + +> **專業提示:** 若你需要完整的 HTML 骨架(``、`
` 等),Aspose.HTML 在儲存文件時會自動產生,即使你只加入了 body 內容。 + +## 步驟 2:實作 **Custom Resource Handler** – 在記憶體中捕獲 HTML + +*資源處理程式* 告訴 Aspose.HTML 每個資源(HTML、CSS、圖片等)要寫入哪裡。透過覆寫 `HandleResource`,我們可以把 HTML 輸出導向 `MemoryStream`,而非檔案。 + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**為什麼使用自訂處理程式:** +- **效能:** 無磁碟 I/O,全部留在 RAM。 +- **安全性:** 不會產生可能被外洩的暫存檔。 +- **彈性:** 之後可以把串流直接傳給回應、資料庫或其他 API。 + +## 步驟 3:使用處理程式儲存文件 – **Generate HTML Programmatically** 的核心 + +現在把文件與處理程式結合起來。當執行 `htmlDoc.Save(handler)` 時,Aspose.HTML 會呼叫 `HandleResource`,把我們的串流交給它寫入。 + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +此時 `handler.HtmlStream` 已經包含原始的 HTML 位元組。沒有任何資料寫入磁碟,你可以隨意重複使用這個串流(只要記得重設位置)。 + +## 步驟 4:從記憶體讀取產生的 HTML – 驗證輸出 + +為了證明一切正常,我們把串流位置重設回開頭,然後把文字讀回來。 + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**預期輸出** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +如果你看到上面的標記,恭喜你!你已成功使用 Aspose.HTML 與 **custom resource handler** **generate html programmatically**。 + +## 常見變形與邊緣案例 + +### 處理 CSS 或圖片 + +示範程式會以回傳 `Stream.Null` 方式忽略非 HTML 資源。實務上,你可能也想捕獲 CSS 檔或圖片: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### 在多次儲存時重複使用同一個處理程式 + +如果需要在迴圈中產生多個 HTML 片段,請在每次迭代時建立新的 `MemoryHtmlHandler`,或是清除現有的串流: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### 非同步儲存(Aspose.HTML 23.4+) + +較新版本支援非同步儲存: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +記得使用 `await`,並將方法宣告為 `async`。 + +## 完整可執行範例 + +以下是完整程式碼,你可以直接貼到 console 應用程式中。程式碼已包含前述所有要素,並加上說明註解。 + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +執行程式 (`dotnet run`) 後,你應該會在主控台看到與前面示範相同的 HTML 輸出。 + +## 結論 + +我們剛剛示範了如何使用 Aspose.HTML **create HTML document C#**,搭配 **custom resource handler** 捕獲輸出,並 **generate HTML programmatically** 而不觸及檔案系統。這套模式具備可擴充性——無論是製作電子郵件範本、即時報表,或是回傳 HTML 片段的微服務,都能輕鬆應用。 + +接下來的步驟?嘗試在處理程式中加入 CSS 樣式表,或直接將 HTML 串流寫入 ASP.NET Core 回應 (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`)。你也可以把輸出接到 PDF 轉換器或 HTML‑to‑image 函式庫,打造更豐富的工作流程。 + +對於圖片處理、非同步儲存或與其他函式庫整合有任何問題,歡迎留言討論,祝開發順利! + +{{< /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/rendering-html-documents/_index.md b/html/hungarian/net/rendering-html-documents/_index.md index 39529197d..f792443ee 100644 --- a/html/hungarian/net/rendering-html-documents/_index.md +++ b/html/hungarian/net/rendering-html-documents/_index.md @@ -60,6 +60,10 @@ Tanulja meg, hogyan renderelhet HTML-t PNG formátumba az Aspose segítségével Ismerje meg, hogyan konvertálhatja a HTML-t PNG-be az Aspose segítségével .NET környezetben, lépésről lépésre. ### [PNG létrehozása HTML-ből – Teljes C# renderelési útmutató](./create-png-from-html-full-c-rendering-guide/) Tanulja meg, hogyan hozhat létre PNG képeket HTML-ből C#-ban az Aspose.HTML segítségével. +### [HTML renderelése képpé C#‑ban – Teljes lépésről‑lépésre útmutató](./render-html-to-image-in-c-complete-step-by-step-guide/) +Tanulja meg, hogyan renderelhet HTML-t képpé C#‑ban az Aspose.HTML segítségével, lépésről lépésre útmutató. +### [HTML renderelése PNG formátumba C#‑ban – Lépésről‑lépésre útmutató](./render-html-to-png-in-c-step-by-step-guide/) +Tanulja meg, hogyan renderelhet HTML-t PNG-be C#-ban az Aspose.HTML segítségével, részletes lépésről‑lépésre útmutató. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/hungarian/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/hungarian/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..8eb722ac9 --- /dev/null +++ b/html/hungarian/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-03-14 +description: HTML-t gyorsan képpé renderel az Aspose.HTML használatával. Tanulja meg, + hogyan konvertálja a weboldalt PNG formátumba, állítson be betűstílust, és mentse + el a renderelt képet néhány C# sorral. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: hu +og_description: HTML renderelése képpé az Aspose.HTML segítségével. Ez az útmutató + bemutatja, hogyan konvertálhatja a weboldalt PNG formátumba, állíthatja be a betűstílust, + és mentheti a renderelt képet C#‑ban. +og_title: HTML képpé renderelése C#-ban – Gyors és egyszerű útmutató +tags: +- C# +- Aspose.HTML +- Image Rendering +title: HTML képpé renderelése C#‑ban – Teljes lépésről‑lépésre útmutató +url: /hu/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML megjelenítése képként – Teljes C# útmutató + +Valaha is szükséged volt **HTML képpé renderelésére**, de nem tudtad, melyik könyvtárat válaszd? Nem vagy egyedül. Sok web‑automatizálási vagy jelentéskészítési szituációban egy élő oldalt szeretnél PNG‑ként, JPEG‑ként vagy akár BMP‑ként archiválni. A jó hír, hogy az Aspose.HTML ezt gyerekjátékká teszi, lehetővé téve a **weboldal PNG‑re konvertálását** néhány sor kóddal. + +Ebben az útmutatóban végigvezetünk a teljes folyamaton: az Aspose.HTML csomag telepítésétől, egy távoli URL betöltéséig, a renderelési beállítások finomhangolásáig (beleértve a **betűstílus beállítását**), és végül a **renderelt kép mentéséig** a lemezre. A végére egy futtatható konzolalkalmazásod lesz, amely tiszta képernyőképet készít bármely weboldalról. + +## Amire szükséged lesz + +Mielőtt belevágnánk, győződj meg róla, hogy a következőkkel rendelkezel: + +| Előfeltétel | Indok | +|--------------|--------| +| .NET 6.0 SDK vagy újabb | Az Aspose.HTML a .NET Standard 2.0+ célplatformot használja, a .NET 6 a legfrissebb futtatókörnyezetet biztosítja. | +| Visual Studio 2022 (vagy VS Code) | Egy kényelmes IDE felgyorsítja a hibakeresést. | +| Aspose.HTML for .NET NuGet csomag | Ez a motor, amely a nehéz munkát végzi. | +| Érvényes Aspose.HTML licenc (opcionális) | Licenc nélkül vízjel jelenik meg a kimeneti képen. | + +A csomagot a parancssorból is beszerezheted: + +```bash +dotnet add package Aspose.HTML +``` + +Ha inkább a grafikus felületet részesíted előnyben, keress rá a „Aspose.HTML” kifejezésre a NuGet Package Managerben. + +--- + +## 1. lépés: Töltsd be a rasterizálni kívánt weboldalt + +Az első dolog, hogy az Aspose.HTML‑nek adj egy forrásdokumentumot. Lehet helyi fájl, karakterlánc vagy távoli URL. A legtöbb valós esetben egy élő oldallal dolgozol, ezért **konvertáljuk a weboldalt PNG‑re** a `https://example.com` cím megadásával. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Miért fontos:** Az oldal `HtmlDocument`‑ként való betöltése teljes hozzáférést biztosít a DOM‑hoz, ami azt jelenti, hogy CSS‑t injektálhatsz, módosíthatod a layoutot, vagy akár JavaScript‑et is futtathatsz a rasterizálás előtt. + +--- + +## 2. lépés: Kép renderelési beállítások konfigurálása + +Most, hogy a HTML a memóriában van, meg kell mondanunk a renderelőnek, hogyan nézzen ki a végső kép. Itt állíthatod be a **betűstílust**, engedélyezheted az antialiasing‑et, vagy módosíthatod a DPI‑t. Az alábbiakban egy jól kiegyensúlyozott alapértelmezett konfigurációt láthatsz, amely a minőség és a sebesség között kompromisszumot kínál. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Pro tipp:** Ha csak normál súlyt szeretnél, hagyd el a `WebFontStyle` zászlókat. Címsorokhoz elegendő a `WebFontStyle.Bold`, míg a feliratokhoz használhatod a `WebFontStyle.Italic`‑et. + +--- + +## 3. lépés: Rendereld az oldalt és **mentse a renderelt képet** PNG‑ként + +A dokumentummal és a beállításokkal készen, az utolsó lépés a `ImageRenderer` példányosítása és a kimeneti fájl írása. A `using` blokk biztosítja, hogy az erőforrások időben felszabaduljanak. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +A program futtatásakor egy `page.png` fájlt kell látnod a projekt mappádban, amely hűen tükrözi az *example.com* oldalt. Nyisd meg bármely képnézővel, és észre fogod venni a korábban kért félkövér‑dőlt stílust. + +### Várható kimenet + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +A PNG nagyjából 800 × 600 px (az oldal eredeti méretétől függően) lesz, sima élekkel az antialiasing köszönhetően. + +--- + +## Teljes működő példa + +Mindent összevonva, itt egy minimális konzolalkalmazás, amelyet egyszerűen bemásolhatsz a `Program.cs`‑be. Fordítható és futtatható azonnal. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Futtasd a következővel: + +```bash +dotnet run +``` + +…és egy friss PNG‑t kapsz, amely készen áll archiválásra, e‑mailben való küldésre vagy jelentésbe ágyazásra. + +--- + +## Variációk és szélhelyzetek + +### 1. Konvertálás JPEG‑re PNG helyett + +Ha a downstream rendszer JPEG‑et preferál (kisebb fájlméret, veszteséges tömörítés), egyszerűen változtasd meg a fájlkiterjesztést a `Save`‑ben. Az Aspose.HTML automatikusan felismeri a formátumot az útvonal alapján. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +A tömörítési minőséget a `JpegRenderingOptions`‑on keresztül is finomhangolhatod. + +### 2. Kép méretének módosítása + +Előfordulhat, hogy egy bélyegkép szükséges a teljes méretű képernyőkép helyett. Állítsd be az `ImageSize`‑t a beállításokon: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Hitelesítést igénylő oldalak kezelése + +Ha a cél‑URL alapvető hitelesítést igényel, add meg a hitelesítő adatokat a `HttpWebRequest`‑en keresztül a `HtmlDocument` létrehozása előtt. Alternatívaként letöltheted a HTML‑t saját magad (pl. `HttpClient`‑tel), és karakterláncként adhatod át: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Egyedi betűtípus használata + +Az Aspose.HTML képes helyi betűtípusok beágyazására. Regisztráld a betűtípus mappát a dokumentum betöltése előtt: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Ezután a lap `font-family` deklarációi a saját fájljaidra fognak hivatkozni. + +### 5. Több oldal renderelése ciklusban + +Ha egy URL‑listát kell batch‑processzelned: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Gyakori hibák és elkerülésük + +| Tünet | Valószínű ok | Javítás | +|---------|--------------|-----| +| Üres PNG fájl | `HtmlDocument.IsEmpty` igaz (az oldal nem töltődött be) | Ellenőrizd az URL‑t, a hálózati proxy‑t, és győződj meg róla, hogy a TLS 1.2 engedélyezve van. | +| Torz szöveg Linuxon | Betűtípus hinting letiltva | Állítsd be `renderingOptions.TextOptions.UseHinting = true;`. | +| Vízjel a kimeneten | Nincs licenc megadva | Regisztrálj ideiglenes vagy teljes licencet: `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Alacsony felbontású kép | Alapértelmezett DPI 96 nem elegendő nyomtatáshoz | Növeld a `renderingOptions.DpiX` és `DpiY` értékét 150‑300‑ra. | + +--- + +## 🎉 Összegzés + +Most már mindent tudsz, ami ahhoz kell, hogy **HTML‑t képpé renderelj** az Aspose.HTML‑el C#‑ban. A távoli oldal betöltésétől, az antialiasing és a **betűstílus beállításán** át a **renderelt kép PNG‑ként mentéséig** a teljes munkafolyamat néhány tömör lépésben összefoglalható. + +Most már **weboldalt PNG‑re konvertálhatsz** futás közben, beágyazhatod a képernyőképeket jelentésekbe, vagy generálhatsz bélyegképeket egy katalógushoz – böngésző‑automatizálás nélkül. + +### Mi a következő? + +- Kísérletezz a **html png konvertálással** különböző képernyőméretekhez (mobil vs. asztali). +- Próbáld ki a PDF‑exportot a `PdfRenderer`‑rel, ha nyomtatható dokumentumra van szükséged. +- Merülj el az Aspose.HTML DOM‑manipulációs API‑kban, hogy vízjeleket vagy egyedi CSS‑t injektálj a renderelés előtt. + +Van kérdésed a szélhelyzetekkel, licenceléssel vagy teljesítményoptimalizálással kapcsolatban? Írj egy megjegyzést alább, és jó kódolást kívánunk! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/hungarian/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..0c0e5dbc6 --- /dev/null +++ b/html/hungarian/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-03-14 +description: Renderelje a HTML-t gyorsan PNG formátumba az Aspose.HTML használatával. + Ismerje meg, hogyan generálhat PNG-t HTML‑ből, hogyan alkalmazhat félkövér dőlt + betűstílust, és hogyan mentheti a HTML‑t egy adatfolyamba. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: hu +og_description: HTML renderelése PNG formátumba az Aspose.HTML segítségével. Ez az + útmutató bemutatja, hogyan generáljunk PNG-t HTML-ből, hogyan használjunk félkövér + dőlt betűstílust, és hogyan mentsük el a HTML-t egy adatfolyamba. +og_title: HTML renderelése PNG-re C#-ban – Teljes programozási útmutató +tags: +- Aspose.HTML +- C# +- Image Rendering +title: HTML renderelése PNG‑be C#‑ban – Lépésről‑lépésre útmutató +url: /hu/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +output. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML renderelése PNG-re C#‑ban – Teljes programozási útmutató + +Valaha is szükséged volt **HTML renderelésére PNG‑re**, de nem tudtad, melyik könyvtár adja a pixel‑pontos eredményt? Nem vagy egyedül. Sok web‑to‑image folyamatban a fejlesztők elakadnak hiányzó betűtípusok, elmosódott szöveg vagy a rettegett „hogyan rögzítsem a HTML‑t anélkül, hogy előbb lemezre írnám?” problémák miatt. + +A lényeg: az Aspose.HTML a teljes folyamatot egy könnyed feladatként teszi. Ebben a bemutatóban **PNG‑t generálunk HTML‑ből**, alkalmazunk **félkövér dőlt betűstílust**, és még **HTML‑t mentünk egy stream‑be**, így minden memóriában marad. A végére egy kész, futtatható konzolalkalmazást kapsz, amely egy apró HTML‑részletből éles PNG‑fájlt készít. + +--- + +## Amire szükséged lesz + +- **.NET 6+** (a kód .NET Core‑dal és .NET Framework‑kel egyaránt működik) +- **Aspose.HTML for .NET** NuGet csomag – `Install-Package Aspose.HTML` +- Kedvenc IDE‑d (Visual Studio, Rider vagy VS Code) – bármelyik megfelel. + +Nincs szükség extra betűtípusokra, külső eszközökre, és egyáltalán nem kell ideiglenes fájl. Csak tiszta C#. + +--- + +## 1. lépés: Egyszerű HTML‑dokumentum létrehozása + +Az első dolog, amit teszünk, egy memóriában létező HTML‑dokumentum felépítése. Tekintsd úgy, mint egy virtuális weboldalt, amely csak a folyamatodban él. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Miért fontos:** A DOM programozott felépítésével elkerülöd a fájl‑IO terhelést, és dinamikus adatokat tudsz a futás során befűzni. A `HtmlDocument` osztály az Aspose.HTML minden műveletének belépési pontja. + +--- + +## 2. lépés: HTML mentése stream‑be + +Ahelyett, hogy a jelölőnyelvet lemezre írnánk, egy egyedi `ResourceHandler`‑ben rögzítjük. Ez a **save html to stream** része a munkafolyamatnak. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Pro tipp:** A `MemoryHandler` kicsi, de erőteljes. Ha később képeket, CSS‑t vagy betűtípusokat kell beágyaznod, egyszerűen bővítsd a `HandleResource` metódust, hogy a megfelelő stream‑eket adja vissza. + +--- + +## 3. lépés: Félkövér dőlt betűstílus beállítása + +Szöveg renderelésekor gyakran azt akarjuk, hogy pontosan úgy nézzen ki, mint a böngészőben. Az Aspose.HTML lehetővé teszi a **bold italic font style** közvetlen beállítását a renderelési opciókban. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **Mi történik:** +> * `UseAntialiasing` simítja a formák széleit. +> * `UseHinting` javítja a glifpozicionálást, ami kis szövegnél kritikus. +> * `FontStyle` a `Bold` és `Italic` zászlókat kombinálja, így a dokumentum minden szövege ezt a stílust örökli, hacsak nem írják felül. + +--- + +## 4. lépés: HTML‑dokumentum renderelése PNG‑képpé + +Most jön a szórakoztató rész – a HTML átalakítása képfájllá. Az `ImageRenderer` végzi a nehéz munkát. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Ha futtatod a programot, a munkakönyvtárban megjelenik egy `output.png` nevű fájl. Ebben a `` elem hozzáadásával már van egy érvényes HTML struktúra, amit elmenthetünk. + +> **Pro tipp:** Ha teljes HTML vázra (``, `
` stb.) van szükséged, az Aspose.HTML automatikusan legenerálja, amikor elmented a dokumentumot, még akkor is, ha csak a body tartalmat adtad hozzá. + +## 2. lépés: Egy **egyedi erőforráskezelő** megvalósítása – HTML memóriában rögzítése + +Egy *erőforráskezelő* azt mondja meg az Aspose.HTML‑nek, hová írja az egyes erőforrásokat (HTML, CSS, képek stb.). A `HandleResource` felülírásával a HTML kimenetet egy `MemoryStream`‑be irányíthatjuk a fájl helyett. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Miért használunk egyedi kezelőt:** +- **Teljesítmény:** Nincs lemez‑I/O, minden RAM‑ban marad. +- **Biztonság:** Nincsenek ideiglenes fájlok, amik kiszivároghatnak. +- **Rugalmasság:** Később a streamet átadhatod egy válaszhoz, adatbázishoz vagy másik API‑nak. + +## 3. lépés: Dokumentum mentése a kezelővel – a **Generate HTML Programmatically** szíve + +Most összekapcsoljuk a dokumentumot és a kezelőt. Amikor a `htmlDoc.Save(handler)` lefut, az Aspose.HTML meghívja a `HandleResource`‑t, és átadja a streamet, amibe írhatunk. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +Ekkor a `handler.HtmlStream` tartalmazza a nyers HTML bájtokat. Semmi sem került a lemezre, és a streamet annyiszor újra felhasználhatod, ahányszor csak akarod (csak ne felejtsd visszaállítani a pozíciót). + +## 4. lépés: A generált HTML olvasása memóriából – az eredmény ellenőrzése + +Az ellenőrzéshez állítsuk vissza a stream pozícióját a kezdetre, majd olvassuk vissza a szöveget. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Várható kimenet** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Ha a fenti markup‑ot látod, gratulálunk – sikeresen **generate html programmatically** használtad az Aspose.HTML‑et és egy **egyedi erőforráskezelőt**. + +## Gyakori változatok és szélhelyzetek + +### CSS vagy képek kezelése + +A demó a nem‑HTML erőforrásokat a `Stream.Null`‑lal hagyja figyelmen kívül. Valós környezetben érdemes lehet a CSS‑fájlokat vagy képeket is rögzíteni: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Ugyanazon kezelő újra‑használata több mentéshez + +Ha egy ciklusban több HTML‑részletet kell generálni, minden iterációban hozz létre egy új `MemoryHtmlHandler`‑t, vagy töröld a meglévő streamet: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Aszinkron mentés (Aspose.HTML 23.4+) + +Az újabb verziók támogatják az aszinkron mentést: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Ne felejtsd `await`‑elni, és a metódust `async`‑ként definiálni. + +## Teljes működő példa + +Az alábbi programot egyszerűen másold be egy konzolalkalmazásba. Tartalmazza az összes korábban tárgyalt elemet, plusz néhány megjegyzést a tisztaság kedvéért. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Futtasd a programot (`dotnet run`), és a konzolon meg kell jelennie a HTML‑nek, pontosan úgy, ahogy korábban láttad. + +## Összegzés + +Megmutattuk, hogyan **hozz létre HTML dokumentumot C#‑ben** az Aspose.HTML‑el, hogyan rögzítsd a kimenetet egy **egyedi erőforráskezelő** segítségével, és hogyan **generate HTML programmatically** anélkül, hogy a fájlrendszert érintenéd. A minta skálázható – legyen szó e‑mail sablonokról, „on‑the‑fly” jelentésekről vagy egy mikro‑szolgáltatásról, ami HTML‑részleteket ad vissza. + +Következő lépések? Próbáld meg egy CSS‑stíluslapot is hozzáadni a kezelőn keresztül, vagy streameld a HTML‑t közvetlenül egy ASP.NET Core válaszba (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Az outputot tovább is irányíthatod egy PDF konverterbe vagy egy HTML‑kép könyvtárba a komplexebb munkafolyamatokhoz. + +Van kérdésed a képek kezeléséről, az aszinkron mentésről vagy más könyvtárak integrálásáról? Írj kommentet, és jó kódolást! + +{{< /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/rendering-html-documents/_index.md b/html/indonesian/net/rendering-html-documents/_index.md index b7c974319..cc0135285 100644 --- a/html/indonesian/net/rendering-html-documents/_index.md +++ b/html/indonesian/net/rendering-html-documents/_index.md @@ -42,11 +42,13 @@ Setelah Anda menyiapkan Aspose.HTML untuk .NET, saatnya menjelajahi tutorial yan ### [Render HTML sebagai PNG di .NET dengan Aspose.HTML](./render-html-as-png/) Pelajari cara bekerja dengan Aspose.HTML untuk .NET: Memanipulasi HTML, mengonversi ke berbagai format, dan banyak lagi. Pelajari tutorial lengkap ini! + ### [Cara Merender HTML sebagai PNG – Panduan Lengkap C#](./how-to-render-html-as-png-complete-c-guide/) Pelajari cara merender HTML menjadi PNG menggunakan Aspose.HTML untuk .NET dengan contoh kode C# lengkap. ### [Buat PNG dari HTML – Panduan Rendering C# Lengkap](./create-png-from-html-full-c-rendering-guide/) Pelajari cara membuat file PNG dari HTML menggunakan Aspose.HTML untuk .NET dengan contoh kode C# lengkap. + ### [Render EPUB sebagai XPS di .NET dengan Aspose.HTML](./render-epub-as-xps/) Pelajari cara membuat dan merender dokumen HTML dengan Aspose.HTML untuk .NET dalam tutorial lengkap ini. Pelajari dunia manipulasi HTML, web scraping, dan banyak lagi. @@ -68,6 +70,12 @@ Pelajari cara menggunakan Aspose untuk mengonversi HTML menjadi PNG dengan pandu ### [Cara Merender HTML ke PNG dengan Aspose – Panduan Lengkap](./how-to-render-html-to-png-with-aspose-complete-guide/) Pelajari cara merender HTML menjadi PNG menggunakan Aspose dengan panduan lengkap langkah demi langkah. +### [Render HTML ke Gambar di C# – Panduan Lengkap Langkah‑demi‑Langkah](./render-html-to-image-in-c-complete-step-by-step-guide/) +Pelajari cara merender HTML menjadi gambar dengan Aspose.HTML untuk .NET menggunakan contoh kode C# lengkap. + +### [Render HTML ke PNG di C# – Panduan Langkah‑demi‑Langkah](./render-html-to-png-in-c-step-by-step-guide/) +Pelajari cara merender HTML menjadi PNG di C# dengan Aspose.HTML melalui panduan langkah demi langkah yang mudah diikuti. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/indonesian/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/indonesian/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..9a2568efa --- /dev/null +++ b/html/indonesian/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-03-14 +description: Render HTML ke gambar dengan cepat menggunakan Aspose.HTML. Pelajari + cara mengonversi halaman web ke PNG, mengatur gaya font, dan menyimpan gambar yang + dirender hanya dengan beberapa baris kode C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: id +og_description: Render HTML ke gambar dengan Aspose.HTML. Tutorial ini menunjukkan + cara mengonversi halaman web ke PNG, mengatur gaya font, dan menyimpan gambar yang + dirender dalam C#. +og_title: Render HTML ke Gambar di C# – Panduan Cepat dan Mudah +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Render HTML ke Gambar di C# – Panduan Lengkap Langkah demi Langkah +url: /id/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML ke Gambar – Tutorial Lengkap C# + +Pernah butuh **render HTML ke gambar** tetapi tidak yakin pustaka mana yang harus dipilih? Anda tidak sendirian. Dalam banyak skenario otomasi web atau pelaporan, Anda berakhir dengan halaman live yang ingin Anda arsipkan sebagai PNG, JPEG, atau bahkan BMP. Kabar baiknya, Aspose.HTML membuat ini sangat mudah, memungkinkan Anda **mengonversi halaman web ke PNG** dengan hanya beberapa baris kode. + +Dalam panduan ini kami akan menelusuri seluruh proses: mulai dari menginstal paket Aspose.HTML, memuat URL remote, menyesuaikan opsi rendering (termasuk cara **set font style**), dan akhirnya **save rendered image** ke disk. Pada akhir tutorial Anda akan memiliki aplikasi console siap‑jalankan yang menghasilkan screenshot tajam dari halaman web apa pun. + +## Apa yang Anda Butuhkan + +Sebelum kita mulai, pastikan Anda memiliki: + +| Prasyarat | Alasan | +|--------------|--------| +| .NET 6.0 SDK atau yang lebih baru | Aspose.HTML menargetkan .NET Standard 2.0+, jadi .NET 6 memberi Anda runtime terbaru. | +| Visual Studio 2022 (atau VS Code) | IDE yang nyaman mempercepat proses debugging. | +| Aspose.HTML for .NET NuGet package | Ini adalah mesin yang melakukan pekerjaan berat. | +| Lisensi Aspose.HTML yang valid (opsional) | Tanpa lisensi Anda akan mendapatkan watermark pada gambar output. | + +Anda dapat mengambil paket tersebut melalui CLI: + +```bash +dotnet add package Aspose.HTML +``` + +Jika Anda lebih suka GUI, cukup cari “Aspose.HTML” di NuGet Package Manager. + +--- + +## Langkah 1: Muat Halaman Web yang Ingin Anda Rasterisasi + +Hal pertama yang harus Anda lakukan adalah memberi Aspose.HTML dokumen sumber. Itu dapat berupa file lokal, string, atau URL remote. Dalam kebanyakan skenario dunia nyata Anda akan berurusan dengan situs live, jadi mari **convert webpage to PNG** dengan menunjuk ke `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Mengapa ini penting:** Memuat halaman sebagai `HtmlDocument` memberi Anda akses penuh ke DOM, yang berarti Anda dapat menyuntikkan CSS, memanipulasi tata letak, atau bahkan menjalankan JavaScript sebelum rasterisasi. + +--- + +## Langkah 2: Konfigurasi Opsi Rendering Gambar + +Sekarang HTML sudah berada di memori, kita perlu memberi tahu renderer bagaimana gambar akhir harus terlihat. Di sinilah Anda dapat **set font style**, mengaktifkan antialiasing, atau menyesuaikan DPI. Di bawah ini adalah konfigurasi default yang solid yang menyeimbangkan kualitas dan kecepatan. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Tips pro:** Jika Anda hanya membutuhkan berat reguler, hapus flag `WebFontStyle`. Untuk judul utama Anda mungkin hanya memerlukan `WebFontStyle.Bold`, sementara caption dapat menggunakan `WebFontStyle.Italic`. + +--- + +## Langkah 3: Render Halaman dan **Save Rendered Image** sebagai PNG + +Dengan dokumen dan opsi siap, langkah terakhir adalah menginstansiasi `ImageRenderer` dan menulis file output. Blok `using` memastikan sumber daya dibebaskan dengan cepat. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +Saat Anda menjalankan program, Anda akan melihat file `page.png` di folder proyek Anda yang berisi snapshot akurat dari *example.com*. Buka dengan penampil gambar apa pun dan Anda akan melihat gaya tebal‑miring yang kami minta sebelumnya. + +### Output yang Diharapkan + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +PNG akan berukuran kira‑kira 800 × 600 px (tergantung pada dimensi asli halaman) dengan tepi halus berkat antialiasing. + +--- + +## Contoh Kerja Lengkap + +Menggabungkan semuanya, berikut aplikasi console minimal yang dapat Anda salin‑tempel ke `Program.cs`. Ia akan dikompilasi dan berjalan langsung. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Jalankan dengan: + +```bash +dotnet run +``` + +…dan Anda akan memiliki PNG segar siap untuk diarsipkan, dikirim email, atau disisipkan dalam laporan. + +--- + +## Variasi & Kasus Tepi + +### 1. Mengonversi ke JPEG Alih-alih PNG + +Jika sistem hilir Anda lebih menyukai JPEG (ukuran file lebih kecil, kompresi lossy), cukup ubah ekstensi file di `Save`. Aspose.HTML secara otomatis mendeteksi format dari path. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +Anda juga dapat menyesuaikan kualitas kompresi melalui `JpegRenderingOptions`. + +### 2. Mengubah Dimensi Gambar + +Kadang‑kadang Anda membutuhkan thumbnail alih‑alih screenshot berukuran penuh. Atur `ImageSize` pada opsi: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Menangani Halaman yang Dilindungi Autentikasi + +Jika URL target memerlukan autentikasi dasar, berikan kredensial melalui `HttpWebRequest` sebelum membuat `HtmlDocument`. Atau, unduh HTML sendiri (menggunakan `HttpClient`) dan berikan sebagai string: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Menggunakan Font Kustom + +Aspose.HTML dapat menyematkan font lokal. Daftarkan folder font sebelum memuat dokumen: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Sekarang setiap deklarasi `font-family` di halaman akan merujuk ke file kustom Anda. + +### 5. Merender Banyak Halaman dalam Loop + +Jika Anda perlu memproses batch daftar URL: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Kesalahan Umum & Cara Menghindarinya + +| Gejala | Penyebab Kemungkinan | Solusi | +|---------|----------------------|--------| +| File PNG kosong | `HtmlDocument.IsEmpty` true (halaman gagal dimuat) | Verifikasi URL, periksa proxy jaringan, pastikan TLS 1.2 diaktifkan. | +| Teks berantakan di Linux | Hinting font dinonaktifkan | Atur `renderingOptions.TextOptions.UseHinting = true;`. | +| Watermark pada output | Tidak ada lisensi yang diberikan | Daftarkan lisensi sementara atau penuh via `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Gambar resolusi rendah | DPI default 96 tidak cukup untuk cetak | Tingkatkan `renderingOptions.DpiX` dan `DpiY` menjadi 150‑300. | + +--- + +## 🎉 Kesimpulan + +Kami baru saja membahas semua yang Anda perlukan untuk **render HTML ke gambar** dengan Aspose.HTML di C#. Dari memuat halaman remote, mengonfigurasi antialiasing dan **set font style**, hingga akhirnya **save rendered image** sebagai PNG, seluruh alur kerja tersusun rapi dalam beberapa langkah singkat. + +Sekarang Anda dapat **convert webpage to PNG** secara langsung, menyisipkan screenshot dalam laporan, atau menghasilkan thumbnail untuk katalog—tanpa perlu otomasi browser. + +### Apa Selanjutnya? + +- Bereksperimen dengan **convert html to png** untuk berbagai ukuran layar (mobile vs desktop). +- Coba mengekspor ke PDF menggunakan `PdfRenderer` jika Anda membutuhkan dokumen yang dapat dicetak. +- Selami API manipulasi DOM Aspose.HTML untuk menyuntikkan watermark atau CSS kustom sebelum rendering. + +Ada pertanyaan tentang kasus tepi, lisensi, atau penyetelan performa? Tinggalkan komentar di bawah, dan selamat coding! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/indonesian/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..3ecce9af9 --- /dev/null +++ b/html/indonesian/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-03-14 +description: Render HTML ke PNG dengan cepat menggunakan Aspose.HTML. Pelajari cara + menghasilkan PNG dari HTML, menerapkan gaya huruf tebal miring, dan menyimpan HTML + ke aliran. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: id +og_description: Render HTML ke PNG dengan Aspose.HTML. Panduan ini menunjukkan cara + menghasilkan PNG dari HTML, menggunakan gaya huruf tebal miring, dan menyimpan HTML + ke stream. +og_title: Render HTML ke PNG dalam C# – Panduan Pemrograman Lengkap +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Render HTML ke PNG di C# – Panduan Langkah demi Langkah +url: /id/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML ke PNG di C# – Panduan Pemrograman Lengkap + +Pernah membutuhkan untuk **render HTML ke PNG** tetapi tidak yakin perpustakaan mana yang akan memberikan hasil pixel‑perfect? Anda tidak sendirian. Dalam banyak pipeline web‑to‑image, pengembang sering mengalami masalah font yang hilang, teks yang buram, atau pertanyaan menakutkan “bagaimana cara menangkap HTML tanpa menulisnya ke disk terlebih dahulu?” + +Begini: Aspose.HTML membuat seluruh proses menjadi sangat mudah. Dalam tutorial ini kami akan **generate PNG from HTML**, menerapkan **bold italic font style**, dan bahkan **save HTML to a stream** sehingga Anda dapat menyimpan semuanya di memori. Pada akhir tutorial Anda akan memiliki aplikasi console siap‑jalankan yang mengubah potongan HTML kecil menjadi file PNG yang tajam. + +--- + +## Apa yang Anda Butuhkan + +- **.NET 6+** (kode ini bekerja dengan .NET Core dan .NET Framework) +- **Aspose.HTML for .NET** paket NuGet – `Install-Package Aspose.HTML` +- IDE favorit (Visual Studio, Rider, atau VS Code) – apa saja boleh. + +Tidak ada font tambahan, tidak ada alat eksternal, dan tentu saja tidak ada file sementara. Hanya C# murni. + +--- + +## Langkah 1: Buat Dokumen HTML Sederhana + +Hal pertama yang kita lakukan adalah membangun dokumen HTML di memori. Anggap saja sebagai halaman web virtual yang hanya hidup di dalam proses Anda. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Why this matters:** Dengan membangun DOM secara programatik Anda menghindari overhead file‑IO dan dapat menyuntikkan data dinamis secara langsung. Kelas `HtmlDocument` adalah titik masuk untuk setiap operasi Aspose.HTML. + +--- + +## Langkah 2: Simpan HTML ke Stream + +Alih-alih menulis markup ke disk, kami menangkapnya dalam `ResourceHandler` khusus. Ini adalah bagian **save html to stream** dari alur kerja. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Pro tip:** `MemoryHandler` kecil namun kuat. Jika nanti Anda perlu menyematkan gambar, CSS, atau font, cukup perpanjang `HandleResource` untuk mengembalikan stream yang sesuai. + +--- + +## Langkah 3: Konfigurasikan Gaya Font Bold Italic + +Saat Anda merender teks, Anda sering ingin tampilannya persis seperti di browser. Aspose.HTML memungkinkan Anda mengatur **bold italic font style** langsung pada opsi rendering. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **What’s happening:** +> * `UseAntialiasing` menghaluskan tepi bentuk. +> * `UseHinting` meningkatkan posisi glyph, yang penting untuk teks kecil. +> * `FontStyle` menggabungkan flag `Bold` dan `Italic`, sehingga setiap potongan teks dalam dokumen mewarisi gaya tersebut kecuali diubah. + +--- + +## Langkah 4: Render Dokumen HTML menjadi Gambar PNG + +Sekarang bagian yang menyenangkan – mengubah HTML tersebut menjadi file gambar. `ImageRenderer` melakukan semua pekerjaan berat. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Jika Anda menjalankan program, Anda akan melihat file bernama `output.png` di direktori kerja. File tersebut berisi heading `` kita sudah memiliki struktur HTML yang valid dan siap disimpan. + +> **Pro tip:** Jika Anda memerlukan kerangka HTML lengkap (``, `
`, dll.), Aspose.HTML secara otomatis menghasilkan nya saat Anda menyimpan dokumen, bahkan jika Anda hanya menambahkan konten body. + +## Langkah 2: Implementasikan **Custom Resource Handler** – Menangkap HTML di Memori + +*Resource handler* memberi tahu Aspose.HTML ke mana menulis setiap sumber daya (HTML, CSS, gambar, dll.). Dengan menimpa `HandleResource` kita dapat mengarahkan output HTML ke `MemoryStream` alih‑alih file. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Mengapa kita menggunakan penangan kustom:** +- **Performa:** Tidak ada I/O disk, semuanya tetap di RAM. +- **Keamanan:** Tidak ada file sementara yang dapat terekspos. +- **Fleksibilitas:** Anda dapat mengalirkan stream ke respons, basis data, atau API lain nanti. + +## Langkah 3: Simpan Dokumen Menggunakan Penangan – Inti dari **Generate HTML Programmatically** + +Sekarang kita menghubungkan dokumen dan penangan. Ketika `htmlDoc.Save(handler)` dijalankan, Aspose.HTML memanggil `HandleResource`, memberikan stream untuk ditulisi. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +Pada titik ini `handler.HtmlStream` berisi byte HTML mentah. Tidak ada yang ditulis ke disk, dan Anda dapat menggunakan kembali stream sebanyak yang Anda mau (ingat untuk mengatur ulang posisinya). + +## Langkah 4: Baca HTML yang Dihasilkan dari Memori – Verifikasi Output + +Untuk membuktikan semuanya berhasil, kita mengatur ulang posisi stream ke awal dan membaca teksnya kembali. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Output yang diharapkan** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Jika Anda melihat markup di atas, selamat—Anda telah berhasil **generate html programmatically** menggunakan Aspose.HTML dan **custom resource handler**. + +## Variasi Umum & Kasus Pinggiran + +### Menangani CSS atau Gambar + +Demo ini mengabaikan sumber daya non‑HTML dengan mengembalikan `Stream.Null`. Dalam skenario dunia nyata Anda mungkin ingin menangkap file CSS atau gambar juga: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Menggunakan Penangan yang Sama untuk Beberapa Simpanan + +Jika Anda perlu menghasilkan beberapa potongan HTML dalam loop, buat `MemoryHtmlHandler` baru setiap iterasi atau bersihkan stream yang ada: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Penyimpanan Async (Aspose.HTML 23.4+) + +Versi yang lebih baru mendukung penyimpanan async: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Ingat untuk `await` dan menjadikan metode Anda `async`. + +## Contoh Lengkap yang Berfungsi + +Berikut adalah program lengkap yang dapat Anda salin‑tempel ke aplikasi console. Program ini mencakup semua bagian yang telah dibahas, plus beberapa komentar untuk kejelasan. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Jalankan program (`dotnet run`) dan Anda akan melihat HTML dicetak ke konsol, persis seperti yang ditunjukkan sebelumnya. + +## Kesimpulan + +Kami baru saja menunjukkan cara **create HTML document C#** menggunakan Aspose.HTML, menangkap output dengan **custom resource handler**, dan **generate HTML programmatically** tanpa menyentuh sistem file. Pola ini dapat diskalakan—baik Anda membuat templat email, laporan on‑the‑fly, atau micro‑service yang mengembalikan potongan HTML. + +Langkah selanjutnya? Coba tambahkan stylesheet CSS melalui penangan, atau alirkan HTML langsung ke respons ASP.NET Core (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Anda juga dapat menghubungkan output ke konverter PDF atau perpustakaan HTML‑to‑image untuk alur kerja yang lebih kaya. + +Punya pertanyaan tentang penangan gambar, penyimpanan async, atau integrasi dengan pustaka lain? Tinggalkan komentar, dan selamat coding! + +{{< /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/rendering-html-documents/_index.md b/html/italian/net/rendering-html-documents/_index.md index 1239e762f..22d60be94 100644 --- a/html/italian/net/rendering-html-documents/_index.md +++ b/html/italian/net/rendering-html-documents/_index.md @@ -60,6 +60,11 @@ Scopri come controllare efficacemente i timeout di rendering in Aspose.HTML per Impara a eseguire il rendering di più documenti HTML utilizzando Aspose.HTML per .NET. Aumenta le tue capacità di elaborazione dei documenti con questa potente libreria. ### [Rendi il documento SVG come PNG in .NET con Aspose.HTML](./render-svg-doc-as-png/) Sblocca la potenza di Aspose.HTML per .NET! Scopri come rendere SVG Doc come PNG senza sforzo. Immergiti in esempi passo dopo passo e FAQ. Inizia subito! +### [Renderizza HTML in immagine in C# – Guida completa passo‑passo](./render-html-to-image-in-c-complete-step-by-step-guide/) +Scopri come convertire HTML in immagini usando C# con Aspose.HTML, seguendo una guida dettagliata passo‑passo. +### [Renderizza HTML in PNG in C# – Guida passo‑passo](./render-html-to-png-in-c-step-by-step-guide/) +Scopri come convertire HTML in PNG usando C# con Aspose.HTML, seguendo una guida dettagliata passo‑passo. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/italian/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/italian/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..be2208b71 --- /dev/null +++ b/html/italian/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-03-14 +description: Renderizza HTML in immagine rapidamente usando Aspose.HTML. Scopri come + convertire una pagina web in PNG, impostare lo stile del carattere e salvare l'immagine + renderizzata in poche righe di C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: it +og_description: Esegui il rendering di HTML in immagine con Aspose.HTML. Questo tutorial + mostra come convertire una pagina web in PNG, impostare lo stile del carattere e + salvare l'immagine renderizzata in C#. +og_title: Renderizza HTML in immagine in C# – Guida rapida e facile +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Converti HTML in immagine in C# – Guida completa passo passo +url: /it/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converti HTML in Immagine – Tutorial Completo C# + +Hai mai avuto bisogno di **render HTML to image** ma non eri sicuro quale libreria scegliere? Non sei l'unico. In molti scenari di web‑automation o reporting ti ritrovi con una pagina live che vuoi archiviare come PNG, JPEG o anche BMP. La buona notizia è che Aspose.HTML rende tutto semplice, permettendoti di **convert webpage to PNG** con poche righe di codice. + +In questa guida percorreremo l'intero processo: dall'installazione del pacchetto Aspose.HTML, al caricamento di un URL remoto, alla regolazione delle opzioni di rendering (incluso come **set font style**), e infine **save rendered image** su disco. Alla fine avrai un'app console pronta all'uso che produce uno screenshot nitido di qualsiasi pagina web. + +## Di cosa avrai bisogno + +| Prerequisito | Motivo | +|--------------|--------| +| .NET 6.0 SDK or later | Aspose.HTML è destinato a .NET Standard 2.0+, quindi .NET 6 ti fornisce il runtime più recente. | +| Visual Studio 2022 (or VS Code) | Un IDE confortevole accelera il debugging. | +| Aspose.HTML for .NET NuGet package | Questo è il motore che esegue il lavoro pesante. | +| A valid Aspose.HTML license (optional) | Senza licenza otterrai una filigrana sull'immagine di output. | + +Puoi ottenere il pacchetto tramite la CLI: + +```bash +dotnet add package Aspose.HTML +``` + +Se preferisci l'interfaccia grafica, cerca semplicemente “Aspose.HTML” nel NuGet Package Manager. + +## Passo 1: Carica la Pagina Web che Vuoi Rasterizzare + +La prima cosa da fare è fornire ad Aspose.HTML un documento sorgente. Può essere un file locale, una stringa o un URL remoto. Nella maggior parte degli scenari reali lavorerai con un sito live, quindi **convert webpage to PNG** puntando a `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Perché è importante:** Caricare la pagina come `HtmlDocument` ti dà pieno accesso al DOM, il che significa che puoi iniettare CSS, manipolare il layout o anche eseguire JavaScript prima della rasterizzazione. + +## Passo 2: Configura le Opzioni di Rendering dell'Immagine + +Ora che l'HTML è in memoria, dobbiamo indicare al renderer come vogliamo che appaia l'immagine finale. Qui puoi **set font style**, abilitare l'antialiasing o regolare il DPI. Di seguito trovi una configurazione predefinita solida che bilancia qualità e velocità. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Consiglio professionale:** Se ti serve solo un peso regolare, rimuovi i flag `WebFontStyle`. Per i titoli potresti volere solo `WebFontStyle.Bold`, mentre per le didascalie potresti usare `WebFontStyle.Italic`. + +## Passo 3: Renderizza la Pagina e **Save Rendered Image** come PNG + +Con il documento e le opzioni pronti, l'ultimo passo è istanziare `ImageRenderer` e scrivere il file di output. Il blocco `using` garantisce che le risorse vengano rilasciate prontamente. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +Quando esegui il programma, dovresti vedere un file `page.png` nella cartella del progetto contenente una fedele istantanea di *example.com*. Aprilo con qualsiasi visualizzatore di immagini e noterai lo stile grassetto‑corsivo che abbiamo richiesto in precedenza. + +### Output Atteso + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +Il PNG sarà approssimativamente 800 × 600 px (a seconda delle dimensioni originali della pagina) con bordi lisci grazie all'antialiasing. + +## Esempio Completo Funzionante + +Mettendo tutto insieme, ecco una app console minimale che puoi copiare‑incollare in `Program.cs`. Compila ed esegue subito. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Eseguilo con: + +```bash +dotnet run +``` + +…e avrai un PNG fresco pronto per l'archiviazione, l'invio email o l'inserimento in un report. + +## Varianti e Casi Limite + +### 1. Conversione in JPEG invece di PNG + +Se il tuo sistema a valle preferisce JPEG (dimensione file più piccola, compressione con perdita), basta cambiare l'estensione del file in `Save`. Aspose.HTML rileva automaticamente il formato dal percorso. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +Puoi anche regolare la qualità della compressione tramite `JpegRenderingOptions`. + +### 2. Modifica delle Dimensioni dell'Immagine + +A volte hai bisogno di una miniatura anziché di uno screenshot a dimensione intera. Imposta `ImageSize` nelle opzioni: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Gestione di Pagine Protette da Autenticazione + +Se l'URL di destinazione richiede autenticazione di base, fornisci le credenziali tramite `HttpWebRequest` prima di creare l'`HtmlDocument`. In alternativa, scarica l'HTML tu stesso (usando `HttpClient`) e passalo come stringa: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Utilizzo di un Font Personalizzato + +Aspose.HTML può incorporare font locali. Registra la cartella dei font prima di caricare il documento: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Ora qualsiasi dichiarazione `font-family` nella pagina verrà risolta con i tuoi file personalizzati. + +### 5. Rendering di Più Pagine in un Loop + +Se devi elaborare in batch un elenco di URL: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +## Problemi Comuni e Come Evitarli + +| Sintomo | Probabile Causa | Soluzione | +|---------|-----------------|-----------| +| File PNG vuoto | `HtmlDocument.IsEmpty` true (pagina non caricata) | Verifica l'URL, controlla il proxy di rete, assicurati che TLS 1.2 sia abilitato. | +| Testo illeggibile su Linux | Hinting dei font disabilitato | Imposta `renderingOptions.TextOptions.UseHinting = true;`. | +| Filigrana sull'output | Nessuna licenza fornita | Registra una licenza temporanea o completa tramite `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Immagine a bassa risoluzione | Il DPI predefinito 96 è insufficiente per la stampa | Aumenta `renderingOptions.DpiX` e `DpiY` a 150‑300. | + +## 🎉 Conclusione + +Abbiamo appena coperto tutto ciò di cui hai bisogno per **render HTML to image** con Aspose.HTML in C#. Dal caricamento di una pagina remota, alla configurazione dell'antialiasing e **set font style**, fino a **save rendered image** come PNG, l'intero flusso di lavoro si adatta perfettamente in pochi passaggi concisi. + +Ora puoi **convert webpage to PNG** al volo, inserire screenshot nei report o generare miniature per un catalogo—senza necessità di automazione del browser. + +### Cosa segue? + +- Sperimenta con **convert html to png** per diverse dimensioni di schermo (mobile vs desktop). +- Prova a esportare in PDF usando `PdfRenderer` se ti serve un documento stampabile. +- Approfondisci le API di manipolazione DOM di Aspose.HTML per iniettare filigrane o CSS personalizzato prima del rendering. + +Hai domande su casi limite, licenze o ottimizzazione delle prestazioni? Lascia un commento qui sotto, e buona programmazione! + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/italian/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..6a15b6b90 --- /dev/null +++ b/html/italian/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-03-14 +description: Renderizza HTML in PNG rapidamente con Aspose.HTML. Scopri come generare + PNG da HTML, applicare lo stile di carattere grassetto corsivo e salvare l'HTML + in uno stream. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: it +og_description: Renderizza HTML in PNG con Aspose.HTML. Questa guida mostra come generare + PNG da HTML, utilizzare lo stile di carattere grassetto corsivo e salvare l'HTML + in uno stream. +og_title: Converti HTML in PNG in C# – Guida completa alla programmazione +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Renderizza HTML in PNG in C# – Guida passo passo +url: /it/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Renderizzare HTML in PNG con C# – Guida completa di programmazione + +Hai mai avuto bisogno di **renderizzare HTML in PNG** ma non eri sicuro quale libreria ti avrebbe dato risultati pixel‑perfetti? Non sei solo. In molte pipeline web‑to‑image gli sviluppatori si imbattono in font mancanti, testo sfocato, o il temuto “come catturo l'HTML senza scriverlo prima su disco?” + +Ecco la questione: Aspose.HTML rende l'intero processo un gioco da ragazzi. In questo tutorial **genereremo PNG da HTML**, applicheremo uno **stile di font grassetto corsivo**, e persino **salveremo l'HTML in uno stream** così potrai tenere tutto in memoria. Alla fine avrai un'app console pronta all'uso che trasforma un piccolo frammento HTML in un file PNG nitido. + +--- + +## Cosa ti serve + +- **.NET 6+** (il codice funziona sia con .NET Core sia con .NET Framework) +- **Aspose.HTML for .NET** pacchetto NuGet – `Install-Package Aspose.HTML` +- Un IDE preferito (Visual Studio, Rider o VS Code) – qualsiasi va bene. + +Nessun font extra, nessuno strumento esterno, e sicuramente nessun file temporaneo. Solo puro C#. + +--- + +## Passo 1: Crea un documento HTML semplice + +La prima cosa che facciamo è costruire un documento HTML in memoria. Pensalo come una pagina web virtuale che vive solo all'interno del tuo processo. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Perché è importante:** Costruendo il DOM programmaticamente eviti l'overhead di I/O su file e puoi iniettare dati dinamici al volo. La classe `HtmlDocument` è il punto di ingresso per ogni operazione di Aspose.HTML. + +--- + +## Passo 2: Salva l'HTML in uno stream + +Invece di scrivere il markup su disco, lo catturiamo in un `ResourceHandler` personalizzato. Questa è la parte **save html to stream** del flusso di lavoro. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Consiglio professionale:** Il `MemoryHandler` è piccolo ma potente. Se in seguito hai bisogno di incorporare immagini, CSS o font, basta estendere `HandleResource` per restituire gli stream appropriati. + +--- + +## Passo 3: Configura lo stile di font grassetto corsivo + +Quando renderizzi del testo, spesso vuoi che appaia esattamente come in un browser. Aspose.HTML ti permette di impostare **bold italic font style** direttamente nelle opzioni di rendering. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **Cosa sta succedendo:** +> * `UseAntialiasing` leviga i bordi delle forme. +> * `UseHinting` migliora il posizionamento dei glifi, fondamentale per il testo piccolo. +> * `FontStyle` combina i flag `Bold` e `Italic`, così ogni pezzo di testo nel documento eredita quello stile a meno che non venga sovrascritto. + +--- + +## Passo 4: Renderizza il documento HTML in un'immagine PNG + +Ora la parte divertente – trasformare quell'HTML in un file immagine. Il `ImageRenderer` fa tutto il lavoro pesante. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Se esegui il programma, vedrai un file chiamato `output.png` nella directory di lavoro. Contiene l'intestazione `` abbiamo già una struttura HTML valida pronta per essere salvata. + +> **Consiglio professionale:** Se ti serve uno scheletro HTML completo (``, `
`, ecc.), Aspose.HTML lo genera automaticamente quando salvi il documento, anche se hai aggiunto solo contenuto nel body. + +## Passo 2: Implementare un **Custom Resource Handler** – Catturare HTML in memoria + +Un *resource handler* indica ad Aspose.HTML dove scrivere ogni risorsa (HTML, CSS, immagini, ecc.). Sovrascrivendo `HandleResource` possiamo indirizzare l'output HTML verso un `MemoryStream` invece che verso un file. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Perché usiamo un handler personalizzato:** +- **Performance:** Nessun I/O su disco, tutto rimane in RAM. +- **Sicurezza:** Nessun file temporaneo che potrebbe essere esposto. +- **Flessibilità:** Puoi in seguito indirizzare lo stream verso una risposta, un database o un'altra API. + +## Passo 3: Salvare il documento usando l'handler – Il cuore di **Generate HTML Programmatically** + +Ora colleghiamo il documento e l'handler. Quando `htmlDoc.Save(handler)` viene eseguito, Aspose.HTML chiama `HandleResource`, fornendoci lo stream su cui scrivere. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +A questo punto `handler.HtmlStream` contiene i byte HTML grezzi. Non è stato scritto nulla su disco, e puoi riutilizzare lo stream quante volte vuoi (ricordati solo di resettare la sua posizione). + +## Passo 4: Leggere l'HTML generato dalla memoria – Verificare l'output + +Per dimostrare che tutto ha funzionato, resettiamo la posizione dello stream all'inizio e leggiamo nuovamente il testo. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Output previsto** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Se vedi il markup sopra, congratulazioni—hai generato con successo **generate html programmatically** usando Aspose.HTML e un **custom resource handler**. + +## Variazioni comuni e casi limite + +### Gestione di CSS o immagini + +La demo ignora le risorse non‑HTML restituendo `Stream.Null`. In uno scenario reale potresti voler catturare anche file CSS o immagini: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Riutilizzare lo stesso handler per più salvataggi + +Se devi generare diversi snippet HTML in un ciclo, crea un nuovo `MemoryHtmlHandler` ad ogni iterazione o svuota lo stream esistente: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Salvataggio asincrono (Aspose.HTML 23.4+) + +Le versioni più recenti supportano il salvataggio asincrono: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Ricorda di usare `await` e di rendere il tuo metodo `async`. + +## Esempio completo funzionante + +Di seguito trovi il programma completo che puoi copiare‑incollare in un'app console. Include tutti gli elementi di cui abbiamo parlato, più qualche commento per chiarezza. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Esegui il programma (`dotnet run`) e dovresti vedere l'HTML stampato sulla console, esattamente come mostrato prima. + +## Conclusione + +Abbiamo appena mostrato come **create HTML document C#** usando Aspose.HTML, catturare l'output con un **custom resource handler**, e **generate HTML programmatically** senza toccare il file system. Il modello è scalabile—sia che tu stia creando template email, report al volo, o un micro‑servizio che restituisce snippet HTML. + +Prossimi passi? Prova ad aggiungere un foglio di stile CSS tramite l'handler, o trasmetti l'HTML direttamente in una risposta ASP.NET Core (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Potresti anche collegare l'output a un convertitore PDF o a una libreria HTML‑to‑image per flussi di lavoro più ricchi. + +Hai domande sulla gestione delle immagini, sul salvataggio asincrono o sull'integrazione con altre librerie? Lascia un commento, e buona programmazione! + +{{< /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/rendering-html-documents/_index.md b/html/japanese/net/rendering-html-documents/_index.md index 0d786f01c..0e6314c42 100644 --- a/html/japanese/net/rendering-html-documents/_index.md +++ b/html/japanese/net/rendering-html-documents/_index.md @@ -68,6 +68,12 @@ Aspose.HTML for .NET を使い、HTML を高品質な PNG 画像に変換する ### [HTML から PNG を作成 – 完全な C# レンダリング ガイド](./create-png-from-html-full-c-rendering-guide/) Aspose.HTML for .NET を使用して、HTML を PNG 画像に変換する完全な C# ガイドです。ステップバイステップで解説します。 +### [C# で HTML を画像にレンダリングする – 完全ステップバイステップガイド](./render-html-to-image-in-c-complete-step-by-step-guide/) +Aspose.HTML for .NET を使い、C# で HTML を画像に変換する手順を完全に解説します。 + +### [C# で HTML を PNG にレンダリングする – ステップバイステップ ガイド](./render-html-to-png-in-c-step-by-step-guide/) +Aspose.HTML for .NET を使用して、C# で HTML を PNG 画像に変換する手順を詳しく解説します。 + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/japanese/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/japanese/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..7f73dc9a9 --- /dev/null +++ b/html/japanese/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-03-14 +description: Aspose.HTML を使用して HTML を画像に高速にレンダリングします。ウェブページを PNG に変換し、フォントスタイルを設定し、C# + の数行でレンダリングされた画像を保存する方法を学びましょう。 +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: ja +og_description: Aspose.HTML を使用して HTML を画像にレンダリングします。このチュートリアルでは、ウェブページを PNG に変換し、フォントスタイルを設定し、C# + でレンダリングされた画像を保存する方法を示します。 +og_title: C#でHTMLを画像に変換 – 簡単で迅速なガイド +tags: +- C# +- Aspose.HTML +- Image Rendering +title: C#でHTMLを画像に変換する – 完全ステップバイステップガイド +url: /ja/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to Image – Complete C# Tutorial + +HTML を画像に **レンダリング**したいが、どのライブラリを選べば良いか分からないことはありませんか? 多くの Web 自動化やレポート作成シナリオで、ライブページを PNG、JPEG、あるいは BMP として保存したくなることがあります。Aspose.HTML を使えば、数行のコードで **webpage を PNG に変換**でき、まさに楽勝です。 + +このガイドでは、Aspose.HTML パッケージのインストールから、リモート URL の読み込み、レンダリングオプションの調整(**フォントスタイルの設定** を含む)、そして最終的に **レンダリングされた画像を保存** するまでの一連の手順を解説します。最後まで実行すれば、任意の Web ページの鮮明なスクリーンショットを生成できるコンソールアプリが完成します。 + +## 必要なもの + +作業を始める前に、以下を用意してください。 + +| 前提条件 | 理由 | +|--------------|--------| +| .NET 6.0 SDK 以上 | Aspose.HTML は .NET Standard 2.0+ を対象としているため、.NET 6 で最新ランタイムが利用できます。 | +| Visual Studio 2022(または VS Code) | 快適な IDE がデバッグを加速します。 | +| Aspose.HTML for .NET NuGet パッケージ | 重い処理を担うエンジンです。 | +| 有効な Aspose.HTML ライセンス(任意) | ライセンスが無い場合、出力画像に透かしが入ります。 | + +CLI でパッケージを取得できます: + +```bash +dotnet add package Aspose.HTML +``` + +GUI が好きな方は、NuGet パッケージマネージャで “Aspose.HTML” を検索してください。 + +--- + +## Step 1: Load the Web Page You Want to Rasterize + +最初に行うべきは、Aspose.HTML にソースドキュメントを渡すことです。ローカルファイル、文字列、またはリモート URL のいずれかを指定できます。実務ではライブサイトを対象にすることが多いので、`https://example.com` を指定して **webpage を PNG に変換** してみましょう。 + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **ポイント:** `HtmlDocument` としてページを読み込むと DOM へのフルアクセスが得られ、CSS の注入やレイアウト操作、さらには JavaScript の実行まで可能になります。 + +--- + +## Step 2: Configure Image Rendering Options + +HTML がメモリ上にロードされたら、最終画像の見た目を指定する必要があります。ここで **フォントスタイルの設定**、アンチエイリアスの有効化、DPI の調整などが行えます。以下は品質と速度のバランスが取れた標準的な設定例です。 + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **プロのコツ:** 通常のウェイトだけが必要な場合は `WebFontStyle` フラグを省略してください。見出しには `WebFontStyle.Bold`、キャプションには `WebFontStyle.Italic` を組み合わせると効果的です。 + +--- + +## Step 3: Render the Page and **Save Rendered Image** as PNG + +ドキュメントとオプションが揃ったら、`ImageRenderer` をインスタンス化し、出力ファイルを書き出します。`using` ブロックを使うことでリソースが速やかに解放されます。 + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +プログラムを実行すると、プロジェクトフォルダーに `page.png` が生成され、*example.com* の忠実なスナップショットが保存されます。任意の画像ビューアで開くと、先ほど設定した太字・斜体スタイルが反映されていることが確認できます。 + +### Expected Output + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +PNG のサイズはおおよそ 800 × 600 px(ページの元サイズに依存)で、アンチエイリアスによりエッジが滑らかです。 + +--- + +## Full Working Example + +すべてをまとめた最小限のコンソールアプリを `Program.cs` に貼り付ければ、すぐにコンパイル・実行できます。 + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +実行コマンド: + +```bash +dotnet run +``` + +…と入力すれば、アーカイブやメール送信、レポート埋め込みに使える新鮮な PNG が手に入ります。 + +--- + +## Variations & Edge Cases + +### 1. Converting to JPEG Instead of PNG + +下流システムが JPEG(ファイルサイズが小さく、非可逆圧縮)を好む場合は、`Save` の拡張子を変更するだけです。Aspose.HTML はパスから自動的にフォーマットを判別します。 + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +`JpegRenderingOptions` で圧縮品質も調整可能です。 + +### 2. Changing Image Dimensions + +フルサイズのスクリーンショットではなくサムネイルが必要なときは、オプションの `ImageSize` を設定します。 + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Handling Authentication‑Protected Pages + +対象 URL がベーシック認証を要求する場合は、`HtmlDocument` を作成する前に `HttpWebRequest` で資格情報を設定します。あるいは `HttpClient` で HTML を自前で取得し、文字列として渡す方法もあります。 + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Using a Custom Font + +Aspose.HTML はローカルフォントの埋め込みに対応しています。ドキュメントをロードする前にフォントフォルダーを登録してください。 + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +これでページ内の `font-family` 宣言がカスタムフォントに解決されます。 + +### 5. Rendering Multiple Pages in a Loop + +URL のリストを一括処理したい場合は、以下のようにループでレンダリングします。 + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Common Pitfalls & How to Avoid Them + +| 症状 | 考えられる原因 | 対策 | +|---------|--------------|-----| +| 空白の PNG ファイル | `HtmlDocument.IsEmpty` が true(ページ読み込み失敗) | URL を確認し、プロキシ設定や TLS 1.2 が有効かチェック | +| Linux で文字化け | フォントヒンティングが無効 | `renderingOptions.TextOptions.UseHinting = true;` を設定 | +| 出力に透かしが入る | ライセンス未登録 | `License license = new License(); license.SetLicense("Aspose.Total.lic");` で一時または正式ライセンスを登録 | +| 低解像度画像 | デフォルト DPI 96 が印刷向けに不足 | `renderingOptions.DpiX` と `DpiY` を 150‑300 に上げる | + +--- + +## 🎉 Conclusion + +Aspose.HTML を使った **HTML の画像へのレンダリング** 手順をすべて解説しました。リモートページの読み込み、アンチエイリアスや **フォントスタイルの設定**、そして最終的に **レンダリングされた画像を PNG として保存** するまで、数ステップで完了します。 + +これで、オンザフライで **webpage を PNG に変換** し、レポートにスクリーンショットを埋め込んだり、カタログ用サムネイルを生成したりと、ブラウザ自動化なしで画像取得が可能になります。 + +### What’s Next? + +- **convert html to png** を異なる画面サイズ(モバイル vs デスクトップ)で試す +- 印刷用ドキュメントが必要な場合は `PdfRenderer` で PDF にエクスポート +- Aspose.HTML の DOM 操作 API を活用し、ウォーターマークやカスタム CSS をレンダリング前に注入 + +質問やライセンス、パフォーマンス調整に関する疑問があれば、下のコメント欄にどうぞ。Happy coding! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/japanese/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..72814c26a --- /dev/null +++ b/html/japanese/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-03-14 +description: Aspose.HTML を使用して HTML を PNG に高速でレンダリングします。HTML から PNG を生成し、太字・斜体のフォントスタイルを適用し、HTML + をストリームに保存する方法を学びましょう。 +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: ja +og_description: Aspose.HTML を使用して HTML を PNG にレンダリングします。このガイドでは、HTML から PNG を生成し、太字と斜体のフォントスタイルを使用し、HTML + をストリームに保存する方法を示します。 +og_title: C#でHTMLをPNGにレンダリング – 完全プログラミングチュートリアル +tags: +- Aspose.HTML +- C# +- Image Rendering +title: C#でHTMLをPNGにレンダリングする – ステップバイステップガイド +url: /ja/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で HTML を PNG にレンダリング – 完全プログラミングウォークスルー + +Ever needed to **render HTML to PNG** but weren’t sure which library would give you pixel‑perfect results? You’re not alone. In many web‑to‑image pipelines developers stumble over missing fonts, blurry text, or the dreaded “how do I capture the HTML without writing it to disk first?” + +実は、Aspose.HTML を使えば全工程がとても簡単です。このチュートリアルでは **generate PNG from HTML** を行い、**bold italic font style** を適用し、さらに **save HTML to a stream** してすべてをメモリ上に保持します。最後まで実行すれば、ほんの小さな HTML スニペットを鮮明な PNG ファイルに変換する、すぐに実行できるコンソールアプリが手に入ります。 + +--- + +## 必要なもの + +- **.NET 6+**(コードは .NET Core と .NET Framework の両方で動作します) +- **Aspose.HTML for .NET** NuGet パッケージ – `Install-Package Aspose.HTML` +- お好みの IDE(Visual Studio、Rider、または VS Code) – どれでも構いません。 + +余計なフォントも外部ツールも、そして一時ファイルも必要ありません。純粋な C# だけです。 + +--- + +## ステップ 1: シンプルな HTML ドキュメントを作成 + +最初に行うのは、メモリ内の HTML ドキュメントを構築することです。これは、プロセス内だけに存在する仮想的なウェブページと考えてください。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Why this matters:** プログラムで DOM を構築することで、ファイル I/O のオーバーヘッドを回避し、動的データをその場で注入できます。`HtmlDocument` クラスはすべての Aspose.HTML 操作のエントリーポイントです。 + +--- + +## ステップ 2: HTML をストリームに保存 + +マークアップをディスクに書き込む代わりに、カスタム `ResourceHandler` で取得します。これはワークフローの **save html to stream** 部分です。 + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Pro tip:** `MemoryHandler` は小さいですが強力です。後で画像、CSS、フォントを埋め込む必要がある場合は、`HandleResource` を拡張して適切なストリームを返すだけです。 + +--- + +## ステップ 3: ボールドイタリックフォントスタイルを設定 + +テキストをレンダリングする際、ブラウザ上と同じ見た目にしたいことが多いです。Aspose.HTML ではレンダリングオプションで **bold italic font style** を直接設定できます。 + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **What’s happening:** +> * `UseAntialiasing` は形状のエッジを滑らかにします。 +> * `UseHinting` はグリフの位置決めを改善し、小さなテキストに重要です。 +> * `FontStyle` は `Bold` と `Italic` フラグを組み合わせるため、ドキュメント内のすべてのテキストが上書きされない限りそのスタイルを継承します。 + +--- + +## ステップ 4: HTML ドキュメントを PNG 画像にレンダリング + +さあ楽しいパートです – HTML を画像ファイルに変換します。`ImageRenderer` がすべての重い処理を行います。 + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +プログラムを実行すると、作業ディレクトリに `output.png` というファイルが生成されます。そこには `` 要素を追加するだけで、保存可能な有効な HTML 構造がすでにできあがります。 + +> **Pro tip:** 完全な HTML 骨格(``、`
` など)が必要な場合でも、Aspose.HTML はドキュメントを保存するときに自動的に生成します。ボディ コンテンツだけを追加した場合でも問題ありません。 + +## Step 2: **Custom Resource Handler** の実装 – メモリ上で HTML をキャプチャ + +*リソースハンドラ* は Aspose.HTML に対し、各リソース(HTML、CSS、画像など)を書き込む先を指示します。`HandleResource` をオーバーライドすることで、HTML 出力先をファイルではなく `MemoryStream` に変更できます。 + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Why we use a custom handler:** +- **Performance:** ディスク I/O が発生せず、すべて RAM 上に留まります。 +- **Security:** 一時ファイルが作成されないため、情報漏洩のリスクが低減します。 +- **Flexibility:** 後でストリームをレスポンス、データベース、または別の API にパイプできます。 + +## Step 3: ハンドラを使ってドキュメントを保存 – **Generate HTML Programmatically** の中心 + +ここでドキュメントとハンドラを結び付けます。`htmlDoc.Save(handler)` が実行されると、Aspose.HTML は `HandleResource` を呼び出し、ストリームへの書き込みを委譲します。 + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +この時点で `handler.HtmlStream` には生の HTML バイト列が格納されています。ディスクには何も書き込まれておらず、ストリームは好きなだけ再利用できます(位置をリセットすることを忘れずに)。 + +## Step 4: メモリ上の生成 HTML を読み取る – 出力を検証 + +すべてが正しく動作したことを確認するため、ストリームの位置を先頭にリセットし、テキストとして読み戻します。 + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Expected output** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +上記のマークアップが表示されれば、Aspose.HTML と **custom resource handler** を使って **generate html programmatically** に成功したことになります。 + +## Common Variations & Edge Cases + +### CSS や画像の取り扱い + +デモでは HTML 以外のリソースを `Stream.Null` で無視しています。実際のシナリオでは CSS ファイルや画像もキャプチャしたい場合があります。 + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### 複数回の保存で同じハンドラを再利用 + +ループ内で複数の HTML スニペットを生成する場合は、各イテレーションで新しい `MemoryHtmlHandler` を作成するか、既存のストリームをクリアしてください。 + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### 非同期保存 (Aspose.HTML 23.4+) + +新しいバージョンでは非同期保存がサポートされています。 + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +`await` を使用し、メソッドを `async` にすることを忘れないでください。 + +## 完全動作サンプル + +以下はコンソール アプリにそのまま貼り付けて使用できる完全なプログラムです。解説コメントも含めています。 + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +プログラムを実行します(`dotnet run`)。コンソールに先ほどと同じ HTML が出力されるはずです。 + +## 結論 + +Aspose.HTML を利用し、**custom resource handler** で出力先をメモリに限定することで、**create HTML document C#** をファイルシステムに触れずに実現し、**generate HTML programmatically** が可能になることを示しました。このパターンは、メールテンプレート、オンザフライレポート、HTML スニペットを返すマイクロサービスなど、さまざまなシナリオにスケールします。 + +次のステップは?ハンドラ経由で CSS スタイルシートを追加したり、ASP.NET Core のレスポンスに直接ストリームを書き込んだり(`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`)してみてください。また、出力を PDF 変換や HTML‑to‑image ライブラリに渡すことで、さらにリッチなワークフローを構築できます。 + +画像の取り扱い、非同期保存、他ライブラリとの統合について質問があればコメントで教えてください。Happy coding! + +{{< /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/rendering-html-documents/_index.md b/html/korean/net/rendering-html-documents/_index.md index 7178d36b0..daadb175d 100644 --- a/html/korean/net/rendering-html-documents/_index.md +++ b/html/korean/net/rendering-html-documents/_index.md @@ -64,6 +64,12 @@ Aspose.HTML for .NET을 사용하여 여러 HTML 문서를 렌더링하는 방 ### [HTML에서 PNG 생성 – 전체 C# 렌더링 가이드](./create-png-from-html-full-c-rendering-guide/) .NET용 Aspose.HTML을 사용해 HTML을 PNG 이미지로 변환하는 전체 C# 렌더링 과정을 배워보세요. +### [C#에서 HTML을 이미지로 렌더링 – 완전 단계별 가이드](./render-html-to-image-in-c-complete-step-by-step-guide/) +Aspose.HTML for .NET을 사용하여 C#에서 HTML을 이미지로 변환하는 전체 과정을 단계별로 안내합니다. + +### [C#에서 HTML을 PNG로 렌더링 – 단계별 가이드](./render-html-to-png-in-c-step-by-step-guide/) +Aspose.HTML for .NET을 활용해 C#에서 HTML을 PNG로 변환하는 과정을 단계별로 안내합니다. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/korean/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/korean/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..30356c4e6 --- /dev/null +++ b/html/korean/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-03-14 +description: Aspose.HTML을 사용하여 HTML을 이미지로 빠르게 렌더링하세요. 웹 페이지를 PNG로 변환하고, 글꼴 스타일을 설정하며, + 몇 줄의 C# 코드만으로 렌더링된 이미지를 저장하는 방법을 배워보세요. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: ko +og_description: Aspose.HTML를 사용하여 HTML을 이미지로 렌더링합니다. 이 튜토리얼에서는 웹 페이지를 PNG로 변환하고, 글꼴 + 스타일을 설정하며, C#에서 렌더링된 이미지를 저장하는 방법을 보여줍니다. +og_title: C#에서 HTML을 이미지로 변환하기 – 빠르고 쉬운 가이드 +tags: +- C# +- Aspose.HTML +- Image Rendering +title: C#에서 HTML을 이미지로 렌더링하기 – 완전한 단계별 가이드 +url: /ko/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to Image – Complete C# Tutorial + +HTML을 **render HTML to image** 해야 하는데 어떤 라이브러리를 골라야 할지 몰라 고민한 적 있나요? 여러분만 그런 것이 아닙니다. 웹 자동화나 보고서 생성 시에 실시간 페이지를 PNG, JPEG, 혹은 BMP 형태로 보관하고 싶을 때가 많습니다. 좋은 소식은 Aspose.HTML을 사용하면 몇 줄의 코드만으로 **convert webpage to PNG** 를 손쉽게 수행할 수 있다는 점입니다. + +이 가이드에서는 Aspose.HTML 패키지 설치, 원격 URL 로드, 렌더링 옵션 조정(예: **set font style** 지정) 그리고 최종적으로 **save rendered image** 를 디스크에 저장하는 전체 과정을 단계별로 살펴봅니다. 끝까지 따라오시면 어떤 웹 페이지든 선명한 스크린샷으로 저장할 수 있는 콘솔 앱을 바로 만들 수 있습니다. + +## What You’ll Need + +시작하기 전에 아래 항목을 준비하세요: + +| Prerequisite | Reason | +|--------------|--------| +| .NET 6.0 SDK 또는 그 이상 | Aspose.HTML은 .NET Standard 2.0+ 를 대상으로 하므로 .NET 6이 최신 런타임을 제공합니다. | +| Visual Studio 2022 (또는 VS Code) | 편리한 IDE가 디버깅을 빠르게 해줍니다. | +| Aspose.HTML for .NET NuGet package | 실제 작업을 수행하는 엔진입니다. | +| 유효한 Aspose.HTML 라이선스 (선택 사항) | 라이선스가 없으면 출력 이미지에 워터마크가 표시됩니다. | + +패키지는 CLI로도 설치할 수 있습니다: + +```bash +dotnet add package Aspose.HTML +``` + +GUI를 선호한다면 NuGet Package Manager에서 “Aspose.HTML”을 검색하면 됩니다. + +--- + +## Step 1: Load the Web Page You Want to Rasterize + +먼저 Aspose.HTML에 소스 문서를 제공해야 합니다. 로컬 파일, 문자열, 혹은 원격 URL 중 하나가 될 수 있습니다. 실제 상황에서는 실시간 사이트를 다루게 되므로 `https://example.com`을 지정해 **convert webpage to PNG** 해보겠습니다. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Why this matters:** 페이지를 `HtmlDocument` 로 로드하면 DOM 전체에 접근할 수 있어 CSS 삽입, 레이아웃 조작, 혹은 렌더링 전에 JavaScript 실행이 가능합니다. + +--- + +## Step 2: Configure Image Rendering Options + +HTML이 메모리에 로드되었으니 이제 최종 이미지의 모양을 지정해야 합니다. 여기서 **set font style** 을 지정하거나 안티앨리어싱, DPI 등을 조정할 수 있습니다. 아래는 품질과 속도의 균형을 맞춘 기본 설정 예시입니다. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Pro tip:** 일반 굵기만 필요하면 `WebFontStyle` 플래그를 생략하세요. 헤드라인에는 `WebFontStyle.Bold`만, 캡션에는 `WebFontStyle.Italic`을 사용할 수 있습니다. + +--- + +## Step 3: Render the Page and **Save Rendered Image** as PNG + +문서와 옵션이 준비되었으면 `ImageRenderer` 를 인스턴스화하고 출력 파일을 저장하면 됩니다. `using` 블록을 사용하면 리소스가 즉시 해제됩니다. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +프로그램을 실행하면 프로젝트 폴더에 `page.png` 파일이 생성되고, *example.com* 의 정확한 스냅샷이 저장됩니다. 이미지 뷰어로 열어 보면 앞서 지정한 굵은‑이탤릭 스타일이 적용된 것을 확인할 수 있습니다. + +### Expected Output + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +PNG 파일은 페이지 원본 크기에 따라 대략 800 × 600 px 정도이며, 안티앨리어싱 덕분에 가장자리가 부드럽게 처리됩니다. + +--- + +## Full Working Example + +모든 코드를 합치면 `Program.cs`에 그대로 붙여넣을 수 있는 최소 콘솔 앱이 됩니다. 바로 컴파일하고 실행할 수 있습니다. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +다음 명령으로 실행하세요: + +```bash +dotnet run +``` + +…그리고 아카이빙, 이메일 전송, 혹은 보고서에 삽입할 수 있는 새로운 PNG 파일이 생성됩니다. + +--- + +## Variations & Edge Cases + +### 1. Converting to JPEG Instead of PNG + +다운스트림 시스템이 JPEG(파일 크기 작고 손실 압축) 를 선호한다면 `Save` 메서드의 파일 확장자를 바꾸기만 하면 됩니다. Aspose.HTML은 경로에서 형식을 자동으로 감지합니다. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +`JpegRenderingOptions` 로 압축 품질도 조정할 수 있습니다. + +### 2. Changing Image Dimensions + +전체 스크린샷이 아니라 썸네일이 필요할 때는 옵션의 `ImageSize` 를 설정합니다: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Handling Authentication‑Protected Pages + +대상 URL이 기본 인증을 요구한다면 `HtmlDocument` 를 만들기 전에 `HttpWebRequest` 로 자격 증명을 전달합니다. 또는 `HttpClient` 로 HTML을 직접 다운로드한 뒤 문자열로 전달할 수도 있습니다: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Using a Custom Font + +Aspose.HTML은 로컬 폰트를 임베드할 수 있습니다. 문서를 로드하기 전에 폰트 폴더를 등록하세요: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +이제 페이지 내 `font-family` 선언이 사용자 지정 폰트 파일을 참조하게 됩니다. + +### 5. Rendering Multiple Pages in a Loop + +URL 리스트를 일괄 처리해야 할 경우: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Common Pitfalls & How to Avoid Them + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Blank PNG file | `HtmlDocument.IsEmpty` 가 true (페이지 로드 실패) | URL 확인, 네트워크 프록시 점검, TLS 1.2 활성화 여부 확인 | +| Garbled text on Linux | 폰트 힌팅 비활성화 | `renderingOptions.TextOptions.UseHinting = true;` 설정 | +| Watermark on output | 라이선스 미등록 | `License license = new License(); license.SetLicense("Aspose.Total.lic");` 로 임시 또는 정식 라이선스 등록 | +| Low‑resolution image | 기본 DPI 96이 인쇄용으로 부족 | `renderingOptions.DpiX` 와 `DpiY` 를 150‑300 으로 증가 | + +--- + +## 🎉 Conclusion + +Aspose.HTML을 사용해 C#에서 **render HTML to image** 하는 전체 과정을 살펴보았습니다. 원격 페이지 로드, 안티앨리어싱 및 **set font style** 설정, 그리고 최종적으로 **save rendered image** 를 PNG 로 저장하는 흐름을 몇 단계로 정리했습니다. + +이제 **convert webpage to PNG** 를 실시간으로 수행해 보고서에 스크린샷을 삽입하거나 카탈로그용 썸네일을 자동 생성할 수 있습니다—브라우저 자동화 없이도 가능합니다. + +### What’s Next? + +- 다양한 화면 크기(모바일 vs 데스크톱) 에 대해 **convert html to png** 를 실험해 보세요. +- 인쇄용 문서가 필요하면 `PdfRenderer` 로 PDF 내보내기를 시도해 보세요. +- 렌더링 전에 워터마크 삽입이나 커스텀 CSS 적용을 위해 Aspose.HTML의 DOM 조작 API 를 탐색해 보세요. + +궁금한 점(에지 케이스, 라이선스, 성능 튜닝 등)이 있으면 아래 댓글로 남겨 주세요. Happy coding! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/korean/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..e35e7c7ac --- /dev/null +++ b/html/korean/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-03-14 +description: Aspose.HTML를 사용하여 HTML을 빠르게 PNG로 렌더링합니다. HTML에서 PNG를 생성하고, 굵은 이탤릭 글꼴 + 스타일을 적용하며, HTML을 스트림에 저장하는 방법을 배워보세요. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: ko +og_description: Aspose.HTML를 사용하여 HTML을 PNG로 렌더링합니다. 이 가이드는 HTML에서 PNG를 생성하고, 굵은 이탤릭 + 글꼴 스타일을 사용하며, HTML을 스트림에 저장하는 방법을 보여줍니다. +og_title: C#에서 HTML을 PNG로 렌더링 – 완전한 프로그래밍 워크스루 +tags: +- Aspose.HTML +- C# +- Image Rendering +title: C#에서 HTML을 PNG로 렌더링하기 – 단계별 가이드 +url: /ko/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 HTML을 PNG로 렌더링하기 – 완전 프로그래밍 워크스루 + +HTML을 PNG로 **렌더링**해야 하는데 어떤 라이브러리가 픽셀 단위까지 정확한 결과를 제공할지 몰라 고민한 적 있나요? 여러분만 그런 것이 아닙니다. 많은 웹‑투‑이미지 파이프라인에서 개발자들은 폰트 누락, 흐릿한 텍스트, 혹은 “HTML을 먼저 디스크에 쓰지 않고 어떻게 캡처할까?” 같은 문제에 부딪히곤 합니다. + +핵심은 이렇습니다: Aspose.HTML을 사용하면 전체 과정이 식은 죽 먹기입니다. 이번 튜토리얼에서는 **HTML에서 PNG 생성**, **볼드 이탤릭 폰트 스타일 적용**, 그리고 **HTML을 스트림에 저장**하는 방법을 다룹니다. 최종적으로 메모리 내에서 작은 HTML 스니펫을 선명한 PNG 파일로 변환하는 콘솔 앱을 완성하게 됩니다. + +--- + +## 준비물 + +- **.NET 6+** (코드는 .NET Core와 .NET Framework 모두에서 동작) +- **Aspose.HTML for .NET** NuGet 패키지 – `Install-Package Aspose.HTML` +- 선호하는 IDE (Visual Studio, Rider, VS Code 등) – 어느 것이든 상관없습니다. + +추가 폰트, 외부 도구, 임시 파일 전혀 필요 없습니다. 순수 C#만 있으면 됩니다. + +--- + +## 1단계: 간단한 HTML 문서 만들기 + +먼저 메모리 내에서 HTML 문서를 구축합니다. 프로세스 안에서만 존재하는 가상의 웹 페이지라고 생각하면 됩니다. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **왜 중요한가:** DOM을 프로그래밍 방식으로 구성하면 파일 I/O 오버헤드를 피하고, 실행 시 동적으로 데이터를 주입할 수 있습니다. `HtmlDocument` 클래스는 모든 Aspose.HTML 작업의 진입점입니다. + +--- + +## 2단계: HTML을 스트림에 저장 + +마크업을 디스크에 쓰는 대신, 커스텀 `ResourceHandler`에 캡처합니다. 이것이 워크플로우에서 **HTML을 스트림에 저장**하는 부분입니다. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **프로 팁:** `MemoryHandler`는 작지만 강력합니다. 나중에 이미지, CSS, 폰트를 포함해야 하면 `HandleResource`를 확장해 적절한 스트림을 반환하면 됩니다. + +--- + +## 3단계: 볼드 이탤릭 폰트 스타일 설정 + +텍스트를 렌더링할 때 브라우저와 똑같은 모양을 원하죠. Aspose.HTML에서는 **볼드 이탤릭 폰트 스타일**을 렌더링 옵션에 직접 지정할 수 있습니다. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **무슨 일인가:** +> * `UseAntialiasing`은 도형 가장자리를 부드럽게 합니다. +> * `UseHinting`은 글리프 위치를 개선해 작은 텍스트에 특히 중요합니다. +> * `FontStyle`은 `Bold`와 `Italic` 플래그를 결합하므로, 문서 내 모든 텍스트가 별도 지정이 없을 경우 이 스타일을 상속받습니다. + +--- + +## 4단계: HTML 문서를 PNG 이미지로 렌더링 + +이제 재미있는 부분—HTML을 이미지 파일로 변환합니다. `ImageRenderer`가 모든 무거운 작업을 담당합니다. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +프로그램을 실행하면 작업 디렉터리에 `output.png` 파일이 생성됩니다. 이 파일에는 볼드‑이탤릭 스타일이 적용된 `` 요소를 추가함으로써 이미 저장할 수 있는 유효한 HTML 구조가 준비됩니다. + +> **Pro tip:** 전체 HTML 골격(`\`, `\
` 등)이 필요하면, Aspose.HTML은 문서를 저장할 때 자동으로 생성합니다. 본문 내용만 추가했더라도 마찬가지입니다. + +## 2단계: **Custom Resource Handler** 구현 – 메모리 내 HTML 캡처 + +리소스 핸들러는 Aspose.HTML에 각 리소스(HTML, CSS, 이미지 등)를 어디에 쓸지 알려줍니다. `HandleResource`를 오버라이드하면 HTML 출력을 파일이 아닌 `MemoryStream`으로 보낼 수 있습니다. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Why we use a custom handler:** +- **Performance:** 디스크 I/O가 없으며 모든 것이 RAM에 유지됩니다. +- **Security:** 노출될 수 있는 임시 파일이 없습니다. +- **Flexibility:** 이후 스트림을 응답, 데이터베이스, 또는 다른 API로 전달할 수 있습니다. + +## 3단계: 핸들러를 사용해 문서 저장 – **Generate HTML Programmatically** 의 핵심 + +이제 문서와 핸들러를 연결합니다. `htmlDoc.Save(handler)`가 실행되면 Aspose.HTML이 `HandleResource`를 호출하고, 우리가 쓸 스트림을 제공합니다. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +이 시점에서 `handler.HtmlStream`은 원시 HTML 바이트를 포함하고 있습니다. 디스크에 아무 것도 쓰여지지 않았으며, 스트림을 원하는 만큼 재사용할 수 있습니다(단, 위치를 재설정하는 것을 잊지 마세요). + +## 4단계: 메모리에서 생성된 HTML 읽기 – 출력 확인 + +모든 작업이 정상적으로 수행됐는지 확인하려면 스트림 위치를 처음으로 재설정하고 텍스트를 다시 읽습니다. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**예상 출력** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +위와 같은 마크업이 보이면 축하합니다—Aspose.HTML과 **custom resource handler** 를 사용해 **generate html programmatically** 를 성공적으로 수행한 것입니다. + +## 일반적인 변형 및 예외 상황 + +### CSS 또는 이미지 처리 + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### 여러 번 저장 시 동일 핸들러 재사용 + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### 비동기 저장 (Aspose.HTML 23.4+) + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +`await`를 사용하고 메서드를 `async`로 선언하는 것을 잊지 마세요. + +## 전체 작업 예제 + +아래는 콘솔 앱에 복사‑붙여넣기 할 수 있는 완전한 프로그램입니다. 앞서 논의한 모든 요소와 명확성을 위한 몇 가지 주석이 포함되어 있습니다. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +프로그램을 실행(`dotnet run`)하면 콘솔에 HTML이 앞서 보여준 그대로 출력되는 것을 확인할 수 있습니다. + +## 결론 + +우리는 Aspose.HTML을 사용해 **create HTML document C#** 를 수행하고, **custom resource handler** 로 출력을 캡처하며, 파일 시스템을 건드리지 않고 **generate HTML programmatically** 하는 방법을 보여주었습니다. 이 패턴은 확장성이 뛰어나며, 이메일 템플릿, 즉시 보고서, 혹은 HTML 스니펫을 반환하는 마이크로서비스를 구축할 때도 적용할 수 있습니다. + +다음 단계는? 핸들러를 통해 CSS 스타일시트를 추가하거나, HTML을 ASP.NET Core 응답(`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`)에 직접 스트리밍해 보세요. 또한 출력을 PDF 변환기나 HTML‑to‑image 라이브러리에 연결해 보다 풍부한 워크플로를 구현할 수도 있습니다. + +이미지 처리, 비동기 저장, 다른 라이브러리와의 통합 등에 대한 질문이 있나요? 댓글을 남겨 주세요. 즐거운 코딩 되세요! + +{{< /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/rendering-html-documents/_index.md b/html/polish/net/rendering-html-documents/_index.md index 41f09366a..14e24d8c7 100644 --- a/html/polish/net/rendering-html-documents/_index.md +++ b/html/polish/net/rendering-html-documents/_index.md @@ -43,8 +43,15 @@ Teraz, gdy masz już skonfigurowany Aspose.HTML dla .NET, czas zapoznać się z ### [Renderuj HTML jako PNG w .NET za pomocą Aspose.HTML](./render-html-as-png/) Naucz się pracować z Aspose.HTML dla .NET: Manipuluj HTML, konwertuj do różnych formatów i nie tylko. Zanurz się w tym kompleksowym samouczku! +### [Renderowanie HTML do obrazu w C# – Kompletny przewodnik krok po kroku](./render-html-to-image-in-c-complete-step-by-step-guide/) +Pełny przewodnik w C# pokazujący, jak przy użyciu Aspose.HTML renderować HTML do obrazu, krok po kroku. + ### [Jak renderować HTML jako PNG – Kompletny przewodnik C#](./how-to-render-html-as-png-complete-c-guide/) Pełny przewodnik C# pokazujący, jak przy użyciu Aspose.HTML renderować HTML jako PNG, krok po kroku. + +### [Renderuj HTML do PNG w C# – Przewodnik krok po kroku](./render-html-to-png-in-c-step-by-step-guide/) +Pełny przewodnik w C# pokazujący, jak przy użyciu Aspose.HTML renderować HTML do PNG, krok po kroku. + ### [Jak używać Aspose do renderowania HTML do PNG – przewodnik krok po kroku](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) Naucz się, jak przy użyciu Aspose renderować HTML do formatu PNG w kilku prostych krokach. diff --git a/html/polish/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/polish/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..2d3b4745a --- /dev/null +++ b/html/polish/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-03-14 +description: Szybko renderuj HTML do obrazu przy użyciu Aspose.HTML. Dowiedz się, + jak przekonwertować stronę internetową na PNG, ustawić styl czcionki i zapisać wyrenderowany + obraz w kilku linijkach C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: pl +og_description: Renderowanie HTML do obrazu przy użyciu Aspose.HTML. Ten samouczek + pokazuje, jak przekonwertować stronę internetową na PNG, ustawić styl czcionki i + zapisać wyrenderowany obraz w C#. +og_title: Renderowanie HTML do obrazu w C# – szybki i prosty przewodnik +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Renderowanie HTML do obrazu w C# – Kompletny przewodnik krok po kroku +url: /pl/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +przyczyna | Rozwiązanie". Keep rows translated. + +Also list items under "Variations & Edge Cases" etc. + +Let's translate. + +Proceed. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to Image – Kompletny samouczek C# + +Kiedykolwiek potrzebowałeś **renderować HTML do obrazu**, ale nie wiedziałeś, którą bibliotekę wybrać? Nie jesteś sam. W wielu scenariuszach automatyzacji sieci lub raportowania kończysz z żywą stroną, którą chcesz zarchiwizować jako PNG, JPEG, a nawet BMP. Dobrą wiadomością jest to, że Aspose.HTML robi to w mig, pozwalając **konwertować stronę internetową do PNG** w kilku linijkach kodu. + +W tym przewodniku przejdziemy przez cały proces: od instalacji pakietu Aspose.HTML, wczytania zdalnego URL, dostosowania opcji renderowania (w tym **ustawiania stylu czcionki**), aż po **zapisanie wyrenderowanego obrazu** na dysku. Po zakończeniu będziesz mieć gotową aplikację konsolową, która tworzy wyraźny zrzut ekranu dowolnej strony internetowej. + +## Czego będziesz potrzebować + +Zanim zaczniemy, upewnij się, że masz: + +| Wymaganie | Powód | +|-----------|-------| +| .NET 6.0 SDK lub nowszy | Aspose.HTML celuje w .NET Standard 2.0+, więc .NET 6 zapewnia najnowsze środowisko uruchomieniowe. | +| Visual Studio 2022 (lub VS Code) | Wygodne IDE przyspiesza debugowanie. | +| Pakiet NuGet Aspose.HTML for .NET | To silnik, który wykonuje całą ciężką pracę. | +| Ważna licencja Aspose.HTML (opcjonalnie) | Bez licencji na wyjściowym obrazie pojawi się znak wodny. | + +Pakiet możesz pobrać z wiersza poleceń: + +```bash +dotnet add package Aspose.HTML +``` + +Jeśli wolisz interfejs graficzny, po prostu wyszukaj „Aspose.HTML” w Menedżerze pakietów NuGet. + +--- + +## Krok 1: Wczytaj stronę internetową, którą chcesz rasteryzować + +Pierwszą rzeczą, którą musisz zrobić, jest przekazanie Aspose.HTML dokumentu źródłowego. Może to być plik lokalny, łańcuch znaków lub zdalny URL. W większości rzeczywistych scenariuszy będziesz pracował z żywą witryną, więc **konwertuj stronę internetową do PNG**, wskazując `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Dlaczego to ważne:** Wczytanie strony jako `HtmlDocument` daje pełny dostęp do DOM, co oznacza, że możesz wstrzykiwać CSS, manipulować układem lub nawet uruchamiać JavaScript przed rasteryzacją. + +--- + +## Krok 2: Skonfiguruj opcje renderowania obrazu + +Teraz, gdy HTML znajduje się w pamięci, musimy powiedzieć rendererowi, jak ma wyglądać końcowy obraz. Tutaj możesz **ustawić styl czcionki**, włączyć antyaliasing lub dostosować DPI. Poniżej solidna domyślna konfiguracja, która równoważy jakość i szybkość. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Porada:** Jeśli potrzebujesz tylko zwykłej wagi, usuń flagi `WebFontStyle`. Dla nagłówków możesz użyć samego `WebFontStyle.Bold`, a dla podpisów `WebFontStyle.Italic`. + +--- + +## Krok 3: Renderuj stronę i **zapisz wyrenderowany obraz** jako PNG + +Mając dokument i opcje gotowe, ostatnim krokiem jest utworzenie `ImageRenderer` i zapisanie pliku wyjściowego. Blok `using` zapewnia szybkie zwolnienie zasobów. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +Po uruchomieniu programu powinien pojawić się plik `page.png` w folderze projektu, zawierający wierny zrzut *example.com*. Otwórz go w dowolnym przeglądarce obrazów, a zauważysz pogrubiono‑pochyły styl, który wcześniej ustawiliśmy. + +### Oczekiwany wynik + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +PNG będzie miał w przybliżeniu 800 × 600 px (w zależności od oryginalnych wymiarów strony) z gładkimi krawędziami dzięki antyaliasingowi. + +--- + +## Pełny działający przykład + +Łącząc wszystko razem, oto minimalna aplikacja konsolowa, którą możesz skopiować‑wkleić do `Program.cs`. Kompiluje się i działa od razu. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Uruchom ją poleceniem: + +```bash +dotnet run +``` + +…i będziesz mieć świeży PNG gotowy do archiwizacji, wysyłki e‑mailem lub osadzenia w raporcie. + +--- + +## Warianty i przypadki brzegowe + +### 1. Konwersja do JPEG zamiast PNG + +Jeśli Twój system docelowy preferuje JPEG (mniejszy rozmiar pliku, kompresja stratna), po prostu zmień rozszerzenie pliku w `Save`. Aspose.HTML automatycznie wykrywa format z ścieżki. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +Możesz także dostosować jakość kompresji za pomocą `JpegRenderingOptions`. + +### 2. Zmiana wymiarów obrazu + +Czasami potrzebujesz miniaturki zamiast pełnego zrzutu. Ustaw `ImageSize` w opcjach: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Obsługa stron chronionych uwierzytelnieniem + +Jeśli docelowy URL wymaga podstawowego uwierzytelnienia, przekaż poświadczenia przez `HttpWebRequest` przed utworzeniem `HtmlDocument`. Alternatywnie pobierz HTML samodzielnie (używając `HttpClient`) i przekaż go jako łańcuch znaków: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Użycie własnej czcionki + +Aspose.HTML może osadzać lokalne czcionki. Zarejestruj folder czcionek przed wczytaniem dokumentu: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Teraz wszystkie deklaracje `font-family` na stronie zostaną rozwiązane do Twoich własnych plików. + +### 5. Renderowanie wielu stron w pętli + +Jeśli musisz przetworzyć wsadowo listę URL‑i: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Typowe pułapki i jak ich unikać + +| Objaw | Prawdopodobna przyczyna | Rozwiązanie | +|-------|--------------------------|-------------| +| Pusty plik PNG | `HtmlDocument.IsEmpty` prawda (strona nie została wczytana) | Sprawdź URL, konfigurację proxy, upewnij się, że TLS 1.2 jest włączony. | +| Zniekształcony tekst na Linuksie | Wyłączone hintowanie czcionek | Ustaw `renderingOptions.TextOptions.UseHinting = true;`. | +| Znak wodny na wyjściu | Brak podanej licencji | Zarejestruj tymczasową lub pełną licencję poprzez `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Obraz o niskiej rozdzielczości | Domyślne DPI 96 jest niewystarczające do druku | Zwiększ `renderingOptions.DpiX` i `DpiY` do 150‑300. | + +--- + +## 🎉 Podsumowanie + +Omówiliśmy wszystko, co potrzebne, aby **renderować HTML do obrazu** przy użyciu Aspose.HTML w C#. Od wczytania zdalnej strony, konfiguracji antyaliasingu i **ustawiania stylu czcionki**, po ostateczne **zapisanie wyrenderowanego obrazu** jako PNG – cały przepływ mieści się w kilku zwięzłych krokach. + +Teraz możesz **konwertować stronę internetową do PNG** w locie, osadzać zrzuty ekranu w raportach lub generować miniaturki do katalogu — bez potrzeby automatyzacji przeglądarki. + +### Co dalej? + +- Eksperymentuj z **konwersją html do png** dla różnych rozmiarów ekranu (mobile vs desktop). +- Spróbuj eksportu do PDF przy użyciu `PdfRenderer`, jeśli potrzebny jest dokument do druku. +- Zagłęb się w API manipulacji DOM Aspose.HTML, aby wstawiać znaki wodne lub własny CSS przed renderowaniem. + +Masz pytania dotyczące przypadków brzegowych, licencjonowania lub optymalizacji wydajności? Zostaw komentarz poniżej i powodzenia w kodowaniu! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/polish/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..a33df556e --- /dev/null +++ b/html/polish/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-03-14 +description: Szybko renderuj HTML do PNG za pomocą Aspose.HTML. Dowiedz się, jak generować + PNG z HTML, zastosować pogrubiony i pochylony styl czcionki oraz zapisać HTML do + strumienia. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: pl +og_description: Renderuj HTML do PNG za pomocą Aspose.HTML. Ten przewodnik pokazuje, + jak wygenerować PNG z HTML, używać pogrubionego i pochylonego stylu czcionki oraz + zapisać HTML do strumienia. +og_title: Renderowanie HTML do PNG w C# – Kompletny przewodnik programistyczny +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Renderowanie HTML do PNG w C# – Przewodnik krok po kroku +url: /pl/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +output.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Renderowanie HTML do PNG w C# – Kompletny przewodnik programistyczny + +Kiedykolwiek potrzebowałeś **renderować HTML do PNG**, ale nie byłeś pewien, która biblioteka zapewni wyniki piksel‑idealne? Nie jesteś sam. W wielu potokach web‑to‑image programiści napotykają brakujące czcionki, rozmyty tekst lub przerażające pytanie „jak przechwycić HTML bez zapisywania go najpierw na dysk?”. + +Rzecz jest taka: Aspose.HTML sprawia, że cały proces jest dziecinnie prosty. W tym tutorialu **wygenerujemy PNG z HTML**, zastosujemy **pogrubioną kursywę**, oraz **zapiszemy HTML do strumienia**, aby wszystko pozostało w pamięci. Po zakończeniu będziesz mieć gotową do uruchomienia aplikację konsolową, która zamieni mały fragment HTML w wyraźny plik PNG. + +--- + +## Czego będziesz potrzebować + +- **.NET 6+** (kod działa zarówno z .NET Core, jak i .NET Framework) +- **Aspose.HTML for .NET** pakiet NuGet – `Install-Package Aspose.HTML` +- Ulubione IDE (Visual Studio, Rider lub VS Code) – dowolne się sprawdzi. + +Bez dodatkowych czcionek, bez zewnętrznych narzędzi i zdecydowanie bez plików tymczasowych. Po prostu czysty C#. + +## Krok 1: Utwórz prosty dokument HTML + +Pierwszą rzeczą, którą robimy, jest zbudowanie dokumentu HTML w pamięci. Traktuj to jak wirtualną stronę internetową, która istnieje wyłącznie w obrębie Twojego procesu. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Dlaczego to ważne:** Tworząc DOM programowo, unikasz narzutu operacji we/wy na plikach i możesz wstrzykiwać dynamiczne dane w locie. Klasa `HtmlDocument` jest punktem wejścia dla każdej operacji Aspose.HTML. + +--- + +## Krok 2: Zapisz HTML do strumienia + +Zamiast zapisywać znacznik na dysku, przechwytujemy go w niestandardowym `ResourceHandler`. To jest część przepływu **save html to stream**. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Porada:** `MemoryHandler` jest mały, ale potężny. Jeśli później będziesz musiał osadzić obrazy, CSS lub czcionki, po prostu rozszerz `HandleResource`, aby zwracał odpowiednie strumienie. + +--- + +## Krok 3: Skonfiguruj styl czcionki pogrubiona kursywa + +Podczas renderowania tekstu często chcesz, aby wyglądał dokładnie tak, jak w przeglądarce. Aspose.HTML pozwala ustawić **bold italic font style** bezpośrednio w opcjach renderowania. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **Co się dzieje:** +> * `UseAntialiasing` wygładza krawędzie kształtów. +> * `UseHinting` poprawia pozycjonowanie glifów, co jest kluczowe przy małym tekście. +> * `FontStyle` łączy flagi `Bold` i `Italic`, więc każdy fragment tekstu w dokumencie dziedziczy ten styl, chyba że zostanie nadpisany. + +--- + +## Krok 4: Renderuj dokument HTML do obrazu PNG + +Teraz najciekawsza część – przekształcenie tego HTML w plik obrazu. `ImageRenderer` wykonuje całą ciężką pracę. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Jeśli uruchomisz program, zobaczysz plik o nazwie `output.png` w katalogu roboczym. Zawiera on nagłówek `` od razu masz poprawną strukturę HTML gotową do zapisania. + +> **Pro tip:** Jeśli potrzebujesz pełnego szkieletu HTML (``, `
` itp.), Aspose.HTML automatycznie go wygeneruje przy zapisie dokumentu, nawet jeśli dodałeś tylko zawartość body. + +## Krok 2: Implementacja **Custom Resource Handler** – przechwytywanie HTML w pamięci + +*Resource handler* informuje Aspose.HTML, gdzie zapisać każdy zasób (HTML, CSS, obrazy itp.). Nadpisując `HandleResource`, możemy skierować wyjście HTML do `MemoryStream` zamiast do pliku. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Dlaczego używamy własnego handlera:** +- **Wydajność:** Brak operacji dyskowych, wszystko pozostaje w RAM. +- **Bezpieczeństwo:** Brak tymczasowych plików, które mogłyby zostać ujawnione. +- **Elastyczność:** Później możesz przekierować strumień do odpowiedzi, bazy danych lub innego API. + +## Krok 3: Zapis dokumentu przy użyciu handlera – serce **Generate HTML Programmatically** + +Teraz łączymy dokument i handler. Gdy wywołasz `htmlDoc.Save(handler)`, Aspose.HTML wywoła `HandleResource`, przekazując nam strumień do zapisu. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +W tym momencie `handler.HtmlStream` zawiera surowe bajty HTML. Nic nie zostało zapisane na dysku, a strumień możesz używać dowolną ilość razy (pamiętaj tylko, aby zresetować jego pozycję). + +## Krok 4: Odczyt wygenerowanego HTML z pamięci – weryfikacja wyniku + +Aby udowodnić, że wszystko działa, resetujemy pozycję strumienia na początek i odczytujemy tekst z powrotem. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Oczekiwany wynik** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Jeśli zobaczysz powyższy markup, gratulacje — udało Ci się **generate html programmatically** przy użyciu Aspose.HTML i **custom resource handler**. + +## Typowe warianty i przypadki brzegowe + +### Obsługa CSS lub obrazów + +Demo pomija zasoby nie‑HTML, zwracając `Stream.Null`. W rzeczywistej aplikacji możesz chcieć przechwycić pliki CSS lub obrazy: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Ponowne użycie tego samego handlera przy wielu zapisach + +Jeśli musisz wygenerować kilka fragmentów HTML w pętli, utwórz nowy `MemoryHtmlHandler` w każdej iteracji lub wyczyść istniejący strumień: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Asynchroniczny zapis (Aspose.HTML 23.4+) + +Nowsze wersje wspierają asynchroniczny zapis: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Pamiętaj, aby używać `await` i oznaczyć metodę jako `async`. + +## Pełny działający przykład + +Poniżej znajduje się kompletny program, który możesz skopiować i wkleić do aplikacji konsolowej. Zawiera wszystkie omawiane elementy oraz kilka komentarzy dla przejrzystości. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Uruchom program (`dotnet run`) i powinieneś zobaczyć HTML wypisany w konsoli, dokładnie tak jak wcześniej. + +## Zakończenie + +Pokazaliśmy, jak **create HTML document C#** przy użyciu Aspose.HTML, przechwycić wynik za pomocą **custom resource handler** i **generate HTML programmatically** bez dotykania systemu plików. Wzorzec skaluje się — niezależnie od tego, czy tworzysz szablony e‑maili, raporty w locie, czy mikroserwis zwracający fragmenty HTML. + +Co dalej? Spróbuj dodać arkusz CSS przez handler, albo strumieniowo przekazać HTML bezpośrednio w odpowiedzi ASP.NET Core (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Możesz także podłączyć wynik do konwertera PDF lub biblioteki HTML‑to‑image, aby uzyskać bardziej rozbudowane przepływy pracy. + +Masz pytania dotyczące obsługi obrazów, asynchronicznego zapisu lub integracji z innymi bibliotekami? Zostaw komentarz i powodzenia w kodowaniu! + +{{< /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/rendering-html-documents/_index.md b/html/portuguese/net/rendering-html-documents/_index.md index 3646fe093..7ebbf36a7 100644 --- a/html/portuguese/net/rendering-html-documents/_index.md +++ b/html/portuguese/net/rendering-html-documents/_index.md @@ -63,6 +63,12 @@ Desbloqueie o poder do Aspose.HTML para .NET! Aprenda como renderizar SVG Doc co ### [Criar PNG a partir de HTML – Guia Completo de Renderização em C#](./create-png-from-html-full-c-rendering-guide/) Aprenda a gerar imagens PNG a partir de HTML usando Aspose.HTML para .NET com um guia completo em C#. +### [Renderizar HTML para Imagem em C# – Guia Completo Passo a Passo](./render-html-to-image-in-c-complete-step-by-step-guide/) +Aprenda a converter HTML em imagens usando Aspose.HTML para .NET com um guia completo passo a passo em C#. + +### [Renderizar HTML para PNG em C# – Guia passo a passo](./render-html-to-png-in-c-step-by-step-guide/) +Aprenda a converter HTML em PNG usando Aspose.HTML para .NET com um guia detalhado passo a passo em C#. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/portuguese/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/portuguese/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..4db28ea08 --- /dev/null +++ b/html/portuguese/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-03-14 +description: Renderize HTML em imagem rapidamente usando Aspose.HTML. Aprenda como + converter uma página da web em PNG, definir o estilo da fonte e salvar a imagem + renderizada em apenas algumas linhas de C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: pt +og_description: Renderize HTML em imagem com Aspose.HTML. Este tutorial mostra como + converter uma página da web em PNG, definir o estilo da fonte e salvar a imagem + renderizada em C#. +og_title: Renderizar HTML para Imagem em C# – Guia Rápido e Fácil +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Renderizar HTML para Imagem em C# – Guia Completo Passo a Passo +url: /pt/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Renderizar HTML para Imagem – Tutorial Completo em C# + +Já precisou **renderizar HTML para imagem** mas não tinha certeza de qual biblioteca escolher? Você não está sozinho. Em muitos cenários de automação web ou geração de relatórios, você acaba com uma página ao vivo que deseja arquivar como PNG, JPEG ou até BMP. A boa notícia é que o Aspose.HTML torna isso muito fácil, permitindo que você **converta página da web para PNG** com apenas algumas linhas de código. + +Neste guia, percorreremos todo o processo: desde a instalação do pacote Aspose.HTML, carregamento de uma URL remota, ajuste das opções de renderização (incluindo como **definir estilo de fonte**), e finalmente **salvar imagem renderizada** no disco. Ao final, você terá um aplicativo console pronto‑para‑executar que produz uma captura de tela nítida de qualquer página web. + +## O que você precisará + +Antes de mergulharmos, certifique-se de que você tem: + +| Pré-requisito | Motivo | +|--------------|--------| +| .NET 6.0 SDK or later | O Aspose.HTML tem como alvo .NET Standard 2.0+, portanto o .NET 6 fornece o runtime mais recente. | +| Visual Studio 2022 (or VS Code) | Um IDE confortável acelera a depuração. | +| Aspose.HTML for .NET NuGet package | Este é o motor que faz o trabalho pesado. | +| A valid Aspose.HTML license (optional) | Sem uma licença, você receberá uma marca d'água na imagem de saída. | + +Você pode obter o pacote via CLI: + +```bash +dotnet add package Aspose.HTML +``` + +Se preferir a interface gráfica, basta procurar por “Aspose.HTML” no Gerenciador de Pacotes NuGet. + +--- + +## Etapa 1: Carregar a Página Web que Você Deseja Rasterizar + +A primeira coisa que você precisa fazer é fornecer ao Aspose.HTML um documento fonte. Ele pode ser um arquivo local, uma string ou uma URL remota. Na maioria dos cenários reais, você lidará com um site ao vivo, então vamos **converter página da web para PNG** apontando para `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Por que isso importa:** Carregar a página como um `HtmlDocument` lhe dá acesso total ao DOM, o que significa que você pode injetar CSS, manipular o layout ou até executar JavaScript antes da rasterização. + +--- + +## Etapa 2: Configurar Opções de Renderização de Imagem + +Agora que o HTML está na memória, precisamos dizer ao renderizador como queremos que a imagem final pareça. É aqui que você pode **definir estilo de fonte**, habilitar antialiasing ou ajustar o DPI. Abaixo está uma configuração padrão sólida que equilibra qualidade e velocidade. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Dica profissional:** Se você precisar apenas de peso regular, omita as flags `WebFontStyle`. Para títulos, talvez queira apenas `WebFontStyle.Bold`, enquanto legendas podem usar `WebFontStyle.Italic`. + +--- + +## Etapa 3: Renderizar a Página e **Salvar Imagem Renderizada** como PNG + +Com o documento e as opções prontos, a etapa final é instanciar `ImageRenderer` e gravar o arquivo de saída. O bloco `using` garante que os recursos sejam liberados prontamente. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +Ao executar o programa, você deverá ver um arquivo `page.png` na pasta do seu projeto contendo uma cópia fiel de *example.com*. Abra‑o com qualquer visualizador de imagens e você notará o estilo negrito‑itálico que solicitamos anteriormente. + +### Saída Esperada + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +O PNG terá aproximadamente 800 × 600 px (dependendo das dimensões originais da página) com bordas suaves graças ao antialiasing. + +--- + +## Exemplo Completo em Funcionamento + +Juntando tudo, aqui está um aplicativo console minimalista que você pode copiar‑colar em `Program.cs`. Ele compila e executa imediatamente. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Execute‑o com: + +```bash +dotnet run +``` + +…e você terá um PNG novo pronto para arquivar, enviar por e‑mail ou incorporar em um relatório. + +--- + +## Variações e Casos de Borda + +### 1. Convertendo para JPEG ao invés de PNG + +Se o seu sistema downstream preferir JPEG (tamanho de arquivo menor, compressão com perdas), basta mudar a extensão do arquivo em `Save`. O Aspose.HTML detecta automaticamente o formato a partir do caminho. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +Você também pode ajustar a qualidade da compressão via `JpegRenderingOptions`. + +### 2. Alterando as Dimensões da Imagem + +Às vezes você precisa de uma miniatura ao invés de uma captura de tela em tamanho completo. Defina `ImageSize` nas opções: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Lidando com Páginas Protegidas por Autenticação + +Se a URL de destino requer autenticação básica, forneça credenciais através de `HttpWebRequest` antes de criar o `HtmlDocument`. Alternativamente, baixe o HTML você mesmo (usando `HttpClient`) e forneça‑o como uma string: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Usando uma Fonte Personalizada + +O Aspose.HTML pode incorporar fontes locais. Registre a pasta de fontes antes de carregar o documento: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Agora, quaisquer declarações `font-family` na página serão resolvidas para seus arquivos personalizados. + +### 5. Renderizando Múltiplas Páginas em um Loop + +Se você precisar processar em lote uma lista de URLs: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Armadilhas Comuns e Como Evitá‑las + +| Sintoma | Causa Provável | Correção | +|---------|----------------|----------| +| Arquivo PNG em branco | `HtmlDocument.IsEmpty` true (a página falhou ao carregar) | Verifique a URL, verifique o proxy de rede, assegure que TLS 1.2 está habilitado. | +| Texto corrompido no Linux | Hinting de fonte desativado | Defina `renderingOptions.TextOptions.UseHinting = true;`. | +| Marca d'água na saída | Nenhuma licença fornecida | Registre uma licença temporária ou completa via `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Imagem de baixa resolução | DPI padrão 96 é insuficiente para impressão | Aumente `renderingOptions.DpiX` e `DpiY` para 150‑300. | + +--- + +## 🎉 Conclusão + +Acabamos de cobrir tudo o que você precisa para **renderizar HTML para imagem** com Aspose.HTML em C#. Desde o carregamento de uma página remota, configuração de antialiasing e **definir estilo de fonte**, até finalmente **salvar imagem renderizada** como PNG, todo o fluxo de trabalho se encaixa perfeitamente em alguns passos concisos. + +Agora você pode **converter página da web para PNG** instantaneamente, incorporar capturas de tela em relatórios ou gerar miniaturas para um catálogo — sem necessidade de automação de navegador. + +### O que vem a seguir? + +- Experimente **converter html para png** em diferentes tamanhos de tela (mobile vs desktop). +- Tente exportar para PDF usando `PdfRenderer` se precisar de um documento imprimível. +- Mergulhe nas APIs de manipulação de DOM do Aspose.HTML para injetar marcas d'água ou CSS personalizado antes da renderização. + +Tem perguntas sobre casos de borda, licenciamento ou ajuste de desempenho? Deixe um comentário abaixo, e feliz codificação! + + + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/portuguese/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/portuguese/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..821191d52 --- /dev/null +++ b/html/portuguese/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2026-03-14 +description: Renderize HTML para PNG rapidamente com Aspose.HTML. Aprenda como gerar + PNG a partir de HTML, aplicar estilo de fonte negrito itálico e salvar HTML em um + stream. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: pt +og_description: Renderizar HTML para PNG com Aspose.HTML. Este guia mostra como gerar + PNG a partir de HTML, usar estilo de fonte negrito itálico e salvar HTML em um stream. +og_title: Renderizar HTML para PNG em C# – Guia Completo de Programação +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Renderizar HTML para PNG em C# – Guia passo a passo +url: /pt/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Renderizar HTML para PNG em C# – Tutorial Completo de Programação + +Já precisou **renderizar HTML para PNG** mas não sabia qual biblioteca entregaria resultados pixel‑perfect? Você não está sozinho. Em muitas pipelines de web‑to‑image os desenvolvedores se deparam com fontes ausentes, texto borrado ou o temido “como capturo o HTML sem gravá‑lo no disco primeiro?”. + +A verdade é que o Aspose.HTML torna todo o processo muito simples. Neste tutorial vamos **gerar PNG a partir de HTML**, aplicar um **estilo de fonte negrito itálico**, e ainda **salvar HTML em um stream** para que tudo permaneça na memória. Ao final, você terá um aplicativo console pronto‑para‑executar que transforma um pequeno trecho de HTML em um PNG nítido. + +--- + +## O Que Você Precisa + +- **.NET 6+** (o código funciona tanto com .NET Core quanto com .NET Framework) +- Pacote NuGet **Aspose.HTML for .NET** – `Install-Package Aspose.HTML` +- Uma IDE de sua preferência (Visual Studio, Rider ou VS Code) – qualquer uma serve. + +Sem fontes extras, sem ferramentas externas e, definitivamente, sem arquivos temporários. Apenas C# puro. + +--- + +## Etapa 1: Criar um Documento HTML Simples + +A primeira coisa que fazemos é montar um documento HTML em memória. Pense nele como uma página web virtual que vive apenas dentro do seu processo. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Por que isso importa:** Ao construir o DOM programaticamente você evita a sobrecarga de I/O de arquivos e pode injetar dados dinâmicos em tempo real. A classe `HtmlDocument` é o ponto de entrada para toda operação do Aspose.HTML. + +--- + +## Etapa 2: Salvar HTML em um Stream + +Em vez de gravar a marcação no disco, capturamos em um `ResourceHandler` personalizado. Esta é a parte **save html to stream** do fluxo de trabalho. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Dica profissional:** O `MemoryHandler` é pequeno, mas poderoso. Se mais tarde precisar incorporar imagens, CSS ou fontes, basta estender `HandleResource` para devolver os streams apropriados. + +--- + +## Etapa 3: Configurar Estilo de Fonte Negrito Itálico + +Ao renderizar texto, você costuma querer que ele apareça exatamente como no navegador. O Aspose.HTML permite definir **bold italic font style** diretamente nas opções de renderização. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **O que está acontecendo:** +> * `UseAntialiasing` suaviza as bordas das formas. +> * `UseHinting` melhora o posicionamento dos glifos, crucial para textos pequenos. +> * `FontStyle` combina as flags `Bold` e `Italic`, de modo que todo o texto no documento herda esse estilo, a menos que seja sobrescrito. + +--- + +## Etapa 4: Renderizar o Documento HTML para uma Imagem PNG + +Agora a parte divertida – transformar o HTML em um arquivo de imagem. O `ImageRenderer` faz todo o trabalho pesado. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Se você executar o programa, verá um arquivo chamado `output.png` no diretório de trabalho. Ele contém o cabeçalho `` já temos uma estrutura HTML válida pronta para ser salva. + +> **Dica profissional:** Se você precisar de um esqueleto HTML completo (``, `
`, etc.), o Aspose.HTML o gera automaticamente ao salvar o documento, mesmo que você tenha adicionado apenas conteúdo ao body. + +## Etapa 2: Implementar um **Custom Resource Handler** – Capturar HTML na Memória + +Um *resource handler* indica ao Aspose.HTML onde gravar cada recurso (HTML, CSS, imagens, etc.). Ao sobrescrever `HandleResource` podemos direcionar a saída HTML para um `MemoryStream` em vez de um arquivo. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Por que usamos um manipulador personalizado:** +- **Desempenho:** Sem I/O de disco, tudo permanece na RAM. +- **Segurança:** Sem arquivos temporários que possam ser expostos. +- **Flexibilidade:** Você pode posteriormente encaminhar o stream para uma resposta, um banco de dados ou outra API. + +## Etapa 3: Salvar o Documento Usando o Manipulador – O Coração do **Generate HTML Programmatically** + +Agora conectamos o documento e o manipulador. Quando `htmlDoc.Save(handler)` é executado, o Aspose.HTML chama `HandleResource`, entregando‑nos o stream para gravação. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +Neste ponto `handler.HtmlStream` contém os bytes brutos do HTML. Nada foi gravado no disco, e você pode reutilizar o stream quantas vezes quiser (apenas lembre‑se de redefinir sua posição). + +## Etapa 4: Ler o HTML Gerado da Memória – Verificar a Saída + +Para provar que tudo funcionou, redefinimos a posição do stream para o início e lemos o texto de volta. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Saída esperada** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Se você vir a marcação acima, parabéns — você **generate html programmatically** com sucesso usando Aspose.HTML e um **custom resource handler**. + +## Variações Comuns e Casos de Borda + +### Manipulando CSS ou Imagens + +A demonstração ignora recursos não‑HTML retornando `Stream.Null`. Em um cenário real, você pode querer capturar arquivos CSS ou imagens também: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Reutilizando o Mesmo Manipulador para Várias Gravações + +Se precisar gerar vários trechos de HTML em um loop, crie um novo `MemoryHtmlHandler` a cada iteração ou limpe o stream existente: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Salvamento Assíncrono (Aspose.HTML 23.4+) + +Versões mais recentes suportam salvamento assíncrono: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Lembre‑se de usar `await` e tornar seu método `async`. + +## Exemplo Completo Funcional + +Abaixo está o programa completo que você pode copiar‑colar em um aplicativo de console. Ele inclui todas as partes que discutimos, além de alguns comentários para clareza. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Execute o programa (`dotnet run`) e você deverá ver o HTML impresso no console, exatamente como mostrado anteriormente. + +## Conclusão + +Acabamos de mostrar como **create HTML document C#** usando Aspose.HTML, capturar a saída com um **custom resource handler** e **generate HTML programmatically** sem tocar no sistema de arquivos. O padrão escala — seja construindo templates de e‑mail, relatórios em tempo real ou um microsserviço que retorna trechos de HTML. + +Próximos passos? Tente adicionar uma folha de estilo CSS via o manipulador, ou transmitir o HTML diretamente para uma resposta ASP.NET Core (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Você também pode conectar a saída a um conversor de PDF ou a uma biblioteca HTML‑to‑image para fluxos de trabalho mais avançados. + +Tem dúvidas sobre manipulação de imagens, salvamento assíncrono ou integração com outras bibliotecas? Deixe um comentário, e feliz codificação! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/russian/net/rendering-html-documents/_index.md b/html/russian/net/rendering-html-documents/_index.md index 80263a376..f412be082 100644 --- a/html/russian/net/rendering-html-documents/_index.md +++ b/html/russian/net/rendering-html-documents/_index.md @@ -45,6 +45,7 @@ Aspose.HTML для .NET выделяется как лучший выбор дл ### [Как отрендерить HTML в PNG – Полное руководство C#](./how-to-render-html-as-png-complete-c-guide/) Полное руководство по рендерингу HTML в PNG с использованием Aspose.HTML и C#. + ### [Создание PNG из HTML – Полное руководство по рендерингу на C#](./create-png-from-html-full-c-rendering-guide/) Подробный учебник по созданию PNG из HTML с использованием Aspose.HTML для .NET на C#. @@ -62,11 +63,19 @@ Aspose.HTML для .NET выделяется как лучший выбор дл ### [Рендеринг SVG Doc как PNG в .NET с помощью Aspose.HTML](./render-svg-doc-as-png/) Откройте для себя мощь Aspose.HTML для .NET! Узнайте, как легко визуализировать SVG Doc как PNG. Погрузитесь в пошаговые примеры и часто задаваемые вопросы. Начните прямо сейчас! + ### [Как использовать Aspose для рендеринга HTML в PNG – пошаговое руководство](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) Подробный пошаговый учебник по использованию Aspose.HTML для конвертации HTML в PNG в .NET. + ### [Как отрендерить HTML в PNG с помощью Aspose – Полное руководство](./how-to-render-html-to-png-with-aspose-complete-guide/) Подробный пошаговый учебник по рендерингу HTML в PNG с использованием Aspose.HTML для .NET. +### [Рендеринг HTML в изображение на C# – Полное пошаговое руководство](./render-html-to-image-in-c-complete-step-by-step-guide/) +Подробный пошаговый учебник по рендерингу HTML в изображения с помощью Aspose.HTML на C#. + +### [Рендеринг HTML в PNG на C# – Пошаговое руководство](./render-html-to-png-in-c-step-by-step-guide/) +Подробный пошаговый учебник по рендерингу HTML в PNG с использованием Aspose.HTML на C#. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/russian/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/russian/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3af2bb779 --- /dev/null +++ b/html/russian/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,299 @@ +--- +category: general +date: 2026-03-14 +description: Быстро преобразуйте HTML в изображение с помощью Aspose.HTML. Узнайте, + как конвертировать веб‑страницу в PNG, задать стиль шрифта и сохранить отрендеренное + изображение всего в несколько строк кода C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: ru +og_description: Отображайте HTML в изображение с помощью Aspose.HTML. В этом руководстве + показано, как преобразовать веб‑страницу в PNG, установить стиль шрифта и сохранить + отрендеренное изображение в C#. +og_title: Отображение HTML в изображение на C# – Быстрое и простое руководство +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Рендеринг HTML в изображение на C# – Полное пошаговое руководство +url: /ru/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +4 etc. All present. + +Check headings: we kept same number of #. + +Check tables: we translated content but kept pipes. + +Check blockquote formatting: we kept >. + +Check bullet list: we used dash. + +Check emojis: 🎉 kept. + +Now produce final content.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Отображение HTML в изображение – Полный учебник C# + +Когда‑нибудь вам нужно было **render HTML to image**, но вы не знали, какую библиотеку выбрать? Вы не одиноки. Во многих сценариях веб‑автоматизации или создания отчетов вы получаете живую страницу, которую хотите сохранить как PNG, JPEG или даже BMP. Хорошая новость в том, что Aspose.HTML делает это проще простого, позволяя **convert webpage to PNG** всего несколькими строками кода. + +В этом руководстве мы пройдем весь процесс: от установки пакета Aspose.HTML, загрузки удаленного URL, настройки параметров рендеринга (включая то, как **set font style**), и, наконец, **save rendered image** на диск. К концу у вас будет готовое к запуску консольное приложение, которое создает четкий скриншот любой веб‑страницы. + +## Что понадобится + +Прежде чем мы начнём, убедитесь, что у вас есть: + +| Prerequisite | Reason | +|--------------|--------| +| .NET 6.0 SDK или новее | Aspose.HTML ориентирован на .NET Standard 2.0+, поэтому .NET 6 предоставляет вам самую свежую среду выполнения. | +| Visual Studio 2022 (или VS Code) | Удобная IDE ускоряет отладку. | +| NuGet‑пакет Aspose.HTML for .NET | Это движок, который выполняет основную работу. | +| Действительная лицензия Aspose.HTML (опционально) | Без лицензии на выходном изображении будет водяной знак. | + +Вы можете получить пакет через CLI: + +```bash +dotnet add package Aspose.HTML +``` + +Если вы предпочитаете GUI, просто найдите “Aspose.HTML” в NuGet Package Manager. + +--- + +## Шаг 1: Загрузите веб‑страницу, которую хотите растрировать + +Первое, что нужно сделать, — предоставить Aspose.HTML исходный документ. Это может быть локальный файл, строка или удалённый URL. В большинстве реальных сценариев вы будете работать с живым сайтом, поэтому давайте **convert webpage to PNG**, указав `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Почему это важно:** Загрузка страницы как `HtmlDocument` даёт вам полный доступ к DOM, что означает возможность внедрять CSS, изменять макет или даже выполнять JavaScript перед растрированием. + +--- + +## Шаг 2: Настройте параметры рендеринга изображения + +Теперь, когда HTML находится в памяти, нам нужно сообщить рендереру, как должна выглядеть конечная картинка. Здесь вы можете **set font style**, включить сглаживание или настроить DPI. Ниже представлена надёжная конфигурация по умолчанию, которая балансирует качество и скорость. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Совет:** Если вам нужен только обычный вес, уберите флаги `WebFontStyle`. Для заголовков может потребоваться только `WebFontStyle.Bold`, а для подписей — `WebFontStyle.Italic`. + +--- + +## Шаг 3: Отрендерите страницу и **Save Rendered Image** как PNG + +Имея документ и параметры, последний шаг — создать экземпляр `ImageRenderer` и записать файл вывода. Блок `using` гарантирует своевременное освобождение ресурсов. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +Когда вы запустите программу, в папке проекта появится файл `page.png`, содержащий точную копию *example.com*. Откройте его в любом просмотрщике изображений, и вы заметите жирно‑курсивное оформление, которое мы запросили ранее. + +### Ожидаемый результат + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +PNG будет примерно 800 × 600 px (в зависимости от оригинальных размеров страницы) с плавными краями благодаря сглаживанию. + +--- + +## Полный рабочий пример + +Объединив всё вместе, представляем минимальное консольное приложение, которое вы можете скопировать‑вставить в `Program.cs`. Оно компилируется и запускается сразу. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Запустите его с помощью: + +```bash +dotnet run +``` + +…и у вас будет свежий PNG, готовый к архивированию, отправке по email или встраиванию в отчёт. + +--- + +## Вариации и особые случаи + +### 1. Конвертация в JPEG вместо PNG + +Если ваша downstream‑система предпочитает JPEG (меньший размер файла, сжатие с потерями), просто измените расширение файла в `Save`. Aspose.HTML автоматически определит формат по пути. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +Вы также можете настроить качество сжатия через `JpegRenderingOptions`. + +### 2. Изменение размеров изображения + +Иногда нужен миниатюрный снимок вместо полноразмерного скриншота. Установите `ImageSize` в параметрах: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Обработка страниц, защищённых аутентификацией + +Если целевой URL требует базовой аутентификации, передайте учетные данные через `HttpWebRequest` до создания `HtmlDocument`. Либо загрузите HTML самостоятельно (используя `HttpClient`) и передайте его как строку: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Использование пользовательского шрифта + +Aspose.HTML может встраивать локальные шрифты. Зарегистрируйте папку со шрифтами перед загрузкой документа: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Теперь любые объявления `font-family` на странице будут разрешаться к вашим пользовательским файлам. + +### 5. Рендеринг нескольких страниц в цикле + +Если нужно пакетно обработать список URL: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Распространённые ошибки и как их избежать + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Пустой PNG‑файл | `HtmlDocument.IsEmpty` true (страница не загрузилась) | Проверьте URL, проверьте сетевой прокси, убедитесь, что включён TLS 1.2. | +| Искажённый текст в Linux | Подсказки шрифтов отключены | Установите `renderingOptions.TextOptions.UseHinting = true;`. | +| Водяной знак на выводе | Лицензия не предоставлена | Зарегистрируйте временную или полную лицензию через `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Изображение низкого разрешения | DPI по умолчанию 96 недостаточно для печати | Увеличьте `renderingOptions.DpiX` и `DpiY` до 150‑300. | + +--- + +## 🎉 Заключение + +Мы только что рассмотрели всё, что нужно для **render HTML to image** с помощью Aspose.HTML в C#. От загрузки удалённой страницы, настройки сглаживания и **set font style**, до окончательного **save rendered image** в PNG, весь процесс удобно укладывается в несколько коротких шагов. + +Теперь вы можете **convert webpage to PNG** «на лету», встраивать скриншоты в отчёты или генерировать миниатюры для каталога — без необходимости автоматизации браузера. + +### Что дальше? + +- Поэкспериментировать с **convert html to png** для разных размеров экрана (мобильный vs настольный). +- Попробовать экспорт в PDF с помощью `PdfRenderer`, если нужен печатный документ. +- Погрузиться в API манипуляции DOM Aspose.HTML, чтобы внедрять водяные знаки или пользовательский CSS перед рендерингом. + +Есть вопросы о особых случаях, лицензировании или настройке производительности? Оставьте комментарий ниже, и удачной разработки! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/russian/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..2f7ef455e --- /dev/null +++ b/html/russian/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2026-03-14 +description: Быстро преобразуйте HTML в PNG с помощью Aspose.HTML. Узнайте, как генерировать + PNG из HTML, применять полужирный и курсивный стиль шрифта и сохранять HTML в поток. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: ru +og_description: Рендеринг HTML в PNG с помощью Aspose.HTML. Это руководство показывает, + как генерировать PNG из HTML, использовать жирный курсивный стиль шрифта и сохранять + HTML в поток. +og_title: Рендер HTML в PNG на C# – Полное пошаговое руководство +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Рендеринг HTML в PNG на C# – пошаговое руководство +url: /ru/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Преобразование HTML в PNG на C# – Полный программный обзор + +Когда‑то вам нужно было **преобразовать HTML в PNG**, но вы не знали, какая библиотека даст пиксель‑идеальный результат? Вы не одиноки. Во многих конвейерах «web‑to‑image» разработчики сталкиваются с отсутствием шрифтов, размытым текстом или страшным вопросом «как захватить HTML, не записывая его на диск сначала?» + +Дело в том, что Aspose.HTML делает весь процесс простым, как пирог. В этом руководстве мы **создадим PNG из HTML**, применим **жирный курсивный стиль шрифта** и даже **сохраним HTML в поток**, чтобы всё оставалось в памяти. К концу вы получите готовое к запуску консольное приложение, которое превратит небольшой фрагмент HTML в чёткий PNG‑файл. + +--- + +## Что понадобится + +- **.NET 6+** (код работает как с .NET Core, так и с .NET Framework) +- **Aspose.HTML for .NET** пакет NuGet – `Install-Package Aspose.HTML` +- Любая любимая IDE (Visual Studio, Rider или VS Code) – подойдёт любая. + +Никаких дополнительных шрифтов, внешних инструментов и, конечно же, временных файлов. Чистый C#. + +--- + +## Шаг 1: Создать простой HTML‑документ + +Первое, что мы делаем, – создаём HTML‑документ в памяти. Представьте его как виртуальную веб‑страницу, существующую только внутри вашего процесса. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Почему это важно:** Создавая DOM программно, вы избегаете накладных расходов ввода‑вывода файлов и можете динамически внедрять данные «на лету». Класс `HtmlDocument` является точкой входа для любой операции Aspose.HTML. + +--- + +## Шаг 2: Сохранить HTML в поток + +Вместо записи разметки на диск мы захватываем её в пользовательском `ResourceHandler`. Это часть рабочего процесса **save html to stream**. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Совет:** `MemoryHandler` небольшой, но мощный. Если позже понадобится внедрить изображения, CSS или шрифты, просто расширьте `HandleResource`, чтобы возвращать соответствующие потоки. + +--- + +## Шаг 3: Настроить жирный курсивный стиль шрифта + +При рендеринге текста часто требуется, чтобы он выглядел точно так же, как в браузере. Aspose.HTML позволяет задать **bold italic font style** напрямую в параметрах рендеринга. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **Что происходит:** +> * `UseAntialiasing` сглаживает края фигур. +> * `UseHinting` улучшает позиционирование глифов, что критично для мелкого текста. +> * `FontStyle` объединяет флаги `Bold` и `Italic`, поэтому каждый фрагмент текста в документе наследует этот стиль, если не переопределён. + +--- + +## Шаг 4: Преобразовать HTML‑документ в PNG‑изображение + +Теперь самая интересная часть – превратить HTML в файл‑изображение. За всё тяжёлое дело отвечает `ImageRenderer`. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Если запустить программу, вы увидите файл `output.png` в рабочем каталоге. В нём будет заголовок ``, мы уже получаем корректную HTML‑структуру, готовую к сохранению. + +> **Pro tip:** Если вам нужен полный скелет HTML (``, `
` и т.д.), Aspose.HTML автоматически генерирует его при сохранении документа, даже если вы добавили только содержимое тела. + +## Шаг 2: Реализация **Custom Resource Handler** – Захват HTML в памяти + +*Обработчик ресурсов* указывает Aspose.HTML, куда записывать каждый ресурс (HTML, CSS, изображения и т.п.). Переопределив `HandleResource`, мы можем направить вывод HTML в `MemoryStream` вместо файла. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Почему мы используем пользовательский обработчик:** +- **Производительность:** Нет ввода‑вывода на диск, всё остаётся в ОЗУ. +- **Безопасность:** Нет временных файлов, которые могут быть раскрыты. +- **Гибкость:** Позже вы можете передать поток в ответ, в базу данных или в другой API. + +## Шаг 3: Сохранение документа с помощью обработчика – Сердце **Generate HTML Programmatically** + +Теперь связываем документ и обработчик. Когда вызывается `htmlDoc.Save(handler)`, Aspose.HTML вызывает `HandleResource`, передавая нам поток для записи. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +На этом этапе `handler.HtmlStream` содержит необработанные байты HTML. На диск ничего не записано, и вы можете переиспользовать поток сколько угодно (только не забудьте сбросить его позицию). + +## Шаг 4: Чтение сгенерированного HTML из памяти – Проверка вывода + +Чтобы убедиться, что всё работает, сбрасываем позицию потока в начало и читаем текст обратно. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Ожидаемый вывод** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Если вы видите разметку выше, поздравляем — вы успешно **generate html programmatically** с помощью Aspose.HTML и **custom resource handler**. + +## Распространённые варианты и граничные случаи + +### Обработка CSS или изображений + +Демонстрация игнорирует не‑HTML ресурсы, возвращая `Stream.Null`. В реальном проекте вы, вероятно, захотите также захватывать CSS‑файлы или изображения: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Переиспользование одного обработчика для нескольких сохранений + +Если нужно генерировать несколько HTML‑фрагментов в цикле, создавайте новый `MemoryHtmlHandler` на каждой итерации или очищайте существующий поток: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Асинхронное сохранение (Aspose.HTML 23.4+) + +Новые версии поддерживают асинхронное сохранение: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Не забудьте использовать `await` и объявить ваш метод как `async`. + +## Полный рабочий пример + +Ниже приведена полная программа, которую можно скопировать‑вставить в консольное приложение. В ней собраны все обсуждаемые части и несколько комментариев для ясности. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Запустите программу (`dotnet run`), и вы увидите HTML, выведенный в консоль, точно так же, как показано ранее. + +## Заключение + +Мы только что продемонстрировали, как **create HTML document C#** с помощью Aspose.HTML, захватить вывод через **custom resource handler** и **generate HTML programmatically** без обращения к файловой системе. Этот подход масштабируется — будь то шаблоны писем, отчёты «на лету» или микросервис, возвращающий HTML‑фрагменты. + +Что дальше? Попробуйте добавить CSS‑стили через обработчик или напрямую передать HTML в ответ ASP.NET Core (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Вы также можете передать вывод в конвертер PDF или библиотеку преобразования HTML в изображение для более сложных сценариев. + +Есть вопросы по работе с изображениями, асинхронному сохранению или интеграции с другими библиотеками? Оставляйте комментарий, и happy coding! + +{{< /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/rendering-html-documents/_index.md b/html/spanish/net/rendering-html-documents/_index.md index aa3ec875b..b6d49f3f7 100644 --- a/html/spanish/net/rendering-html-documents/_index.md +++ b/html/spanish/net/rendering-html-documents/_index.md @@ -58,8 +58,12 @@ Aprenda a representar múltiples documentos HTML con Aspose.HTML para .NET. Aume ¡Descubra el poder de Aspose.HTML para .NET! Aprenda a convertir documentos SVG en PNG sin esfuerzo. Conozca ejemplos paso a paso y preguntas frecuentes. ¡Comience ahora! ### [Cómo renderizar HTML como PNG con Aspose.HTML – Guía completa en C#](./how-to-render-html-as-png-complete-c-guide/) Aprenda paso a paso a convertir HTML a PNG usando C# y Aspose.HTML. Guía completa con ejemplos claros. +### [Renderizar HTML a PNG en C# – Guía paso a paso](./render-html-to-png-in-c-step-by-step-guide/) +Aprenda paso a paso a convertir HTML a PNG usando C# y Aspose.HTML. Guía completa con ejemplos claros. ### [Cómo renderizar HTML a PNG con Aspose – Guía completa](./how-to-render-html-to-png-with-aspose-complete-guide/) Aprenda a convertir HTML a PNG usando Aspose.HTML para .NET con esta guía completa paso a paso. +### [Renderizar HTML a Imagen en C# – Guía Completa Paso a Paso](./render-html-to-image-in-c-complete-step-by-step-guide/) +Aprenda paso a paso a convertir HTML a imágenes usando C# y Aspose.HTML. Guía completa con ejemplos claros. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/spanish/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/spanish/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..ef8161133 --- /dev/null +++ b/html/spanish/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-03-14 +description: Render HTML a imagen rápidamente usando Aspose.HTML. Aprende cómo convertir + una página web a PNG, establecer el estilo de fuente y guardar la imagen renderizada + en solo unas pocas líneas de C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: es +og_description: Renderiza HTML a imagen con Aspose.HTML. Este tutorial muestra cómo + convertir una página web a PNG, establecer el estilo de fuente y guardar la imagen + renderizada en C#. +og_title: Renderizar HTML a Imagen en C# – Guía Rápida y Fácil +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Renderizar HTML a Imagen en C# – Guía Completa Paso a Paso +url: /es/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Renderizar HTML a Imagen – Tutorial Completo en C# + +¿Alguna vez necesitaste **renderizar HTML a imagen** pero no estabas seguro de qué biblioteca elegir? No eres el único. En muchos escenarios de automatización web o generación de informes terminas con una página en vivo que deseas archivar como PNG, JPEG o incluso BMP. La buena noticia es que Aspose.HTML lo hace muy sencillo, permitiéndote **convertir página web a PNG** con solo unas pocas líneas de código. + +En esta guía recorreremos todo el proceso: desde la instalación del paquete Aspose.HTML, la carga de una URL remota, la configuración de opciones de renderizado (incluido cómo **establecer estilo de fuente**), y finalmente **guardar la imagen renderizada** en disco. Al final tendrás una aplicación de consola lista para ejecutarse que produce una captura nítida de cualquier página web. + +## Lo que Necesitarás + +Antes de comenzar, asegúrate de contar con: + +| Prerrequisito | Motivo | +|--------------|--------| +| .NET 6.0 SDK o posterior | Aspose.HTML apunta a .NET Standard 2.0+, así que .NET 6 te brinda el runtime más reciente. | +| Visual Studio 2022 (o VS Code) | Un IDE cómodo acelera la depuración. | +| Paquete NuGet Aspose.HTML for .NET | Este es el motor que realiza el trabajo pesado. | +| Una licencia válida de Aspose.HTML (opcional) | Sin licencia obtendrás una marca de agua en la imagen de salida. | + +Puedes obtener el paquete mediante la CLI: + +```bash +dotnet add package Aspose.HTML +``` + +Si prefieres la interfaz gráfica, simplemente busca “Aspose.HTML” en el Administrador de paquetes NuGet. + +--- + +## Paso 1: Cargar la Página Web que Deseas Rasterizar + +Lo primero que debes hacer es proporcionar a Aspose.HTML un documento fuente. Puede ser un archivo local, una cadena o una URL remota. En la mayoría de los casos reales trabajarás con un sitio en vivo, así que **convertiremos página web a PNG** apuntando a `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Por qué es importante:** Cargar la página como un `HtmlDocument` te brinda acceso total al DOM, lo que significa que puedes inyectar CSS, manipular el diseño o incluso ejecutar JavaScript antes de rasterizar. + +--- + +## Paso 2: Configurar Opciones de Renderizado de Imagen + +Ahora que el HTML está en memoria, debemos indicarle al renderizador cómo queremos que sea la imagen final. Aquí es donde puedes **establecer estilo de fuente**, habilitar antialiasing o ajustar el DPI. A continuación se muestra una configuración predeterminada sólida que equilibra calidad y velocidad. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Consejo profesional:** Si solo necesitas un peso regular, elimina las banderas `WebFontStyle`. Para encabezados podrías usar solo `WebFontStyle.Bold`, mientras que para subtítulos podrías usar `WebFontStyle.Italic`. + +--- + +## Paso 3: Renderizar la Página y **Guardar Imagen Renderizada** como PNG + +Con el documento y las opciones listos, el paso final es instanciar `ImageRenderer` y escribir el archivo de salida. El bloque `using` garantiza que los recursos se liberen rápidamente. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +Al ejecutar el programa, deberías ver un archivo `page.png` en la carpeta de tu proyecto que contiene una captura fiel de *example.com*. Ábrelo con cualquier visor de imágenes y notarás el estilo negrita‑cursiva que solicitamos anteriormente. + +### Resultado Esperado + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +El PNG tendrá aproximadamente 800 × 600 px (según las dimensiones originales de la página) con bordes suaves gracias al antialiasing. + +--- + +## Ejemplo Completo Funcional + +Juntando todo, aquí tienes una aplicación de consola mínima que puedes copiar‑pegar en `Program.cs`. Compila y se ejecuta sin necesidad de ajustes adicionales. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Ejecuta con: + +```bash +dotnet run +``` + +…y tendrás un PNG recién creado listo para archivar, enviar por correo o incrustar en un informe. + +--- + +## Variaciones y Casos Especiales + +### 1. Convertir a JPEG en Lugar de PNG + +Si tu sistema downstream prefiere JPEG (tamaño de archivo menor, compresión con pérdida), simplemente cambia la extensión del archivo en `Save`. Aspose.HTML detecta automáticamente el formato a partir de la ruta. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +También puedes ajustar la calidad de compresión mediante `JpegRenderingOptions`. + +### 2. Cambiar las Dimensiones de la Imagen + +A veces necesitas una miniatura en lugar de una captura a pantalla completa. Establece `ImageSize` en las opciones: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Manejar Páginas con Autenticación + +Si la URL objetivo requiere autenticación básica, suministra credenciales a través de `HttpWebRequest` antes de crear el `HtmlDocument`. Alternativamente, descarga el HTML tú mismo (usando `HttpClient`) y pásalo como cadena: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Usar una Fuente Personalizada + +Aspose.HTML puede incrustar fuentes locales. Registra la carpeta de fuentes antes de cargar el documento: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Ahora cualquier declaración `font-family` en la página se resolverá a tus archivos personalizados. + +### 5. Renderizar Múltiples Páginas en un Bucle + +Si necesitas procesar en lote una lista de URLs: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Errores Comunes y Cómo Evitarlos + +| Síntoma | Causa Probable | Solución | +|---------|----------------|----------| +| Archivo PNG en blanco | `HtmlDocument.IsEmpty` es true (la página no se cargó) | Verifica la URL, revisa el proxy de red, asegura que TLS 1.2 esté habilitado. | +| Texto distorsionado en Linux | Hinting de fuente deshabilitado | Establece `renderingOptions.TextOptions.UseHinting = true;`. | +| Marca de agua en la salida | No se proporcionó licencia | Registra una licencia temporal o completa mediante `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Imagen de baja resolución | DPI predeterminado 96 es insuficiente para impresión | Incrementa `renderingOptions.DpiX` y `DpiY` a 150‑300. | + +--- + +## 🎉 Conclusión + +Acabamos de cubrir todo lo que necesitas para **renderizar HTML a imagen** con Aspose.HTML en C#. Desde cargar una página remota, configurar antialiasing y **establecer estilo de fuente**, hasta finalmente **guardar la imagen renderizada** como PNG, todo el flujo de trabajo cabe en unos pocos pasos concisos. + +Ahora puedes **convertir página web a PNG** al vuelo, incrustar capturas en informes o generar miniaturas para un catálogo—sin necesidad de automatizar un navegador. + +### ¿Qué Sigue? + +- Experimenta con **convertir html a png** para diferentes tamaños de pantalla (móvil vs escritorio). +- Prueba exportar a PDF usando `PdfRenderer` si necesitas un documento imprimible. +- Sumérgete en las APIs de manipulación del DOM de Aspose.HTML para inyectar marcas de agua o CSS personalizado antes del renderizado. + +¿Tienes preguntas sobre casos especiales, licencias o afinación de rendimiento? Deja un comentario abajo, ¡y feliz codificación! + +--- + + + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/spanish/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/spanish/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..b64064725 --- /dev/null +++ b/html/spanish/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-03-14 +description: Renderiza HTML a PNG rápidamente con Aspose.HTML. Aprende cómo generar + PNG a partir de HTML, aplicar estilo de fuente en negrita y cursiva, y guardar HTML + en un flujo. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: es +og_description: Renderizar HTML a PNG con Aspose.HTML. Esta guía muestra cómo generar + PNG a partir de HTML, usar estilo de fuente negrita cursiva y guardar HTML en un + flujo. +og_title: Renderizar HTML a PNG en C# – Guía completa de programación +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Renderizar HTML a PNG en C# – Guía paso a paso +url: /es/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +límite". + +"Recap" translate to "Resumen". + +"What’s Next?" translate to "¿Qué sigue?". + +Also bullet lists. + +Make sure to keep markdown formatting. + +Now produce final content.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG in C# – Complete Programming Walkthrough + +¿Alguna vez necesitaste **renderizar HTML a PNG** pero no estabas seguro de qué biblioteca te daría resultados píxel‑perfectos? No estás solo. En muchos flujos de trabajo web‑to‑image los desarrolladores se tropiezan con fuentes faltantes, texto borroso o la temida pregunta “¿cómo capturo el HTML sin escribirlo en disco primero?”. + +La cuestión es que Aspose.HTML hace que todo el proceso sea pan comido. En este tutorial **generaremos PNG a partir de HTML**, aplicaremos un **estilo de fuente negrita cursiva**, e incluso **guardaremos HTML en un stream** para que todo permanezca en memoria. Al final tendrás una aplicación de consola lista para ejecutar que convierte un pequeño fragmento de HTML en un archivo PNG nítido. + +--- + +## What You’ll Need + +- **.NET 6+** (el código funciona tanto con .NET Core como con .NET Framework) +- **Aspose.HTML for .NET** paquete NuGet – `Install-Package Aspose.HTML` +- Un IDE favorito (Visual Studio, Rider o VS Code) – cualquiera sirve. + +Sin fuentes extra, sin herramientas externas y, definitivamente, sin archivos temporales. Solo puro C#. + +--- + +## Step 1: Create a Simple HTML Document + +Lo primero que hacemos es construir un documento HTML en memoria. Piensa en él como una página web virtual que solo vive dentro de tu proceso. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Por qué esto importa:** Al construir el DOM programáticamente evitas la sobrecarga de I/O de archivos y puedes inyectar datos dinámicos al vuelo. La clase `HtmlDocument` es el punto de entrada para cada operación de Aspose.HTML. + +--- + +## Step 2: Save HTML to a Stream + +En lugar de escribir el marcado en disco, lo capturamos en un `ResourceHandler` personalizado. Esta es la parte de **save html to stream** del flujo de trabajo. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Consejo:** El `MemoryHandler` es pequeño pero potente. Si más adelante necesitas incrustar imágenes, CSS o fuentes, simplemente extiende `HandleResource` para devolver los streams correspondientes. + +--- + +## Step 3: Configure Bold Italic Font Style + +Cuando renderizas texto, a menudo quieres que se vea exactamente como en un navegador. Aspose.HTML te permite establecer **bold italic font style** directamente en las opciones de renderizado. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **Qué está sucediendo:** +> * `UseAntialiasing` suaviza los bordes de las formas. +> * `UseHinting` mejora la posición de los glifos, lo cual es crucial para texto pequeño. +> * `FontStyle` combina las banderas `Bold` e `Italic`, de modo que cada pieza de texto en el documento hereda ese estilo a menos que se sobrescriba. + +--- + +## Step 4: Render the HTML Document to a PNG Image + +Ahora la parte divertida: convertir ese HTML en un archivo de imagen. El `ImageRenderer` hace todo el trabajo pesado. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Si ejecutas el programa, verás un archivo llamado `output.png` en el directorio de trabajo. Contiene el encabezado `` ya dispones de una estructura HTML válida lista para guardarse. + +> **Consejo profesional:** Si necesitas un esqueleto HTML completo (``, `
`, etc.), Aspose.HTML lo genera automáticamente al guardar el documento, incluso si solo añadiste contenido al cuerpo. + +## Paso 2: Implementar un **Controlador de recursos personalizado** – Capturar HTML en memoria + +Un *controlador de recursos* indica a Aspose.HTML dónde escribir cada recurso (HTML, CSS, imágenes, etc.). Al sobrescribir `HandleResource` podemos dirigir la salida HTML a un `MemoryStream` en lugar de a un archivo. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Por qué usamos un controlador personalizado:** +- **Rendimiento:** Sin I/O de disco, todo permanece en RAM. +- **Seguridad:** No hay archivos temporales que puedan exponerse. +- **Flexibilidad:** Luego puedes canalizar el stream a una respuesta, una base de datos o otra API. + +## Paso 3: Guardar el documento usando el controlador – El corazón de **Generar HTML programáticamente** + +Ahora vinculamos el documento y el controlador. Cuando se ejecuta `htmlDoc.Save(handler)`, Aspose.HTML llama a `HandleResource`, entregándonos el stream donde escribir. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +En este punto `handler.HtmlStream` contiene los bytes crudos del HTML. No se ha escrito nada en disco y puedes reutilizar el stream tantas veces como necesites (solo recuerda restablecer su posición). + +## Paso 4: Leer el HTML generado desde la memoria – Verificar la salida + +Para demostrar que todo funcionó, restablecemos la posición del stream al inicio y leemos el texto de nuevo. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Salida esperada** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Si ves el marcado anterior, felicidades —has **generado HTML programáticamente** usando Aspose.HTML y un **controlador de recursos personalizado**. + +## Variaciones comunes y casos límite + +### Manejo de CSS o imágenes + +El ejemplo ignora los recursos que no son HTML devolviendo `Stream.Null`. En un escenario real podrías querer capturar también archivos CSS o imágenes: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Reutilizar el mismo controlador para múltiples guardados + +Si necesitas generar varios fragmentos HTML en un bucle, crea un nuevo `MemoryHtmlHandler` en cada iteración o limpia el stream existente: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Guardado asíncrono (Aspose.HTML 23.4+) + +Las versiones más recientes admiten guardado asíncrono: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Recuerda usar `await` y declarar tu método como `async`. + +## Ejemplo completo funcionando + +A continuación tienes el programa completo que puedes copiar y pegar en una aplicación de consola. Incluye todas las piezas que discutimos, más algunos comentarios para mayor claridad. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Ejecuta el programa (`dotnet run`) y deberías ver el HTML impreso en la consola, exactamente como se mostró antes. + +## Conclusión + +Acabamos de mostrar cómo **crear documento HTML C#** usando Aspose.HTML, capturar la salida con un **controlador de recursos personalizado**, y **generar HTML programáticamente** sin tocar el sistema de archivos. El patrón escala —ya sea que estés construyendo plantillas de correo electrónico, informes bajo demanda o un microservicio que devuelve fragmentos HTML. + +¿Próximos pasos? Prueba agregar una hoja de estilo CSS mediante el controlador, o transmite el HTML directamente a una respuesta de ASP.NET Core (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). También podrías conectar la salida a un convertidor a PDF o a una biblioteca HTML‑a‑imagen para flujos de trabajo más ricos. + +¿Tienes preguntas sobre el manejo de imágenes, guardado asíncrono o integración con otras librerías? Deja un comentario, ¡y feliz codificación! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/swedish/net/rendering-html-documents/_index.md b/html/swedish/net/rendering-html-documents/_index.md index 72cae28c3..6f633d2e3 100644 --- a/html/swedish/net/rendering-html-documents/_index.md +++ b/html/swedish/net/rendering-html-documents/_index.md @@ -60,6 +60,10 @@ Lås upp kraften i Aspose.HTML för .NET! Lär dig hur du renderar SVG-dokument Lär dig hur du med Aspose.HTML för .NET konverterar HTML till PNG i en detaljerad steg‑för‑steg‑handledning. ### [Hur man renderar HTML till PNG med Aspose – Komplett guide](./how-to-render-html-to-png-with-aspose-complete-guide/) Lär dig hur du med Aspose.HTML för .NET konverterar HTML till PNG i en komplett guide. +### [Rendera HTML till bild i C# – Komplett steg‑för‑steg‑guide](./render-html-to-image-in-c-complete-step-by-step-guide/) +Lär dig hur du med Aspose.HTML för .NET konverterar HTML till bild i en komplett steg‑för‑steg‑guide. +### [Rendera HTML till PNG i C# – Steg‑för‑steg‑guide](./render-html-to-png-in-c-step-by-step-guide/) +Lär dig hur du med Aspose.HTML för .NET konverterar HTML till PNG i en komplett steg‑för‑steg‑guide. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/swedish/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/swedish/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..02b522e54 --- /dev/null +++ b/html/swedish/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-03-14 +description: Rendera HTML till bild snabbt med Aspose.HTML. Lär dig hur du konverterar + en webbsida till PNG, ställer in teckensnittsstil och sparar den renderade bilden + med bara några rader C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: sv +og_description: Rendera HTML till bild med Aspose.HTML. Den här handledningen visar + hur du konverterar en webbsida till PNG, ställer in teckensnittsstil och sparar + den renderade bilden i C#. +og_title: Rendera HTML till bild i C# – Snabb och enkel guide +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Rendera HTML till bild i C# – Komplett steg‑för‑steg‑guide +url: /sv/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Rendera HTML till Bild – Komplett C#-handledning + +Har du någonsin behövt **rendera HTML till bild** men varit osäker på vilket bibliotek du ska välja? Du är inte ensam. I många webb‑automatiserings- eller rapporteringsscenarier får du en live‑sida som du vill arkivera som PNG, JPEG eller till och med BMP. Den goda nyheten är att Aspose.HTML gör detta enkelt, så att du kan **konvertera webbsida till PNG** med bara några rader kod. + +I den här guiden går vi igenom hela processen: från att installera Aspose.HTML‑paketet, ladda en fjärr‑URL, justera renderingsalternativ (inklusive hur man **ställer in teckensnittsstil**), och slutligen **sparar renderad bild** till disk. När du är klar har du en färdig‑att‑köra konsolapp som producerar en skarp skärmdump av vilken webbsida som helst. + +## Vad du behöver + +| Prerequisite | Reason | +|--------------|--------| +| .NET 6.0 SDK or later | Aspose.HTML riktar sig mot .NET Standard 2.0+, så .NET 6 ger dig den senaste runtime‑miljön. | +| Visual Studio 2022 (or VS Code) | En bekväm IDE snabbar upp felsökning. | +| Aspose.HTML for .NET NuGet package | Detta är motorn som utför det tunga arbetet. | +| A valid Aspose.HTML license (optional) | Utan en licens får du ett vattenstämpel på den genererade bilden. | + +Du kan hämta paketet via CLI: + +```bash +dotnet add package Aspose.HTML +``` + +Om du föredrar GUI, sök bara efter “Aspose.HTML” i NuGet Package Manager. + +--- + +## Steg 1: Ladda webbsidan du vill rasterisera + +Det första du måste göra är att ge Aspose.HTML ett källdokument. Det kan vara en lokal fil, en sträng eller en fjärr‑URL. I de flesta verkliga scenarier arbetar du med en live‑sida, så låt oss **konvertera webbsida till PNG** genom att peka på `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Varför detta är viktigt:** Att ladda sidan som ett `HtmlDocument` ger dig full åtkomst till DOM, vilket betyder att du kan injicera CSS, manipulera layouten eller till och med köra JavaScript innan rasterisering. + +--- + +## Steg 2: Konfigurera bildrenderingsalternativ + +Nu när HTML är i minnet måste vi tala om för renderaren hur vi vill att den slutgiltiga bilden ska se ut. Här kan du **ställa in teckensnittsstil**, aktivera kantutjämning eller justera DPI. Nedan är en solid standardkonfiguration som balanserar kvalitet och hastighet. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Proffstips:** Om du bara behöver en normal vikt, släpp `WebFontStyle`‑flaggorna. För rubriker kan du vilja ha bara `WebFontStyle.Bold`, medan bildtexter kan använda `WebFontStyle.Italic`. + +--- + +## Steg 3: Rendera sidan och **spara renderad bild** som PNG + +Med dokumentet och alternativen klara är sista steget att instansiera `ImageRenderer` och skriva utdatafilen. `using`‑blocket säkerställer att resurser frigörs snabbt. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +När du kör programmet bör du se en `page.png`‑fil i din projektmapp som innehåller en trogen avbildning av *example.com*. Öppna den med någon bildvisare så märker du den fet‑kursiva stil vi begärde tidigare. + +### Förväntad utdata + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +PNG‑filen kommer att vara ungefär 800 × 600 px (beroende på sidans ursprungliga dimensioner) med mjuka kanter tack vare kantutjämning. + +--- + +## Fullt fungerande exempel + +När vi sätter ihop allt, här är en minimal konsolapp som du kan kopiera‑klistra in i `Program.cs`. Den kompilerar och körs direkt. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Kör den med: + +```bash +dotnet run +``` + +…och du får en ny PNG klar för arkivering, e‑post eller inbäddning i en rapport. + +--- + +## Variationer & kantfall + +### 1. Konvertera till JPEG istället för PNG + +Om ditt efterföljande system föredrar JPEG (mindre filstorlek, förlustkomprimering), ändra bara filändelsen i `Save`. Aspose.HTML upptäcker automatiskt formatet från sökvägen. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +Du kan också justera komprimeringskvaliteten via `JpegRenderingOptions`. + +### 2. Ändra bilddimensioner + +Ibland behöver du en miniatyr istället för en full‑storlek skärmdump. Ställ in `ImageSize` på alternativen: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Hantera autentiseringsskyddade sidor + +Om mål‑URL:en kräver grundläggande autentisering, ange referenser via `HttpWebRequest` innan du skapar `HtmlDocument`. Alternativt, ladda ner HTML själv (med `HttpClient`) och mata in den som en sträng: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Använda ett eget teckensnitt + +Aspose.HTML kan bädda in lokala teckensnitt. Registrera teckensnittsmappen innan du laddar dokumentet: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Nu kommer alla `font-family`‑deklarationer på sidan att lösa upp till dina egna filer. + +### 5. Rendera flera sidor i en loop + +Om du behöver batch‑processa en lista med URL:er: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Vanliga fallgropar & hur du undviker dem + +| Symptom | Trolig orsak | Åtgärd | +|---------|--------------|-----| +| Tom PNG‑fil | `HtmlDocument.IsEmpty` true (sidan misslyckades att laddas) | Verifiera URL, kontrollera nätverksproxy, säkerställ att TLS 1.2 är aktiverat. | +| Förvrängd text på Linux | Teckensnittshintning inaktiverad | Ställ in `renderingOptions.TextOptions.UseHinting = true;`. | +| Vattenstämpel på utdata | Ingen licens angiven | Registrera en temporär eller fullständig licens via `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Lågupplöst bild | Standard‑DPI 96 är otillräckligt för utskrift | Öka `renderingOptions.DpiX` och `DpiY` till 150‑300. | + +--- + +## 🎉 Slutsats + +Vi har precis gått igenom allt du behöver för att **rendera HTML till bild** med Aspose.HTML i C#. Från att ladda en fjärr‑sida, konfigurera kantutjämning och **ställa in teckensnittsstil**, till slut att **spara renderad bild** som PNG, hela arbetsflödet passar snyggt in i några korta steg. + +Nu kan du **konvertera webbsida till PNG** i farten, bädda in skärmdumpar i rapporter eller generera miniatyrer för en katalog—utan någon webbläsar‑automatisering. + +### Vad blir nästa? + +- Experimentera med **convert html to png** för olika skärmstorlekar (mobil vs desktop). +- Försök exportera till PDF med `PdfRenderer` om du behöver ett utskrivbart dokument. +- Dyk ner i Aspose.HTML:s DOM‑manipulerings‑API:er för att injicera vattenstämplar eller anpassad CSS innan rendering. + +Har du frågor om kantfall, licensiering eller prestandaoptimering? Lägg en kommentar nedan, och lycka till med kodandet! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/swedish/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..6afed0e69 --- /dev/null +++ b/html/swedish/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,249 @@ +--- +category: general +date: 2026-03-14 +description: Rendera HTML till PNG snabbt med Aspose.HTML. Lär dig hur du genererar + PNG från HTML, tillämpar fet och kursiv teckensnittsstil och sparar HTML till en + ström. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: sv +og_description: Rendera HTML till PNG med Aspose.HTML. Denna guide visar hur du genererar + PNG från HTML, använder fet kursiv teckensnittsstil och sparar HTML till en ström. +og_title: Rendera HTML till PNG i C# – Fullständig programmeringsgenomgång +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Rendera HTML till PNG i C# – Steg‑för‑steg guide +url: /sv/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Rendera HTML till PNG i C# – Komplett programmeringsgenomgång + +Har du någonsin behövt **rendera HTML till PNG** men varit osäker på vilket bibliotek som ger dig pixelperfekta resultat? Du är inte ensam. I många web‑till‑bild‑pipelines stöter utvecklare på saknade typsnitt, suddig text eller den fruktade frågan “hur fångar jag HTML utan att skriva den till disk först?” + +Här är grejen: Aspose.HTML gör hela processen enkel. I den här handledningen kommer vi att **generera PNG från HTML**, applicera en **fet kursiv teckensnittsstil**, och även **spara HTML till en ström** så att du kan hålla allt i minnet. I slutet har du en färdig‑att‑köra konsolapp som omvandlar ett litet HTML‑snutt till en skarp PNG‑fil. + +--- + +## Vad du behöver + +- **.NET 6+** (koden fungerar med .NET Core och .NET Framework lika väl) +- **Aspose.HTML for .NET** NuGet‑paket – `Install-Package Aspose.HTML` +- En favorit‑IDE (Visual Studio, Rider eller VS Code) – vilken som helst fungerar. + +Inga extra typsnitt, inga externa verktyg, och definitivt inga temporära filer. Bara ren C#. + +## Steg 1: Skapa ett enkelt HTML‑dokument + +Det första vi gör är att bygga ett HTML‑dokument i minnet. Tänk på det som en virtuell webbsida som bara existerar i din process. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Varför detta är viktigt:** Genom att konstruera DOM programatiskt undviker du fil‑IO‑kostnader och du kan injicera dynamiska data i farten. Klassen `HtmlDocument` är ingångspunkten för varje Aspose.HTML‑operation. + +## Steg 2: Spara HTML till en ström + +Istället för att skriva markupen till disk fångar vi den i en anpassad `ResourceHandler`. Detta är **save html to stream**‑delen av arbetsflödet. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Proffstips:** `MemoryHandler` är liten men kraftfull. Om du senare behöver bädda in bilder, CSS eller typsnitt, utöka bara `HandleResource` för att returnera lämpliga strömmar. + +## Steg 3: Konfigurera fet kursiv teckensnittsstil + +När du renderar text vill du ofta att den ser exakt likadan ut som i en webbläsare. Aspose.HTML låter dig sätta **bold italic font style** direkt i renderingsalternativen. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **Vad som händer:** +> * `UseAntialiasing` mjukar upp kanterna på former. +> * `UseHinting` förbättrar glyfpositionering, vilket är avgörande för liten text. +> * `FontStyle` kombinerar `Bold` och `Italic`‑flaggor, så varje textstycke i dokumentet ärver den stilen om den inte överskrivs. + +## Steg 4: Rendera HTML‑dokumentet till en PNG‑bild + +Nu blir det roligt – att omvandla HTML till en bildfil. `ImageRenderer` sköter allt det tunga lyftet. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Om du kör programmet kommer du att se en fil som heter `output.png` i arbetskatalogen. Den innehåller ``‑element har vi redan en giltig HTML‑struktur redo att sparas. + +> **Pro‑tips:** Om du behöver ett komplett HTML‑skelett (``, `
` osv.) genererar Aspose.HTML det automatiskt när du sparar dokumentet, även om du bara har lagt till innehåll i body. + +## Steg 2: Implementera en **Custom Resource Handler** – Fånga HTML i minnet + +En *resurs‑hanterare* talar om för Aspose.HTML var varje resurs (HTML, CSS, bilder osv.) ska skrivas. Genom att åsidosätta `HandleResource` kan vi dirigera HTML‑utdata till en `MemoryStream` istället för en fil. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Varför vi använder en anpassad hanterare:** +- **Prestanda:** Ingen disk‑I/O, allt stannar i RAM. +- **Säkerhet:** Inga temporära filer som kan exponeras. +- **Flexibilitet:** Du kan senare skicka strömmen till ett svar, en databas eller ett annat API. + +## Steg 3: Spara dokumentet med hanteraren – Hjärtat i **Generate HTML Programmatically** + +Nu knyter vi ihop dokumentet och hanteraren. När `htmlDoc.Save(handler)` körs anropar Aspose.HTML `HandleResource` och ger oss strömmen att skriva till. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +Vid detta tillfälle innehåller `handler.HtmlStream` de råa HTML‑bytena. Inget har skrivits till disk, och du kan återanvända strömmen hur många gånger du vill (kom bara ihåg att återställa dess position). + +## Steg 4: Läs den genererade HTML:n från minnet – Verifiera resultatet + +För att bevisa att allt fungerar återställer vi strömmens position till början och läser tillbaka texten. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Förväntad utdata** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Om du ser markupen ovan, grattis – du har lyckats **generate html programmatically** med Aspose.HTML och en **custom resource handler**. + +## Vanliga variationer & kantfall + +### Hantera CSS eller bilder + +Demo‑exemplet ignorerar icke‑HTML‑resurser genom att returnera `Stream.Null`. I ett riktigt scenario kan du vilja fånga CSS‑filer eller bilder också: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Återanvända samma hanterare för flera sparningar + +Om du behöver generera flera HTML‑snuttar i en loop, skapa en ny `MemoryHtmlHandler` för varje iteration eller rensa den befintliga strömmen: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Asynkron sparning (Aspose.HTML 23.4+) + +Nyare versioner stödjer asynkron sparning: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Kom ihåg att `await` och göra din metod `async`. + +## Fullt fungerande exempel + +Nedan är hela programmet som du kan kopiera‑klistra in i en konsolapp. Det innehåller alla delar vi diskuterat, plus några kommentarer för tydlighet. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Kör programmet (`dotnet run`) så bör du se HTML‑koden skriven till konsolen, exakt som tidigare visat. + +## Slutsats + +Vi har just visat hur man **create HTML document C#** med Aspose.HTML, fångar utdata med en **custom resource handler**, och **generate HTML programmatically** utan att röra filsystemet. Mönstret skalar – oavsett om du bygger e‑postmallar, rapporter i farten eller en mikrotjänst som returnerar HTML‑snuttar. + +Nästa steg? Prova att lägga till en CSS‑stilfil via hanteraren, eller strömma HTML:n direkt in i ett ASP.NET Core‑svar (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Du kan också koppla utdata till en PDF‑konverterare eller ett HTML‑till‑bild‑bibliotek för ännu rikare arbetsflöden. + +Har du frågor om bildhantering, asynkron sparning eller integration med andra bibliotek? Lämna en kommentar, och lycka till med kodandet! + +{{< /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/rendering-html-documents/_index.md b/html/thai/net/rendering-html-documents/_index.md index 9266aa954..d9455b5a7 100644 --- a/html/thai/net/rendering-html-documents/_index.md +++ b/html/thai/net/rendering-html-documents/_index.md @@ -62,6 +62,11 @@ Aspose.HTML สำหรับ .NET ถือเป็นตัวเลือ เรียนรู้วิธีการเรนเดอร์ไฟล์ HTML เป็น PNG ด้วย Aspose.HTML สำหรับ .NET อย่างละเอียดในคู่มือขั้นตอนนี้! ### [วิธีเรนเดอร์ HTML เป็น PNG ด้วย Aspose – คู่มือฉบับสมบูรณ์](./how-to-render-html-to-png-with-aspose-complete-guide/) เรียนรู้วิธีการเรนเดอร์ไฟล์ HTML เป็น PNG อย่างละเอียดด้วย Aspose.HTML สำหรับ .NET ในคู่มือฉบับสมบูรณ์นี้! +### [เรนเดอร์ HTML เป็นภาพใน C# – คู่มือขั้นตอนเต็ม](./render-html-to-image-in-c-complete-step-by-step-guide/) +เรียนรู้วิธีเรนเดอร์ HTML เป็นภาพด้วย C# อย่างละเอียดในคู่มือขั้นตอนเต็มนี้! + +### [เรนเดอร์ HTML เป็น PNG ใน C# – คู่มือขั้นตอนต่อขั้นตอน](./render-html-to-png-in-c-step-by-step-guide/) +เรียนรู้วิธีการเรนเดอร์ HTML เป็น PNG ด้วย C# อย่างละเอียดในคู่มือขั้นตอนต่อขั้นตอนนี้! {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/thai/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/thai/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..78dcf9030 --- /dev/null +++ b/html/thai/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-03-14 +description: เรนเดอร์ HTML เป็นภาพอย่างรวดเร็วด้วย Aspose.HTML เรียนรู้วิธีแปลงหน้าเว็บเป็น + PNG ตั้งค่ารูปแบบฟอนต์ และบันทึกภาพที่เรนเดอร์ด้วยเพียงไม่กี่บรรทัดของ C# +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: th +og_description: เรนเดอร์ HTML เป็นภาพด้วย Aspose.HTML บทเรียนนี้แสดงวิธีแปลงเว็บเพจเป็น + PNG ตั้งค่ารูปแบบฟอนต์ และบันทึกภาพที่เรนเดอร์ใน C# +og_title: แปลง HTML เป็นภาพใน C# – คู่มือเร็วและง่าย +tags: +- C# +- Aspose.HTML +- Image Rendering +title: แปลง HTML เป็นภาพใน C# – คู่มือขั้นตอนเต็ม +url: /th/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# แปลง HTML เป็นภาพ – คำแนะนำเต็มสำหรับ C# + +เคยต้อง **แปลง HTML เป็นภาพ** แต่ไม่แน่ใจว่าจะเลือกไลบรารีไหนหรือไม่? คุณไม่ได้เป็นคนเดียว ในหลายสถานการณ์ของการทำเว็บ‑อัตโนมัติหรือการสร้างรายงาน คุณอาจมีหน้าเว็บสดที่ต้องการเก็บเป็น PNG, JPEG หรือแม้แต่ BMP ข่าวดีคือ Aspose.HTML ทำให้เรื่องนี้ง่ายเหมือนเค้ก เพียงไม่กี่บรรทัดของโค้ดคุณก็สามารถ **แปลงหน้าเว็บเป็น PNG** ได้เลย + +ในคู่มือนี้เราจะเดินผ่านกระบวนการทั้งหมด: ตั้งแต่การติดตั้งแพ็กเกจ Aspose.HTML, การโหลด URL ระยะไกล, การปรับแต่งตัวเลือกการเรนเดอร์ (รวมถึงวิธี **ตั้งค่าแบบอักษร**), และสุดท้าย **บันทึกภาพที่เรนเดอร์** ลงดิสก์ เมื่อเสร็จคุณจะมีแอปคอนโซลที่พร้อมรันและสร้างภาพหน้าจอคมชัดของหน้าเว็บใดก็ได้ + +## สิ่งที่คุณต้องมี + +ก่อนที่เราจะเริ่มลงมือ ตรวจสอบให้แน่ใจว่าคุณมี: + +| ข้อกำหนด | เหตุผล | +|--------------|--------| +| .NET 6.0 SDK หรือใหม่กว่า | Aspose.HTML รองรับ .NET Standard 2.0+ ดังนั้น .NET 6 จะให้รันไทม์ที่ทันสมัยที่สุด | +| Visual Studio 2022 (หรือ VS Code) | IDE ที่สะดวกช่วยเร่งการดีบัก | +| Aspose.HTML for .NET NuGet package | นี่คือเครื่องยนต์ที่ทำงานหนัก | +| ใบอนุญาต Aspose.HTML ที่ถูกต้อง (ไม่บังคับ) | หากไม่มีใบอนุญาต คุณจะเห็นลายน้ำบนภาพผลลัพธ์ | + +คุณสามารถดาวน์โหลดแพ็กเกจผ่าน CLI: + +```bash +dotnet add package Aspose.HTML +``` + +หากคุณชอบใช้ GUI เพียงค้นหา “Aspose.HTML” ใน NuGet Package Manager + +--- + +## ขั้นตอนที่ 1: โหลดหน้าเว็บที่คุณต้องการแปลงเป็นภาพ + +สิ่งแรกที่ต้องทำคือให้ Aspose.HTML มีเอกสารต้นทาง สามารถเป็นไฟล์ในเครื่อง, สตริง, หรือ URL ระยะไกล ในสถานการณ์จริงส่วนใหญ่คุณจะทำงานกับไซต์สด ดังนั้นเราจะ **แปลงหน้าเว็บเป็น PNG** โดยชี้ไปที่ `https://example.com` + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **ทำไมเรื่องนี้ถึงสำคัญ:** การโหลดหน้าเป็น `HtmlDocument` ให้คุณเข้าถึง DOM อย่างเต็มที่ ซึ่งหมายความว่าคุณสามารถแทรก CSS, ปรับเปลี่ยนเลย์เอาต์, หรือแม้แต่รัน JavaScript ก่อนทำการแปลงเป็นภาพได้ + +--- + +## ขั้นตอนที่ 2: กำหนดค่าตัวเลือกการเรนเดอร์ภาพ + +เมื่อ HTML อยู่ในหน่วยความจำแล้ว เราต้องบอกตัวเรนเดอร์ว่าต้องการให้ภาพสุดท้ายออกมาอย่างไร ที่นี่คุณสามารถ **ตั้งค่าแบบอักษร**, เปิดใช้งาน antialiasing, หรือปรับ DPI ตัวอย่างการตั้งค่าพื้นฐานที่สมดุลระหว่างคุณภาพและความเร็ว + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **เคล็ดลับ:** หากคุณต้องการน้ำหนักแบบปกติเท่านั้น ให้ลบ flag `WebFontStyle` ออก สำหรับหัวเรื่องคุณอาจใช้ `WebFontStyle.Bold` เพียงอย่างเดียว ส่วนคำบรรยายอาจใช้ `WebFontStyle.Italic` + +--- + +## ขั้นตอนที่ 3: เรนเดอร์หน้าและ **บันทึกภาพที่เรนเดอร์** เป็น PNG + +เมื่อเอกสารและตัวเลือกพร้อม ขั้นตอนสุดท้ายคือสร้าง `ImageRenderer` และเขียนไฟล์ผลลัพธ์ บล็อก `using` จะทำให้ทรัพยากรถูกปล่อยออกมาอย่างทันท่วงที + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +เมื่อคุณรันโปรแกรม คุณควรจะเห็นไฟล์ `page.png` ในโฟลเดอร์โปรเจกต์ของคุณ ซึ่งเป็นภาพสแนปช็อตที่ตรงกับ *example.com* เปิดด้วยโปรแกรมดูภาพใดก็ได้และคุณจะเห็นสไตล์ตัวหนา‑เอียงที่เราตั้งค่าไว้ก่อนหน้า + +### ผลลัพธ์ที่คาดหวัง + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +PNG จะมีขนาดประมาณ 800 × 600 px (ขึ้นอยู่กับมิติเดิมของหน้า) พร้อมขอบเรียบเนียนจาก antialiasing + +--- + +## ตัวอย่างทำงานเต็มรูปแบบ + +รวมทุกอย่างเข้าด้วยกัน นี่คือแอปคอนโซลขนาดเล็กที่คุณสามารถคัดลอก‑วางลงใน `Program.cs` ได้ มันคอมไพล์และรันได้ทันที + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +รันด้วยคำสั่ง: + +```bash +dotnet run +``` + +…และคุณจะได้ PNG ใหม่พร้อมสำหรับการเก็บ, ส่งอีเมล, หรือฝังในรายงาน + +--- + +## ความแปรผันและกรณีขอบ + +### 1. แปลงเป็น JPEG แทน PNG + +หากระบบต่อท้ายของคุณต้องการ JPEG (ไฟล์ขนาดเล็กกว่า, การบีบอัดแบบเสียคุณภาพ) เพียงเปลี่ยนนามสกุลไฟล์ใน `Save` Aspose.HTML จะตรวจจับรูปแบบจากเส้นทางโดยอัตโนมัติ + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +คุณยังสามารถปรับคุณภาพการบีบอัดผ่าน `JpegRenderingOptions` + +### 2. เปลี่ยนขนาดภาพ + +บางครั้งคุณต้องการรูปขนาดย่อแทนสแนปช็อตเต็มขนาด ตั้งค่า `ImageSize` บน options: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. จัดการหน้าที่ต้องการการยืนยันตัวตน + +หาก URL เป้าหมายต้องการการยืนยันแบบ basic ให้ส่งข้อมูลประจำตัวผ่าน `HttpWebRequest` ก่อนสร้าง `HtmlDocument` หรือดาวน์โหลด HTML ด้วยตนเอง (ใช้ `HttpClient`) แล้วส่งเป็นสตริง: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. ใช้ฟอนต์แบบกำหนดเอง + +Aspose.HTML สามารถฝังฟอนต์ในเครื่องได้ ลงทะเบียนโฟลเดอร์ฟอนต์ก่อนโหลดเอกสาร: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +ตอนนี้คำสั่ง `font-family` ใด ๆ ในหน้าเว็บจะถูกแมปไปยังไฟล์ฟอนต์ที่คุณกำหนดไว้ + +### 5. เรนเดอร์หลายหน้าในลูป + +หากต้องการประมวลผลหลาย URL เป็นชุด: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## ข้อผิดพลาดทั่วไปและวิธีหลีกเลี่ยง + +| อาการ | สาเหตุที่เป็นไปได้ | วิธีแก้ | +|---------|--------------|-----| +| PNG ว่างเปล่า | `HtmlDocument.IsEmpty` เป็น true (โหลดหน้าไม่สำเร็จ) | ตรวจสอบ URL, ตรวจสอบพร็อกซีเครือข่าย, เปิดใช้งาน TLS 1.2 | +| ตัวอักษรแสดงเป็นอักขระผิดบน Linux | การ hint ฟอนต์ถูกปิด | ตั้งค่า `renderingOptions.TextOptions.UseHinting = true;` | +| มีลายน้ำบนผลลัพธ์ | ไม่มีใบอนุญาต | ลงทะเบียนใบอนุญาตชั่วคราวหรือเต็มรูปแบบด้วย `License license = new License(); license.SetLicense("Aspose.Total.lic");` | +| ภาพความละเอียดต่ำ | DPI เริ่มต้น 96 ไม่พอสำหรับการพิมพ์ | เพิ่มค่า `renderingOptions.DpiX` และ `DpiY` เป็น 150‑300 | + +--- + +## 🎉 สรุป + +เราครอบคลุมทุกอย่างที่คุณต้องการเพื่อ **แปลง HTML เป็นภาพ** ด้วย Aspose.HTML ใน C# ตั้งแต่การโหลดหน้าเว็บระยะไกล, การกำหนด antialiasing และ **ตั้งค่าแบบอักษร**, จนถึงการ **บันทึกภาพที่เรนเดอร์** เป็น PNG กระบวนการทั้งหมดสั้นกระชับในไม่กี่ขั้นตอน + +ตอนนี้คุณสามารถ **แปลงหน้าเว็บเป็น PNG** ได้แบบเรียลไทม์, ฝังสแนปช็อตในรายงาน, หรือสร้างรูปขนาดย่อสำหรับแคตาล็อก — ไม่ต้องพึ่งการอัตโนมัติของเบราว์เซอร์ + +### ขั้นตอนต่อไป + +- ทดลอง **แปลง html เป็น png** สำหรับขนาดหน้าจอที่ต่างกัน (มือถือ vs เดสก์ท็อป) +- ลองส่งออกเป็น PDF ด้วย `PdfRenderer` หากต้องการเอกสารที่พิมพ์ได้ +- ศึกษา API การจัดการ DOM ของ Aspose.HTML เพื่อแทรกลายน้ำหรือ CSS กำหนดเองก่อนการเรนเดอร์ + +มีคำถามเกี่ยวกับกรณีขอบ, ใบอนุญาต, หรือการปรับประสิทธิภาพ? แสดงความคิดเห็นด้านล่างและขอให้สนุกกับการเขียนโค้ด! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/thai/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..c638ebd95 --- /dev/null +++ b/html/thai/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-03-14 +description: เรนเดอร์ HTML เป็น PNG อย่างรวดเร็วด้วย Aspose.HTML เรียนรู้วิธีสร้าง + PNG จาก HTML ใช้สไตล์ฟอนต์หนาและเอียง และบันทึก HTML ไปยังสตรีม. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: th +og_description: เรนเดอร์ HTML เป็น PNG ด้วย Aspose.HTML คู่มือนี้แสดงวิธีสร้าง PNG + จาก HTML, ใช้รูปแบบฟอนต์หนาและเอียง, และบันทึก HTML ไปยังสตรีม. +og_title: เรนเดอร์ HTML เป็น PNG ใน C# – คู่มือการเขียนโปรแกรมอย่างครบถ้วน +tags: +- Aspose.HTML +- C# +- Image Rendering +title: แปลง HTML เป็น PNG ใน C# – คู่มือขั้นตอนโดยละเอียด +url: /th/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +final output with all translated content.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# แปลง HTML เป็น PNG ใน C# – คู่มือการเขียนโปรแกรมเต็มรูปแบบ + +เคยต้องการ **render HTML to PNG** แต่ไม่แน่ใจว่าห้องสมุดใดจะให้ผลลัพธ์ที่พิกเซล‑เพอร์เฟค? คุณไม่ได้เป็นคนเดียว ในหลาย pipeline จากเว็บไปเป็นภาพ นักพัฒนามักเจอปัญหาแบบฟอนต์หาย, ข้อความเบลอ, หรือคำถามที่น่ากลัว “จะจับ HTML อย่างไรโดยไม่ต้องเขียนลงดิสก์ก่อน?” + +เรื่องคือ: Aspose.HTML ทำให้กระบวนการทั้งหมดง่ายดาย ในบทแนะนำนี้เราจะ **generate PNG from HTML**, ใช้ **bold italic font style**, และแม้กระทั่ง **save HTML to a stream** เพื่อให้คุณเก็บทุกอย่างในหน่วยความจำ สุดท้ายคุณจะได้แอปคอนโซลที่พร้อมรันซึ่งแปลงสแนปเพต HTML เล็ก ๆ เป็นไฟล์ PNG ที่คมชัด. + +--- + +## สิ่งที่คุณต้องการ + +- **.NET 6+** (โค้ดทำงานได้กับ .NET Core และ .NET Framework ทั้งหมด) +- **Aspose.HTML for .NET** NuGet package – `Install-Package Aspose.HTML` +- IDE ที่คุณชื่นชอบ (Visual Studio, Rider หรือ VS Code) – ใช้ได้ทุกตัว + +ไม่มีฟอนต์เพิ่มเติม, ไม่มีเครื่องมือภายนอก, และแน่นอนว่าไม่มีไฟล์ชั่วคราว เพียงแค่ C# แท้ ๆ. + +--- + +## ขั้นตอนที่ 1: สร้างเอกสาร HTML อย่างง่าย + +สิ่งแรกที่เราทำคือสร้างเอกสาร HTML ที่อยู่ในหน่วยความจำ คิดว่าเป็นหน้าเว็บเสมือนที่อยู่เฉพาะภายในโปรเซสของคุณ. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **ทำไมเรื่องนี้ถึงสำคัญ:** การสร้าง DOM อย่างโปรแกรมมิ่งทำให้คุณหลีกเลี่ยงภาระการอ่าน‑เขียนไฟล์และสามารถแทรกข้อมูลแบบไดนามิกได้ทันที คลาส `HtmlDocument` เป็นจุดเริ่มต้นสำหรับทุกการทำงานของ Aspose.HTML + +--- + +## ขั้นตอนที่ 2: บันทึก HTML ไปยัง Stream + +แทนที่จะเขียนมาร์กอัปลงดิสก์ เราจับมันไว้ใน `ResourceHandler` ที่กำหนดเอง นี่คือส่วน **save html to stream** ของกระบวนการทำงาน. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **เคล็ดลับ:** `MemoryHandler` มีขนาดเล็กแต่ทรงพลัง หากคุณต้องการฝังรูปภาพ, CSS หรือฟอนต์ในภายหลัง เพียงขยาย `HandleResource` ให้คืนค่า stream ที่เหมาะสม + +--- + +## ขั้นตอนที่ 3: ตั้งค่า Bold Italic Font Style + +เมื่อคุณเรนเดอร์ข้อความ คุณมักต้องการให้มันดูเหมือนในเบราว์เซอร์ Aspose.HTML ให้คุณตั้งค่า **bold italic font style** โดยตรงในตัวเลือกการเรนเดอร์. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **กำลังเกิดอะไรขึ้น:** +> * `UseAntialiasing` ทำให้ขอบของรูปร่างเรียบเนียน +> * `UseHinting` ปรับตำแหน่ง glyph ให้ดีขึ้น ซึ่งสำคัญสำหรับข้อความขนาดเล็ก +> * `FontStyle` รวมแฟล็ก `Bold` และ `Italic` ทำให้ข้อความทุกส่วนในเอกสารสืบทอดสไตล์นั้น เว้นแต่จะถูกเขียนทับ + +--- + +## ขั้นตอนที่ 4: เรนเดอร์เอกสาร HTML เป็นภาพ PNG + +ตอนนี้เป็นส่วนที่สนุก – แปลง HTML นั้นเป็นไฟล์ภาพ `ImageRenderer` ทำงานหนักทั้งหมด. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +หากคุณรันโปรแกรม คุณจะเห็นไฟล์ชื่อ `output.png` ในไดเรกทอรีทำงาน ซึ่งประกอบด้วยหัวข้อ `` เราก็มีโครงสร้าง HTML ที่สมบูรณ์พร้อมบันทึกแล้ว + +> **เคล็ดลับ:** หากคุณต้องการโครงสร้าง HTML เต็มรูปแบบ (``, `
` ฯลฯ) Aspose.HTML จะสร้างให้โดยอัตโนมัติเมื่อคุณบันทึกเอกสาร แม้ว่าคุณจะเพิ่มเฉพาะเนื้อหาใน `` เท่านั้น + +## ขั้นตอนที่ 2: สร้าง **Custom Resource Handler** – จับ HTML ไว้ในหน่วยความจำ + +*Resource handler* บอก Aspose.HTML ว่าจะเขียนทรัพยากรแต่ละประเภท (HTML, CSS, รูปภาพ ฯลฯ) ไปที่ไหน โดยการโอเวอร์ไรด์ `HandleResource` เราสามารถกำหนดให้เอาต์พุต HTML ไปยัง `MemoryStream` แทนไฟล์ได้ + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**เหตุผลที่ใช้ตัวจัดการแบบกำหนดเอง:** +- **ประสิทธิภาพ:** ไม่ต้องทำ I/O กับดิสก์, ทุกอย่างอยู่ใน RAM +- **ความปลอดภัย:** ไม่มีไฟล์ชั่วคราวที่อาจถูกเปิดเผย +- **ความยืดหยุ่น:** คุณสามารถส่งสตรีมต่อไปยัง response, ฐานข้อมูล, หรือ API อื่นได้ + +## ขั้นตอนที่ 3: บันทึกเอกสารด้วยตัวจัดการ – ใจกลางของ **Generate HTML Programmatically** + +ตอนนี้เราจะเชื่อมเอกสารกับตัวจัดการ เมื่อเรียก `htmlDoc.Save(handler)` Aspose.HTML จะเรียก `HandleResource` ให้เราได้สตรีมเพื่อเขียนข้อมูล + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +ในขณะนี้ `handler.HtmlStream` จะมีไบต์ของ HTML ดิบอยู่ทั้งหมด ไม่ได้เขียนใด ๆ ลงดิสก์ และคุณสามารถใช้สตรีมนี้ซ้ำได้หลายครั้ง (แค่จำไว้ว่ารีเซ็ตตำแหน่งของสตรีม) + +## ขั้นตอนที่ 4: อ่าน HTML ที่สร้างจากหน่วยความจำ – ตรวจสอบผลลัพธ์ + +เพื่อยืนยันว่าทุกอย่างทำงานตามที่คาด เราจะรีเซ็ตตำแหน่งของสตรีมไปที่จุดเริ่มต้นและอ่านข้อความกลับมา + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**ผลลัพธ์ที่คาดหวัง** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +หากคุณเห็นมาร์กอัปด้านบน, ยินดีด้วย—คุณได้ **generate html programmatically** ด้วย Aspose.HTML และ **custom resource handler** อย่างสำเร็จ + +## ความแตกต่างทั่วไป & กรณีขอบ + +### จัดการ CSS หรือรูปภาพ + +ตัวอย่างนี้ละเลยทรัพยากรที่ไม่ใช่ HTML โดยคืนค่า `Stream.Null` ในสถานการณ์จริงคุณอาจต้องการจับไฟล์ CSS หรือรูปภาพด้วย: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### ใช้ตัวจัดการเดียวกันหลายครั้ง + +หากต้องการสร้างส่วน HTML หลายส่วนในลูป ให้สร้าง `MemoryHtmlHandler` ใหม่ทุกครั้งหรือเคลียร์สตรีมที่มีอยู่: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### การบันทึกแบบ Async (Aspose.HTML 23.4+) + +เวอร์ชันใหม่รองรับการบันทึกแบบ async: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +อย่าลืมใช้ `await` และทำให้เมธอดของคุณเป็น `async` + +## ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นโปรแกรมเต็มที่คุณสามารถคัดลอกไปวางในแอปคอนโซลได้ รวมทุกส่วนที่อธิบายไว้และคอมเมนต์เพื่อความชัดเจน + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +รันโปรแกรม (`dotnet run`) แล้วคุณจะเห็น HTML แสดงผลบนคอนโซลตรงตามที่แสดงไว้ก่อนหน้านี้ + +## สรุป + +เราได้แสดงวิธี **create HTML document C#** ด้วย Aspose.HTML, จับเอาต์พุตด้วย **custom resource handler**, และ **generate HTML programmatically** โดยไม่ต้องสัมผัสระบบไฟล์ แพทเทิร์นนี้สามารถขยายได้ ไม่ว่าจะเป็นการสร้างเทมเพลตอีเมล, รายงานแบบไดนามิก, หรือไมโครเซอร์วิสที่คืนส่วน HTML + +ขั้นตอนต่อไป? ลองเพิ่มสไตล์ชีต CSS ผ่านตัวจัดการ, หรือสตรีม HTML ตรงเข้าสู่ response ของ ASP.NET Core (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`) คุณยังสามารถต่อผลลัพธ์ไปยังตัวแปลง PDF หรือไลบรารีแปลง HTML‑to‑image เพื่อเวิร์กโฟลว์ที่ซับซ้อนได้อีกด้วย + +มีคำถามเกี่ยวกับการจัดการรูปภาพ, การบันทึกแบบ async, หรือการผสานกับไลบรารีอื่น ๆ? แสดงความคิดเห็นได้เลย, ขอให้สนุกกับการเขียนโค้ด! + +{{< /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/rendering-html-documents/_index.md b/html/turkish/net/rendering-html-documents/_index.md index 6cce1b921..37068a967 100644 --- a/html/turkish/net/rendering-html-documents/_index.md +++ b/html/turkish/net/rendering-html-documents/_index.md @@ -60,6 +60,10 @@ Aspose.HTML for .NET ile HTML dosyalarını PNG formatına dönüştürmeyi adı Aspose.HTML for .NET kullanarak HTML dosyalarını PNG formatına dönüştürmenin tüm adımlarını öğrenin. ### [HTML'den PNG Oluşturma – Tam C# Render Rehberi](./create-png-from-html-full-c-rendering-guide/) HTML'den PNG oluşturmayı tam C# render rehberiyle adım adım öğrenin. +### [C# ile HTML'yi Görüntüye Dönüştürme – Tam Adım‑Adım Kılavuz](./render-html-to-image-in-c-complete-step-by-step-guide/) +C# ile HTML'yi görüntüye dönüştürmeyi adım adım öğrenin. Bu kapsamlı rehberde örnek kodlar ve ipuçları bulacaksınız. +### [C# ile HTML'yi PNG Olarak İşleme – Adım‑Adım Kılavuz](./render-html-to-png-in-c-step-by-step-guide/) +C# kullanarak HTML'yi PNG'ye dönüştürmeyi adım adım öğrenin. Bu rehberde örnek kodlar ve ipuçları bulacaksınız. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/turkish/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/turkish/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..7af30a2f0 --- /dev/null +++ b/html/turkish/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-03-14 +description: Aspose.HTML kullanarak HTML'yi hızlıca görüntüye dönüştürün. Web sayfasını + PNG'ye nasıl dönüştüreceğinizi, yazı tipi stilini nasıl ayarlayacağınızı ve render + edilen görüntüyü sadece birkaç C# satırıyla nasıl kaydedeceğinizi öğrenin. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: tr +og_description: Aspose.HTML ile HTML'yi görüntüye dönüştürün. Bu öğreticide, web sayfasını + PNG'ye nasıl dönüştüreceğiniz, yazı tipi stilini nasıl ayarlayacağınız ve oluşturulan + görüntüyü C#'ta nasıl kaydedeceğiniz gösterilmektedir. +og_title: C#'ta HTML'yi Görsele Dönüştür – Hızlı ve Kolay Rehber +tags: +- C# +- Aspose.HTML +- Image Rendering +title: C#'ta HTML'yi Görsele Dönüştür – Tam Adım Adım Kılavuz +url: /tr/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML'yi Görüntüye Dönüştür – Tam C# Öğreticisi + +Hiç **render HTML to image** ihtiyacınız oldu mu ama hangi kütüphaneyi seçeceğinizden emin değildiniz? Tek başınıza değilsiniz. Birçok web‑otomasyon veya raporlama senaryosunda arşivlemek istediğiniz canlı bir sayfa elde edersiniz; PNG, JPEG ya da hatta BMP olarak. İyi haber, Aspose.HTML bunu çocuk oyuncağı haline getiriyor, sadece birkaç satır kodla **convert webpage to PNG** yapmanızı sağlıyor. + +Bu rehberde tüm süreci adım adım inceleyeceğiz: Aspose.HTML paketini kurmaktan, uzak bir URL'yi yüklemeye, render seçeneklerini (özellikle **set font style** nasıl yapılır) ayarlamaya ve sonunda **save rendered image** dosyaya kaydetmeye kadar. Sonunda, herhangi bir web sayfasının net bir ekran görüntüsünü üreten, çalıştırmaya hazır bir konsol uygulamanız olacak. + +## İhtiyacınız Olanlar + +| Gereklilik | Sebep | +|------------|-------| +| .NET 6.0 SDK veya daha yenisi | Aspose.HTML .NET Standard 2.0+ hedeflediği için .NET 6 en güncel çalışma zamanını sağlar. | +| Visual Studio 2022 (veya VS Code) | Rahat bir IDE hata ayıklamayı hızlandırır. | +| Aspose.HTML for .NET NuGet paketi | Ağır işi yapan motor budur. | +| Geçerli bir Aspose.HTML lisansı (isteğe bağlı) | Lisans olmadan çıktı görüntüsünde filigran alırsınız. | + +Paketi CLI üzerinden alabilirsiniz: + +```bash +dotnet add package Aspose.HTML +``` + +GUI tercih ediyorsanız, NuGet Package Manager’da “Aspose.HTML” araması yapmanız yeterlidir. + +--- + +## Adım 1: Rasterleştirmek İstediğiniz Web Sayfasını Yükleyin + +İlk yapmanız gereken Aspose.HTML'e bir kaynak belge vermektir. Bu yerel bir dosya, bir dize ya da uzak bir URL olabilir. Çoğu gerçek dünya senaryosunda canlı bir siteyle çalışacaksınız, bu yüzden `https://example.com` adresine işaret ederek **convert webpage to PNG** yapalım. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Neden önemli:** Sayfayı bir `HtmlDocument` olarak yüklemek, DOM’a tam erişim sağlar; bu da CSS enjekte etmenize, düzeni değiştirmenize ya da rasterleştirmeden önce JavaScript çalıştırmanıza imkan tanır. + +--- + +## Adım 2: Görüntü Render Seçeneklerini Yapılandırın + +HTML bellekte olduğuna göre, render aracına son resmin nasıl görünmesini istediğimizi söylememiz gerekiyor. İşte **set font style** yapabileceğiniz, antialiasing’i etkinleştirebileceğiniz ve DPI’yı ayarlayabileceğiniz yer. Aşağıda kalite ve hız dengesini sağlayan sağlam bir varsayılan yapılandırma bulunuyor. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Pro ipucu:** Sadece normal ağırlığa ihtiyacınız varsa `WebFontStyle` bayraklarını kaldırın. Başlıklar için yalnızca `WebFontStyle.Bold`, alt yazılar için ise `WebFontStyle.Italic` kullanabilirsiniz. + +--- + +## Adım 3: Sayfayı Render Edin ve **Save Rendered Image** PNG Olarak + +Belge ve seçenekler hazır olduğunda, son adım `ImageRenderer` nesnesini oluşturup çıktıyı dosyaya yazmaktır. `using` bloğu kaynakların hızlıca serbest bırakılmasını sağlar. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +Programı çalıştırdığınızda proje klasörünüzde `page.png` adlı bir dosya görmelisiniz; bu dosya *example.com* sitesinin sadık bir anlık görüntüsünü içerir. Herhangi bir görüntü görüntüleyiciyle açtığınızda daha önce talep ettiğimiz kalın‑italik stilini fark edeceksiniz. + +### Beklenen Çıktı + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +PNG, sayfanın orijinal boyutlarına bağlı olarak yaklaşık 800 × 600 px olacaktır ve antialiasing sayesinde kenarları yumuşak olur. + +--- + +## Tam Çalışan Örnek + +Her şeyi bir araya getirerek, `Program.cs` içine kopyalayıp yapıştırabileceğiniz minimal bir konsol uygulaması aşağıdadır. Derlenir ve kutudan çıkar çıkmaz çalışır. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Şu komutla çalıştırın: + +```bash +dotnet run +``` + +…ve arşivleme, e‑posta gönderme ya da rapora ekleme için hazır, taze bir PNG elde edeceksiniz. + +--- + +## Varyasyonlar ve Kenar Durumları + +### 1. PNG Yerine JPEG'e Dönüştürme + +Alt sisteminiz JPEG tercih ediyorsa (daha küçük dosya boyutu, kayıplı sıkıştırma), `Save` içindeki dosya uzantısını sadece değiştirin. Aspose.HTML yolu inceleyerek formatı otomatik algılar. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +Sıkıştırma kalitesini `JpegRenderingOptions` üzerinden de ayarlayabilirsiniz. + +### 2. Görüntü Boyutlarını Değiştirme + +Bazen tam boyutlu bir ekran görüntüsü yerine bir küçük resim (thumbnail) gerekir. Seçeneklerde `ImageSize` özelliğini ayarlayın: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Kimlik Doğrulamalı Sayfaları İşleme + +Hedef URL temel kimlik doğrulama gerektiriyorsa, `HtmlDocument` oluşturulmadan önce `HttpWebRequest` ile kimlik bilgilerini sağlayın. Alternatif olarak, HTML'i kendiniz (`HttpClient` kullanarak) indirip bir dize olarak besleyebilirsiniz: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Özel Yazı Tipi Kullanma + +Aspose.HTML yerel yazı tiplerini gömebilir. Belgeyi yüklemeden önce yazı tipi klasörünü kaydedin: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Böylece sayfadaki herhangi bir `font-family` bildirimi, sizin özel dosyalarınıza yönlendirilir. + +### 5. Döngüde Birden Fazla Sayfayı Render Etme + +URL listesine toplu işlem uygulamanız gerekiyorsa: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Yaygın Tuzaklar ve Nasıl Önlenir + +| Belirti | Muhtemel Sebep | Çözüm | +|---------|----------------|-------| +| Boş PNG dosyası | `HtmlDocument.IsEmpty` true (sayfa yüklenemedi) | URL'yi doğrulayın, ağ proxy ayarlarını kontrol edin, TLS 1.2'nin etkin olduğundan emin olun. | +| Linux'ta bozuk metin | Yazı tipi ipucu (hinting) devre dışı | `renderingOptions.TextOptions.UseHinting = true;` olarak ayarlayın. | +| Çıktıda filigran | Lisans sağlanmadı | Geçici ya da tam lisansı `License license = new License(); license.SetLicense("Aspose.Total.lic");` ile kaydedin. | +| Düşük çözünürlüklü görüntü | Varsayılan DPI 96 baskı için yetersiz | `renderingOptions.DpiX` ve `DpiY` değerlerini 150‑300'e yükseltin. | + +--- + +## 🎉 Sonuç + +Aspose.HTML ile C# içinde **render HTML to image** işlemini nasıl yapacağınızı tüm adımlarla ele aldık. Uzaktan bir sayfa yüklemek, antialiasing ve **set font style** ayarlarını yapılandırmak ve sonunda **save rendered image** PNG olarak kaydetmek, birkaç kısa adımda tamamlanıyor. + +Artık **convert webpage to PNG** işlemini anında yapabilir, raporlara ekran görüntüsü ekleyebilir ya da kataloglar için küçük resimler oluşturabilirsiniz—tarayıcı otomasyonuna gerek kalmadan. + +### Sıradaki Adımlar? + +- Farklı ekran boyutları (mobil vs masaüstü) için **convert html to png** deneyin. +- Yazdırılabilir bir belgeye ihtiyacınız varsa `PdfRenderer` ile PDF dışa aktarımını deneyin. +- Render etmeden önce su işareti eklemek veya özel CSS enjekte etmek için Aspose.HTML’in DOM manipülasyon API’lerine dalın. + +Kenarlık durumları, lisanslama veya performans ayarlamalarıyla ilgili sorularınız mı var? Aşağıya yorum bırakın, iyi kodlamalar! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/turkish/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..4bbef8a89 --- /dev/null +++ b/html/turkish/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-03-14 +description: Aspose.HTML ile HTML'yi hızlıca PNG'ye dönüştürün. HTML'den PNG oluşturmayı, + kalın ve italik yazı tipi stilini uygulamayı ve HTML'yi bir akışa kaydetmeyi öğrenin. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: tr +og_description: Aspose.HTML ile HTML'yi PNG'ye dönüştürün. Bu kılavuz, HTML'den PNG + oluşturmayı, kalın italik yazı stilini kullanmayı ve HTML'yi bir akışa kaydetmeyi + gösterir. +og_title: C#'ta HTML'yi PNG'ye Render Et – Tam Programlama Rehberi +tags: +- Aspose.HTML +- C# +- Image Rendering +title: C# ile HTML'yi PNG'ye Dönüştür – Adım Adım Rehber +url: /tr/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +: none else. + +Check variable names: we didn't translate. + +Check markdown links: none. + +Check shortcodes: preserved. + +Now produce final output with all content.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#’ta HTML’yi PNG’ye Dönüştür – Tam Programlama Rehberi + +Hiç **HTML'yi PNG'ye dönüştürmek** gerektiğinde, hangi kütüphanenin pikselleri mükemmel sonuç vereceğinden emin olamıyor muydunuz? Yalnız değilsiniz. Birçok web‑to‑image işlem hattında geliştiriciler eksik yazı tipleri, bulanık metinler veya “HTML'yi diske yazmadan nasıl yakalarım?” gibi korkutucu sorunlarla karşılaşıyor. + +İşte mesele: Aspose.HTML tüm süreci çocuk oyuncağı haline getiriyor. Bu öğreticide **HTML'den PNG oluşturacağız**, **kalın italik yazı tipi stilini** uygulayacağız ve hatta **HTML'yi bir akışa kaydedeceğiz** böylece her şeyi bellekte tutabilirsiniz. Sonunda, küçük bir HTML snippet'ini net bir PNG dosyasına dönüştüren, çalıştırmaya hazır bir konsol uygulamanız olacak. + +--- + +## İhtiyacınız Olanlar + +- **.NET 6+** (kod .NET Core ve .NET Framework ile aynı şekilde çalışır) +- **Aspose.HTML for .NET** NuGet paketi – `Install-Package Aspose.HTML` +- Favori bir IDE (Visual Studio, Rider veya VS Code) – herhangi biri yeterli. + +Ekstra yazı tipleri, harici araçlar yok ve kesinlikle geçici dosyalar yok. Sadece saf C#. + +## Adım 1: Basit Bir HTML Belgesi Oluşturun + +İlk yaptığımız şey, bellekte bir HTML belgesi oluşturmaktır. Bunu, yalnızca süreciniz içinde var olan sanal bir web sayfası olarak düşünün. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Why this matters:** DOM'u programlı olarak oluşturduğunuzda dosya‑IO yükünden kaçınırsınız ve dinamik verileri anında ekleyebilirsiniz. `HtmlDocument` sınıfı, her Aspose.HTML işleminin giriş noktasıdır. + +## Adım 2: HTML'yi Bir Akışa Kaydedin + +İşaretlemeyi diske yazmak yerine, özel bir `ResourceHandler` içinde yakalıyoruz. Bu, iş akışının **save html to stream** kısmıdır. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Pro tip:** `MemoryHandler` küçük ama güçlüdür. Daha sonra görüntü, CSS veya yazı tipleri eklemeniz gerekirse, sadece `HandleResource` metodunu genişleterek uygun akışları döndürün. + +## Adım 3: Kalın İtalik Yazı Tipi Stilini Yapılandırın + +Metin render ederken, genellikle tarayıcıda göründüğü gibi olmasını istersiniz. Aspose.HTML, **bold italic font style**'ı doğrudan render seçeneklerine ayarlamanıza izin verir. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **What’s happening:** +> * `UseAntialiasing` şekil kenarlarını yumuşatır. +> * `UseHinting` glif konumlandırmasını iyileştirir, bu küçük metinler için kritiktir. +> * `FontStyle` `Bold` ve `Italic` bayraklarını birleştirir, böylece belgedeki her metin parçası bu stili devralır, aksi belirtilmedikçe. + +## Adım 4: HTML Belgesini PNG Görüntüsüne Render Edin + +Şimdi eğlenceli kısım – HTML'yi bir görüntü dosyasına dönüştürmek. `ImageRenderer` tüm ağır işi yapar. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Programı çalıştırırsanız, çalışma dizininde `output.png` adlı bir dosya göreceksiniz. Bu dosya, kalın‑italik stilinde render edilmiş `` öğesi ekleyerek zaten kaydedilmeye hazır geçerli bir HTML yapısına sahip oluyoruz. + +> **Pro tip:** Tam bir HTML iskeleti (``, `
` vb.) ihtiyacınız varsa, Aspose.HTML belgeyi kaydettiğinizde bunu otomatik olarak oluşturur; sadece gövde içeriği eklemiş olsanız bile. + +## Adım 2: **Özel Kaynak İşleyicisi** Uygulama – HTML’i Bellekte Yakalama + +Bir *kaynak işleyicisi*, Aspose.HTML’e her kaynağın (HTML, CSS, resimler vb.) nereye yazılacağını söyler. `HandleResource` metodunu geçersiz kılarak HTML çıktısını bir `MemoryStream`’e yönlendirebiliriz, dosyaya değil. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Özel bir işleyici kullanmamızın sebepleri:** +- **Performans:** Disk I/O yok, her şey RAM’de kalır. +- **Güvenlik:** Açığa çıkabilecek geçici dosyalar olmaz. +- **Esneklik:** Akışı daha sonra bir yanıt, veritabanı veya başka bir API’ye aktarabilirsiniz. + +## Adım 3: İşleyiciyi Kullanarak Belgeyi Kaydetme – **Generate HTML Programmatically**’in Kalbi + +Şimdi belgeyi ve işleyiciyi birleştiriyoruz. `htmlDoc.Save(handler)` çalıştığında, Aspose.HTML `HandleResource` metodunu çağırır ve bize yazılacak akışı verir. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +Bu noktada `handler.HtmlStream` ham HTML baytlarını içerir. Disk’e hiçbir şey yazılmamış olur ve akışı istediğiniz kadar yeniden kullanabilirsiniz (pozisyonunu sıfırlamayı unutmayın). + +## Adım 4: Bellekten Üretilen HTML’i Okuma – Çıktıyı Doğrulama + +Her şeyin doğru çalıştığını kanıtlamak için akışın konumunu başa alıp metni geri okuruz. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Beklenen çıktı** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Eğer yukarıdaki işaretlemeyi görüyorsanız, tebrikler—Aspose.HTML ve **özel bir kaynak işleyicisi** kullanarak **generate html programmatically** işlemini başarıyla tamamladınız. + +## Yaygın Varyasyonlar ve Kenar Durumları + +### CSS veya Resimlerin İşlenmesi + +Demo, HTML dışı kaynakları `Stream.Null` döndürerek yok sayar. Gerçek bir senaryoda CSS dosyalarını veya resimleri de yakalamak isteyebilirsiniz: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Aynı İşleyiciyi Birden Çok Kaydetme İçin Yeniden Kullanma + +Bir döngü içinde birkaç HTML snippet’i üretmeniz gerekiyorsa, her yineleme için yeni bir `MemoryHtmlHandler` oluşturun veya mevcut akışı temizleyin: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Async Kaydetme (Aspose.HTML 23.4+) + +Yeni sürümler async kaydetmeyi destekler: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +`await` kullanmayı ve metodunuzu `async` olarak işaretlemeyi unutmayın. + +## Tam Çalışan Örnek + +Aşağıda, bir konsol uygulamasına kopyalayıp yapıştırabileceğiniz eksiksiz program yer alıyor. Tartıştığımız tüm parçalar ve açıklayıcı yorumlar içeriyor. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Programı çalıştırın (`dotnet run`) ve daha önce gösterildiği gibi HTML’in konsola basıldığını görmelisiniz. + +## Sonuç + +Aspose.HTML kullanarak **HTML belge oluşturma C#** işlemini, **özel bir kaynak işleyicisi** ile çıktıyı yakalayarak ve **generate HTML programmatically** yaparak dosya sistemine dokunmadan nasıl gerçekleştireceğimizi gösterdik. Bu desen, e‑posta şablonları, anlık raporlar veya HTML snippet’leri dönen bir mikro‑servis gibi senaryolarda ölçeklenebilir. + +Sonraki adımlar? İşleyici aracılığıyla bir CSS stil sayfası ekleyin ya da HTML’i doğrudan bir ASP.NET Core yanıtına (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`) akıtın. Çıktıyı bir PDF dönüştürücüye veya HTML‑to‑image kütüphanesine de bağlayarak daha zengin iş akışları oluşturabilirsiniz. + +Resim işleme, async kaydetme veya diğer kütüphanelerle entegrasyon hakkında sorularınız mı var? Yorum bırakın, mutlu kodlamalar! + +{{< /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/rendering-html-documents/_index.md b/html/vietnamese/net/rendering-html-documents/_index.md index 8ef7cb5b6..cb83f7436 100644 --- a/html/vietnamese/net/rendering-html-documents/_index.md +++ b/html/vietnamese/net/rendering-html-documents/_index.md @@ -60,6 +60,10 @@ Học cách chuyển đổi HTML sang PNG một cách dễ dàng với Aspose.HT Học cách chuyển đổi HTML sang PNG một cách dễ dàng với Aspose.HTML cho .NET. Khám phá hướng dẫn chi tiết từng bước. ### [Tạo PNG từ HTML – Hướng dẫn đầy đủ C# Rendering](./create-png-from-html-full-c-rendering-guide/) Học cách chuyển đổi HTML thành PNG bằng Aspose.HTML cho .NET với hướng dẫn chi tiết bằng C#. +### [Render HTML thành hình ảnh trong C# – Hướng dẫn chi tiết từng bước](./render-html-to-image-in-c-complete-step-by-step-guide/) +Học cách chuyển đổi HTML sang hình ảnh bằng C# với Aspose.HTML, bao gồm các bước chi tiết và mẹo thực tiễn. +### [Cách render HTML thành PNG trong C# – Hướng dẫn từng bước](./render-html-to-png-in-c-step-by-step-guide/) +Học cách chuyển đổi HTML sang PNG trong C# bằng Aspose.HTML, qua các bước chi tiết và thực hành thực tế. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/vietnamese/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md b/html/vietnamese/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..1427fe9d4 --- /dev/null +++ b/html/vietnamese/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-03-14 +description: Kết xuất HTML thành hình ảnh nhanh chóng bằng Aspose.HTML. Tìm hiểu cách + chuyển đổi trang web sang PNG, thiết lập kiểu phông chữ và lưu hình ảnh đã kết xuất + chỉ trong vài dòng C#. +draft: false +keywords: +- render html to image +- convert webpage to png +- convert html to png +- set font style +- save rendered image +language: vi +og_description: Kết xuất HTML thành hình ảnh với Aspose.HTML. Hướng dẫn này chỉ cách + chuyển trang web sang PNG, thiết lập kiểu phông chữ và lưu hình ảnh đã kết xuất + bằng C#. +og_title: Chuyển đổi HTML thành hình ảnh trong C# – Hướng dẫn nhanh và dễ dàng +tags: +- C# +- Aspose.HTML +- Image Rendering +title: Chuyển đổi HTML thành hình ảnh trong C# – Hướng dẫn chi tiết từng bước +url: /vi/net/rendering-html-documents/render-html-to-image-in-c-complete-step-by-step-guide/ +--- + +Also bullet list items. + +Also "Got questions..." translate. + +Also "Screenshot of a rendered page showing the result of render html to image" alt translate. + +Now produce final content. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to Image – Complete C# Tutorial + +Bạn đã bao giờ cần **render HTML to image** nhưng không chắc nên chọn thư viện nào? Bạn không phải là người duy nhất. Trong nhiều trường hợp tự động hoá web hoặc báo cáo, bạn sẽ có một trang web đang hoạt động và muốn lưu lại dưới dạng PNG, JPEG, hoặc thậm chí BMP. Tin tốt là Aspose.HTML làm cho việc này trở nên đơn giản, cho phép bạn **convert webpage to PNG** chỉ với vài dòng code. + +Trong hướng dẫn này, chúng ta sẽ đi qua toàn bộ quy trình: từ cài đặt gói Aspose.HTML, tải một URL từ xa, điều chỉnh các tùy chọn render (bao gồm cách **set font style**), và cuối cùng **save rendered image** vào đĩa. Khi hoàn thành, bạn sẽ có một ứng dụng console sẵn sàng chạy và tạo ra một ảnh chụp màn hình sắc nét của bất kỳ trang web nào. + +## What You’ll Need + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +| Điều kiện tiên quyết | Lý do | +|----------------------|-------| +| .NET 6.0 SDK hoặc mới hơn | Aspose.HTML hỗ trợ .NET Standard 2.0+, vì vậy .NET 6 cung cấp môi trường runtime mới nhất. | +| Visual Studio 2022 (hoặc VS Code) | Một IDE thoải mái giúp việc gỡ lỗi nhanh hơn. | +| Aspose.HTML for .NET NuGet package | Đây là động cơ thực hiện các công việc nặng. | +| Giấy phép Aspose.HTML hợp lệ (tùy chọn) | Nếu không có giấy phép, bạn sẽ nhận được watermark trên ảnh đầu ra. | + +Bạn có thể lấy gói này qua CLI: + +```bash +dotnet add package Aspose.HTML +``` + +Nếu bạn thích giao diện đồ họa, chỉ cần tìm “Aspose.HTML” trong NuGet Package Manager. + +--- + +## Bước 1: Load the Web Page You Want to Rasterize + +Điều đầu tiên bạn cần làm là cung cấp cho Aspose.HTML một tài liệu nguồn. Nó có thể là một tệp cục bộ, một chuỗi, hoặc một URL từ xa. Trong hầu hết các tình huống thực tế, bạn sẽ làm việc với một trang web đang hoạt động, vì vậy hãy **convert webpage to PNG** bằng cách chỉ tới `https://example.com`. + +```csharp +using Aspose.Html; + +// ... + +// Create an HtmlDocument from a remote URL +HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + +// Optional: verify that the document loaded successfully +if (htmlDoc.IsEmpty) +{ + Console.WriteLine("Failed to load the page. Check the URL or your network."); + return; +} +``` + +> **Tại sao điều này quan trọng:** Tải trang dưới dạng `HtmlDocument` cho phép bạn truy cập đầy đủ DOM, nghĩa là bạn có thể chèn CSS, thao tác bố cục, hoặc thậm chí chạy JavaScript trước khi rasterize. + +--- + +## Bước 2: Configure Image Rendering Options + +Bây giờ HTML đã nằm trong bộ nhớ, chúng ta cần chỉ cho renderer cách mà hình ảnh cuối cùng sẽ trông như thế nào. Đây là nơi bạn có thể **set font style**, bật antialiasing, hoặc điều chỉnh DPI. Dưới đây là một cấu hình mặc định ổn định, cân bằng giữa chất lượng và tốc độ. + +```csharp +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +// ... + +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + // Smoother curves and text – especially important for vector graphics + UseAntialiasing = true, + + // Improves glyph clarity on Linux and low‑resolution displays + TextOptions = { UseHinting = true }, + + // Demonstrates how to set a combined font style (bold + italic) + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic, + + // Optional: increase DPI for a higher‑resolution PNG (default is 96) + // DpiX = 150, + // DpiY = 150, +}; +``` + +> **Mẹo chuyên nghiệp:** Nếu bạn chỉ cần độ đậm thông thường, bỏ qua các flag `WebFontStyle`. Đối với tiêu đề, bạn có thể chỉ dùng `WebFontStyle.Bold`, trong khi chú thích có thể dùng `WebFontStyle.Italic`. + +--- + +## Bước 3: Render the Page and **Save Rendered Image** as PNG + +Với tài liệu và các tùy chọn đã sẵn sàng, bước cuối cùng là khởi tạo `ImageRenderer` và ghi file đầu ra. Khối `using` đảm bảo các tài nguyên được giải phóng kịp thời. + +```csharp +using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) +{ + // Path where the PNG will be saved – adjust as needed + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); +} +``` + +Khi bạn chạy chương trình, bạn sẽ thấy một file `page.png` trong thư mục dự án chứa một bản sao chính xác của *example.com*. Mở nó bằng bất kỳ trình xem ảnh nào và bạn sẽ nhận thấy kiểu chữ in đậm‑nghiêng mà chúng ta đã yêu cầu trước đó. + +### Expected Output + +``` +✅ Image saved to: C:\Projects\RenderHtml\bin\Debug\net6.0\page.png +``` + +File PNG sẽ có kích thước khoảng 800 × 600 px (tùy thuộc vào kích thước gốc của trang) với các cạnh mượt nhờ antialiasing. + +--- + +## Full Working Example + +Kết hợp tất cả lại, đây là một ứng dụng console tối thiểu mà bạn có thể sao chép‑dán vào `Program.cs`. Nó biên dịch và chạy ngay lập tức. + +```csharp +// Program.cs +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; + +class Program +{ + static void Main() + { + // 1️⃣ Load the target web page + HtmlDocument htmlDoc = new HtmlDocument("https://example.com"); + if (htmlDoc.IsEmpty) + { + Console.WriteLine("Unable to load the URL. Exiting."); + return; + } + + // 2️⃣ Set up rendering options (including font style) + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic + }; + + // 3️⃣ Render and **save rendered image** as PNG + using (var imageRenderer = new ImageRenderer(htmlDoc, renderingOptions)) + { + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "page.png"); + imageRenderer.Save(outputPath); + Console.WriteLine($"✅ Image saved to: {outputPath}"); + } + } +} +``` + +Chạy nó với: + +```bash +dotnet run +``` + +…và bạn sẽ có một PNG mới sẵn sàng để lưu trữ, gửi email, hoặc nhúng vào báo cáo. + +--- + +## Variations & Edge Cases + +### 1. Converting to JPEG Instead of PNG + +Nếu hệ thống downstream của bạn thích JPEG (kích thước file nhỏ hơn, nén mất dữ liệu), chỉ cần thay đổi phần mở rộng file trong `Save`. Aspose.HTML sẽ tự động phát hiện định dạng từ đường dẫn. + +```csharp +imageRenderer.Save("page.jpg"); // JPEG output +``` + +Bạn cũng có thể điều chỉnh chất lượng nén qua `JpegRenderingOptions`. + +### 2. Changing Image Dimensions + +Đôi khi bạn cần một thumbnail thay vì ảnh chụp màn hình đầy đủ. Đặt `ImageSize` trên các tùy chọn: + +```csharp +renderingOptions.ImageSize = new Size(400, 300); // width × height in pixels +``` + +### 3. Handling Authentication‑Protected Pages + +Nếu URL mục tiêu yêu cầu xác thực cơ bản, cung cấp thông tin đăng nhập qua `HttpWebRequest` trước khi tạo `HtmlDocument`. Hoặc, tải HTML bằng tay (sử dụng `HttpClient`) và truyền nó dưới dạng chuỗi: + +```csharp +string html = await new HttpClient().GetStringAsync("https://secure.example.com"); +HtmlDocument doc = new HtmlDocument(html); +``` + +### 4. Using a Custom Font + +Aspose.HTML có thể nhúng các phông chữ cục bộ. Đăng ký thư mục phông chữ trước khi tải tài liệu: + +```csharp +HtmlLoadOptions loadOptions = new HtmlLoadOptions(); +loadOptions.Fonts.AddFolder(@"C:\MyFonts"); +HtmlDocument htmlDoc = new HtmlDocument("https://example.com", loadOptions); +``` + +Bây giờ bất kỳ khai báo `font-family` nào trong trang sẽ được giải quyết tới các tệp tùy chỉnh của bạn. + +### 5. Rendering Multiple Pages in a Loop + +Nếu bạn cần xử lý hàng loạt danh sách URL: + +```csharp +string[] urls = { "https://example.com", "https://contoso.com" }; +int i = 1; +foreach (var url in urls) +{ + HtmlDocument doc = new HtmlDocument(url); + using var renderer = new ImageRenderer(doc, renderingOptions); + renderer.Save($"page_{i++}.png"); +} +``` + +--- + +## Common Pitfalls & How to Avoid Them + +| Triệu chứng | Nguyên nhân có thể | Cách khắc phục | +|-------------|--------------------|----------------| +| File PNG trắng | `HtmlDocument.IsEmpty` true (trang không tải được) | Kiểm tra URL, proxy mạng, đảm bảo TLS 1.2 được bật. | +| Văn bản bị rối trên Linux | Font hinting bị tắt | Đặt `renderingOptions.TextOptions.UseHinting = true;`. | +| Watermark trên đầu ra | Không có giấy phép | Đăng ký giấy phép tạm thời hoặc đầy đủ qua `License license = new License(); license.SetLicense("Aspose.Total.lic");`. | +| Ảnh có độ phân giải thấp | DPI mặc định 96 không đủ cho in | Tăng `renderingOptions.DpiX` và `DpiY` lên 150‑300. | + +--- + +## 🎉 Conclusion + +Chúng ta vừa đi qua mọi thứ bạn cần để **render HTML to image** với Aspose.HTML trong C#. Từ việc tải một trang từ xa, cấu hình antialiasing và **set font style**, đến cuối cùng **save rendered image** dưới dạng PNG, toàn bộ quy trình chỉ mất vài bước ngắn gọn. + +Bây giờ bạn có thể **convert webpage to PNG** ngay lập tức, chèn ảnh chụp màn hình vào báo cáo, hoặc tạo thumbnail cho danh mục—không cần tự động hoá trình duyệt. + +### What’s Next? + +- Thử nghiệm **convert html to png** cho các kích thước màn hình khác nhau (mobile vs desktop). +- Thử xuất ra PDF bằng `PdfRenderer` nếu bạn cần tài liệu có thể in. +- Khám phá các API thao tác DOM của Aspose.HTML để chèn watermark hoặc CSS tùy chỉnh trước khi render. + +Có câu hỏi về các trường hợp đặc biệt, giấy phép, hoặc tối ưu hiệu năng? Hãy để lại bình luận bên dưới, và chúc bạn lập trình vui vẻ! + +--- + + + +{{< /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/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md b/html/vietnamese/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..0e06b47ed --- /dev/null +++ b/html/vietnamese/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-03-14 +description: Kết xuất HTML sang PNG nhanh chóng với Aspose.HTML. Tìm hiểu cách tạo + PNG từ HTML, áp dụng kiểu chữ in đậm và nghiêng, và lưu HTML vào một luồng. +draft: false +keywords: +- render html to png +- bold italic font style +- generate png from html +- convert html to png +- save html to stream +language: vi +og_description: Kết xuất HTML sang PNG với Aspose.HTML. Hướng dẫn này cho thấy cách + tạo PNG từ HTML, sử dụng kiểu chữ in đậm và nghiêng, và lưu HTML vào một luồng. +og_title: Chuyển đổi HTML sang PNG trong C# – Hướng dẫn lập trình chi tiết +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Chuyển đổi HTML sang PNG trong C# – Hướng dẫn từng bước +url: /vi/net/rendering-html-documents/render-html-to-png-in-c-step-by-step-guide/ +--- + +unchanged. + +Also there is a markdown table with description and screenshot. Translate description but keep screenshot URL unchanged. Alt text also. + +Also there are blockquotes with **...** etc. Keep formatting. + +Let's produce final translation. + +We'll start with the same shortcodes lines. + +Proceed. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG in C# – Complete Programming Walkthrough + +Bạn đã bao giờ cần **render HTML to PNG** nhưng không chắc thư viện nào sẽ cho kết quả pixel‑perfect? Bạn không đơn độc. Trong nhiều pipeline web‑to‑image, các nhà phát triển gặp phải vấn đề thiếu phông chữ, văn bản mờ, hoặc câu hỏi “làm sao chụp HTML mà không ghi vào đĩa trước?” + +Thực tế là: Aspose.HTML làm cho toàn bộ quy trình trở nên đơn giản. Trong tutorial này chúng ta sẽ **generate PNG from HTML**, áp dụng **bold italic font style**, và thậm chí **save HTML to a stream** để bạn có thể giữ mọi thứ trong bộ nhớ. Khi kết thúc, bạn sẽ có một ứng dụng console sẵn sàng chạy, chuyển một đoạn HTML nhỏ thành file PNG sắc nét. + +--- + +## What You’ll Need + +- **.NET 6+** (code hoạt động với .NET Core và .NET Framework) +- **Aspose.HTML for .NET** NuGet package – `Install-Package Aspose.HTML` +- Một IDE yêu thích (Visual Studio, Rider, hoặc VS Code) – bất kỳ cái nào cũng được. + +Không cần phông chữ bổ sung, không công cụ bên ngoài, và chắc chắn không có file tạm. Chỉ thuần C#. + +--- + +## Step 1: Create a Simple HTML Document + +Điều đầu tiên chúng ta làm là xây dựng một tài liệu HTML trong bộ nhớ. Hãy nghĩ nó như một trang web ảo chỉ tồn tại trong quá trình của bạn. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using Aspose.Html.Drawing; + +// ... + +// Step 1 – build a tiny HTML page +var htmlDocument = new HtmlDocument(); +var h1 = htmlDocument.CreateElement("h1"); +h1.InnerHtml = "Aspose.HTML demo – render html to png"; +htmlDocument.Body.AppendChild(h1); +``` + +> **Why this matters:** Bằng cách tạo DOM một cách lập trình, bạn tránh được chi phí I/O file và có thể chèn dữ liệu động ngay lập tức. Lớp `HtmlDocument` là điểm vào cho mọi thao tác Aspose.HTML. + +--- + +## Step 2: Save HTML to a Stream + +Thay vì ghi markup ra đĩa, chúng ta nắm bắt nó trong một `ResourceHandler` tùy chỉnh. Đây là phần **save html to stream** của quy trình. + +```csharp +// Simple in‑memory handler – can be swapped for a ZIP or file handler later +class MemoryHandler : ResourceHandler +{ + public string Html { get; private set; } = string.Empty; + + public override Stream HandleResource(ResourceInfo info) + { + // Return an empty stream for HTML; ignore other resources + return info.ResourceType == ResourceType.Html ? new MemoryStream() : Stream.Null; + } + + // Capture the HTML after the document is saved + public override void OnResourceSaved(ResourceInfo info, Stream stream) + { + if (info.ResourceType == ResourceType.Html) + { + stream.Position = 0; + using var reader = new StreamReader(stream); + Html = reader.ReadToEnd(); + } + } +} + +// ... + +var memoryHandler = new MemoryHandler(); +htmlDocument.Save(memoryHandler); +Console.WriteLine($"HTML saved, length = {memoryHandler.Html.Length}"); +``` + +> **Pro tip:** `MemoryHandler` nhỏ gọn nhưng mạnh mẽ. Nếu sau này bạn cần nhúng hình ảnh, CSS, hoặc phông chữ, chỉ cần mở rộng `HandleResource` để trả về các stream thích hợp. + +--- + +## Step 3: Configure Bold Italic Font Style + +Khi render văn bản, bạn thường muốn nó trông giống như trong trình duyệt. Aspose.HTML cho phép bạn thiết lập **bold italic font style** trực tiếp trên các tùy chọn render. + +```csharp +var renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + FontStyle = WebFontStyle.Bold | WebFontStyle.Italic // <-- bold + italic +}; +``` + +> **What’s happening:** +> * `UseAntialiasing` làm mịn các cạnh của hình dạng. +> * `UseHinting` cải thiện vị trí glyph, rất quan trọng đối với văn bản nhỏ. +> * `FontStyle` kết hợp các flag `Bold` và `Italic`, vì vậy mọi đoạn văn bản trong tài liệu sẽ kế thừa kiểu này trừ khi được ghi đè. + +--- + +## Step 4: Render the HTML Document to a PNG Image + +Bây giờ là phần thú vị – chuyển HTML thành file ảnh. `ImageRenderer` sẽ thực hiện toàn bộ công việc nặng. + +```csharp +using var imageRenderer = new ImageRenderer(htmlDocument, renderingOptions); +imageRenderer.Save("output.png"); // change the path as needed +Console.WriteLine("Rendered image saved."); +``` + +Nếu bạn chạy chương trình, sẽ thấy một file có tên `output.png` trong thư mục làm việc. Nó chứa thẻ `` chúng ta đã có một cấu trúc HTML hợp lệ sẵn sàng để lưu. + +> **Mẹo chuyên nghiệp:** Nếu bạn cần một khung HTML đầy đủ (``, `
`, v.v.), Aspose.HTML sẽ tự động tạo nó khi bạn lưu tài liệu, ngay cả khi bạn chỉ thêm nội dung trong body. + +## Bước 2: Triển khai **Custom Resource Handler** – Ghi HTML vào bộ nhớ + +Một *trình xử lý tài nguyên* chỉ định cho Aspose.HTML nơi ghi mỗi tài nguyên (HTML, CSS, hình ảnh, v.v.). Bằng cách ghi đè `HandleResource`, chúng ta có thể chuyển đầu ra HTML tới một `MemoryStream` thay vì tệp. + +```csharp +// Step 2: Define a custom handler that returns a MemoryStream for the main HTML +class MemoryHtmlHandler : ResourceHandler +{ + // Stream that will hold the generated HTML + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // If the resource type is HTML, give back our memory stream. + // All other resources (images, CSS) are ignored for this simple demo. + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } +} +``` + +**Lý do chúng ta dùng trình xử lý tùy chỉnh:** +- **Hiệu năng:** Không có I/O đĩa, mọi thứ ở trong RAM. +- **Bảo mật:** Không có tệp tạm thời có thể bị lộ. +- **Linh hoạt:** Bạn có thể truyền stream này tới phản hồi, cơ sở dữ liệu, hoặc API khác. + +## Bước 3: Lưu tài liệu bằng trình xử lý – Trái tim của **Generate HTML Programmatically** + +Bây giờ chúng ta kết nối tài liệu và trình xử lý lại với nhau. Khi `htmlDoc.Save(handler)` được gọi, Aspose.HTML sẽ gọi `HandleResource`, cung cấp cho chúng ta stream để ghi. + +```csharp +// Step 3: Instantiate the handler and save the document +MemoryHtmlHandler handler = new MemoryHtmlHandler(); +htmlDoc.Save(handler); +``` + +Tại thời điểm này `handler.HtmlStream` chứa các byte HTML thô. Không có gì được ghi ra đĩa, và bạn có thể tái sử dụng stream này bao nhiêu lần tùy thích (chỉ cần nhớ đặt lại vị trí của nó). + +## Bước 4: Đọc HTML đã tạo từ bộ nhớ – Xác minh đầu ra + +Để chứng minh mọi thứ hoạt động, chúng ta đặt lại vị trí của stream về đầu và đọc lại nội dung văn bản. + +```csharp +// Step 4: Reset stream position and read the HTML as a string +handler.HtmlStream.Position = 0; +using (var reader = new StreamReader(handler.HtmlStream)) +{ + string generatedHtml = reader.ReadToEnd(); + System.Console.WriteLine(generatedHtml); +} +``` + +**Kết quả mong đợi** + +```html + + + + +Hello, Aspose.HTML!
+ + +``` + +Nếu bạn thấy markup như trên, chúc mừng — bạn đã **generate html programmatically** thành công bằng Aspose.HTML và một **custom resource handler**. + +## Các biến thể phổ biến & Trường hợp đặc biệt + +### Xử lý CSS hoặc hình ảnh + +Ví dụ này bỏ qua các tài nguyên không phải HTML bằng cách trả về `Stream.Null`. Trong thực tế, bạn có thể muốn ghi lại các tệp CSS hoặc hình ảnh: + +```csharp +public override Stream HandleResource(ResourceInfo info) +{ + switch (info.ResourceType) + { + case ResourceType.Html: + return HtmlStream; + case ResourceType.Css: + // Return a separate MemoryStream for CSS + return CssStream; + case ResourceType.Image: + // Return a stream for each image, perhaps from a cache + return ImageCache.GetStream(info.Uri); + default: + return Stream.Null; + } +} +``` + +### Tái sử dụng cùng một trình xử lý cho nhiều lần lưu + +Nếu bạn cần tạo nhiều đoạn HTML trong một vòng lặp, hãy tạo một `MemoryHtmlHandler` mới cho mỗi lần lặp hoặc xóa sạch stream hiện có: + +```csharp +handler.HtmlStream.SetLength(0); // Clears previous content +htmlDoc.Save(handler); +``` + +### Lưu bất đồng bộ (Aspose.HTML 23.4+) + +Các phiên bản mới hỗ trợ lưu bất đồng bộ: + +```csharp +await htmlDoc.SaveAsync(handler); +``` + +Nhớ `await` và khai báo phương thức của bạn là `async`. + +## Ví dụ đầy đủ hoạt động + +Dưới đây là chương trình hoàn chỉnh mà bạn có thể sao chép‑dán vào một ứng dụng console. Nó bao gồm tất cả các phần chúng ta đã thảo luận, cùng một vài chú thích để dễ hiểu. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +namespace HtmlGenerationDemo +{ + // Custom handler that captures the main HTML in a memory stream + class MemoryHtmlHandler : ResourceHandler + { + public MemoryStream HtmlStream = new MemoryStream(); + + public override Stream HandleResource(ResourceInfo info) + { + // Return the memory stream for HTML; ignore everything else + return info.ResourceType == ResourceType.Html ? HtmlStream : Stream.Null; + } + } + + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the document and add a paragraph + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.Body.AppendChild(htmlDoc.CreateElement("p")).InnerHtml = "Hello, Aspose.HTML!"; + + // 2️⃣ Set up the custom resource handler + MemoryHtmlHandler handler = new MemoryHtmlHandler(); + + // 3️⃣ Save the document – Aspose.HTML writes to our memory stream + htmlDoc.Save(handler); + + // 4️⃣ Read back the generated HTML + handler.HtmlStream.Position = 0; + using (var reader = new StreamReader(handler.HtmlStream)) + { + string result = reader.ReadToEnd(); + Console.WriteLine("=== Generated HTML ==="); + Console.WriteLine(result); + } + + // Keep console open + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +Chạy chương trình (`dotnet run`) và bạn sẽ thấy HTML được in ra console, giống như đã trình bày ở trên. + +## Kết luận + +Chúng ta vừa minh họa cách **tạo tài liệu HTML C#** bằng Aspose.HTML, ghi đầu ra bằng một **custom resource handler**, và **generate HTML programmatically** mà không chạm tới hệ thống tệp. Mẫu này có thể mở rộng — dù bạn đang xây dựng mẫu email, báo cáo động, hay một micro‑service trả về đoạn HTML. + +Bước tiếp theo? Hãy thử thêm một stylesheet CSS qua trình xử lý, hoặc truyền HTML trực tiếp vào phản hồi ASP.NET Core (`await response.Body.WriteAsync(handler.HtmlStream.ToArray())`). Bạn cũng có thể đưa đầu ra này vào bộ chuyển đổi PDF hoặc thư viện chuyển HTML‑to‑image để tạo quy trình làm việc phong phú hơn. + +Có câu hỏi về việc xử lý hình ảnh, lưu bất đồng bộ, hoặc tích hợp với thư viện khác? Hãy để lại bình luận, chúc bạn lập trình vui vẻ! + +{{< /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