diff --git a/html/arabic/net/generate-jpg-and-png-images/_index.md b/html/arabic/net/generate-jpg-and-png-images/_index.md index 432f80cdc0..fbf3bfdb42 100644 --- a/html/arabic/net/generate-jpg-and-png-images/_index.md +++ b/html/arabic/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,7 @@ Aspose.HTML for .NET هي مكتبة قوية تتيح للمطورين إنشا تعلم كيفية تمكين مضاد التعرج عند تحويل ملفات DOCX إلى صور PNG أو JPG باستخدام Aspose.HTML. ### [تحويل docx إلى png – إنشاء أرشيف zip في C# – دليل تعليمي](./convert-docx-to-png-create-zip-archive-c-tutorial/) تعلم كيفية تحويل ملفات docx إلى صور PNG وإنشاء أرشيف ZIP باستخدام C# و Aspose.HTML. +### [تحويل HTML إلى PNG في C# – دليل كامل](./render-html-to-png-in-c-complete-guide/) ## خاتمة diff --git a/html/arabic/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/arabic/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..23182c63ed --- /dev/null +++ b/html/arabic/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,334 @@ +--- +category: general +date: 2026-08-06 +description: تحويل HTML إلى PNG باستخدام Aspose.HTML في C#. تعلّم كيفية تحويل HTML + إلى صورة، وتطبيق أنماط الخطوط، وإزالة التعرجات، وتلميحات النص في مثال واحد قابل + للتنفيذ. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: ar +lastmod: 2026-08-06 +og_description: تحويل HTML إلى PNG باستخدام Aspose.HTML لـ .NET. يوضح هذا البرنامج + التعليمي كيفية تحويل HTML إلى صورة، وتطبيق تنسيق غامق‑مائل، وإزالة التعرجات (التنعيم)، + وتلميحات النص. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: تحويل HTML إلى PNG في C# – خطوة بخطوة باستخدام Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: تحويل HTML إلى PNG في C# – دليل كامل +url: /ar/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحويل HTML إلى PNG في C# – دليل كامل + +إذا كنت بحاجة إلى **render html to png** بسرعة وموثوقية، يوضح لك هذا الدليل بالضبط كيفية القيام بذلك باستخدام Aspose.HTML لـ .NET. ستتعرف أيضًا على كيفية **convert html to image** مع التحكم في نمط الخط، وإزالة التعرج (antialiasing)، وتلميحات النص (text hinting)، بحيث يبدو PNG النهائي واضحًا على أي شاشة. + +سنستعرض جميع الخطوات المطلوبة—من تثبيت حزمة NuGet إلى إنتاج ملف PNG جاهز للإنتاج. في نهاية الدرس ستحصل على برنامج مستقل وقابل للتنفيذ يمكنك إدراجه في أي مشروع C#. + +## ما ستتعلمه + +* كيفية إعداد Aspose.HTML في مشروع .NET. +* كيفية إنشاء مستند HTML في الذاكرة وتطبيق تعداد `WebFontStyle.BoldItalic`. +* كيفية تمكين إزالة التعرج (antialiasing) وتلميحات النص للحصول على عرض أكثر سلاسة. +* كيفية تحويل المستند إلى ملف PNG باستخدام `ImageRenderer`. +* الاختلافات الشائعة مثل التحويل إلى صيغ صور أخرى أو تعديل حجم الإخراج. + +لا تحتاج إلى أدوات خارجية أو خطوات تحويل صور يدوية—كل شيء يتم برمجيًا. + +## المتطلبات المسبقة + +* .NET 6.0 SDK أو أحدث (الكود يعمل أيضًا مع .NET Framework 4.7+). +* Visual Studio 2022 (أو أي بيئة تطوير تدعم C#). +* ترخيص Aspose.HTML لـ .NET ساري (أو مفتاح تقييم مجاني). +* إلمام أساسي بصياغة C#. + +> **نصيحة احترافية:** إذا كنت تستخدم نسخة التقييم المجانية، سيحتوي PNG المُولد على علامة مائية. الترخيص المشتري يزيلها تلقائيًا. + +--- + +## تحويل HTML إلى صورة – إعداد البيئة + +1. **إنشاء مشروع وحدة تحكم جديد** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **إضافة حزمة Aspose.HTML عبر NuGet** + + ```bash + dotnet add package Aspose.HTML + ``` + + هذا الأمر يجلب جميع التجميعات التي تحتاجها لتحويل HTML إلى صور. + +3. **(اختياري) إضافة ملف ترخيص** + + ضع ملف `Aspose.Total.lic` في جذر المشروع وأضف السطر التالي في بداية `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + خطوة الترخيص غير مطلوبة في نسخة التجربة المجانية، لكنها تمنع ظهور العلامة المائية. + +## تحويل HTML إلى PNG باستخدام Aspose.HTML + +جوهر الدرس هو عملية من خمس خطوات تعكس الكود الذي قدمته. يتم شرح كل خطوة بالتفصيل لتفهم **لماذا** الاستدعاء ضروري، وليس فقط **ماذا** يفعل. + +### الخطوة 1: إنشاء مستند HTML + +نبدأ بسلسلة HTML بسيطة تحتوي على فقرة مُنسقة بخط Arial. يتيح لنا استخدام `HTMLDocument` العمل بالكامل في الذاكرة—بدون إنشاء ملفات مؤقتة. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "
Hello
" +); +``` + +*لماذا هذا مهم:* `HTMLDocument` يحلل العلامات ويبني DOM يمكن للعارض استعراضه. بما أن المستند يعيش في الذاكرة، تكون العملية سريعة وآمنة للخطوط المتعددة. + +### الخطوة 2: تطبيق تنسيق غامق‑مائل باستخدام `WebFontStyle` + +تُظهر Aspose.HTML تعداد `WebFontStyle` لدمج قيم CSS الشائعة للوزن والنمط. ضبطه على `BoldItalic` يجعل النص يظهر غامقًا ومائلًا دون كتابة CSS إضافي. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **لماذا نستخدم `WebFontStyle`؟** +> يلغي الحاجة إلى تضمين كتلة نمط أو ورقة أنماط خارجية، مما يقلل كمية HTML التي يجب إدارتها عند تحويل الصور من جانب الخادم. + +### الخطوة 3: تمكين إزالة التعرج للحصول على حواف أكثر سلاسة + +إزالة التعرج (antialiasing) تُنعّم حدود الأشكال والنص، مما يقلل البكسلات المتعرجة خاصةً على الشاشات عالية الدقة (high‑DPI). + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*التأثير:* عندما تكون `UseAntialiasing` مساوية لـ `true`، يطبق العارض خوارزمية تحت‑بكسلية تُنتج PNG أنظف، خاصةً للخطوط المائلة أو الأحجام الصغيرة. + +### الخطوة 4: تفعيل تلميحات النص + +تلميحات النص (text hinting) تُحاذي الحروف إلى شبكة البكسل، مما يجعل الأحرف تبدو أكثر حدة عند الدقة المنخفضة. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*متى تُعطّل:* إذا كنت ستُحوّل ملفات PDF مبنية على المتجهات لاحقًا، قد تتجنب التلميحات للحفاظ على المخطط الأصلي. بالنسبة لإخراج PNG النقطي، تكون التلميحات مفيدة في معظم الحالات. + +### الخطوة 5: تحويل المستند إلى ملف PNG + +أخيرًا، نقوم بإنشاء `ImageRenderer`، نمرر المستند وكائتي الخيارات، ونكتب النتيجة إلى القرص. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +يستمر الاستدعاء حتى يُكتب الملف بالكامل، مما يضمن وجود `output.png` عند انتهاء البرنامج. + +#### النتيجة المتوقعة + +تشغيل البرنامج يُنشئ **output.png** في مجلد المشروع. تُظهر الصورة كلمة **Hello** بخط Arial، غامق‑مائل، مُركزة على خلفية بيضاء، مع حواف ناعمة بفضل إزالة التعرج وتلميحات النص. + +{.img-fluid alt="مثال إخراج تحويل html إلى png"} + +> **ملاحظة:** الصورة أعلاه هي عنصر نائب. في مشروعك الخاص سيعكس PNG HTML الدقيق الذي قدمته. + +--- + +## الكود الكامل القابل للتنفيذ + +فيما يلي ملف `Program.cs` الكامل. انسخه إلى مشروع وحدة التحكم الذي أنشأته مسبقًا، استعد حزم NuGet، وشغّل `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Running the program prints: + +``` +HTML has been rendered to PNG successfully. +``` + +ويُنشئ `output.png` بجوار الملف التنفيذي. + +## الاختلافات والحالات الخاصة + +### التحويل إلى صيغ صور أخرى + +`ImageRenderer` يدعم BMP و GIF و JPEG و TIFF. غيّر امتداد الملف في `RenderToFile` واختياريًا عدّل `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### تعديل حجم الإخراج + +إذا كنت بحاجة إلى PNG بدقة أعلى (مثلاً لشاشات Retina)، اضبط خصائص `ImageWidth` و `ImageHeight`: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +سيقوم العارض بتحويل HTML إلى نقطية بالحجم المحدد مع الحفاظ على جودة المتجه. + +### معالجة CSS المعقد + +Aspose.HTML يدعم بالكامل أوراق الأنماط الخارجية، واستعلامات الوسائط (media queries)، وSVG. فقط قم بتحميل HTML من ملف أو URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +تنطبق نفس سلسلة التحويل، لذا يمكنك **convert html to image** لأي صفحة ويب، وليس فقط السلاسل البسيطة. + +### اعتبارات أمان الخيوط (Thread‑safety) + +`HTMLDocument` و `ImageRenderer` غير آمنين للخطوط المتعددة. إذا كنت تحتاج إلى تحويل عدة صفحات بالتوازي، أنشئ نسخة منفصلة من `HTMLDocument` لكل خيط أو استخدم نمط مجموعة الخيوط (thread‑pool). + +## الأخطاء الشائعة وكيفية تجنّبها + +| المشكلة | سبب حدوثه | الحل | +|-------|----------------|-----| +| PNG فارغ أو يفتقد النص | الخط غير موجود على الخادم | قم بتثبيت الخط المطلوب على الجهاز أو تضمينه عبر CSS `@font-face`. | +| ظهور علامة مائية | استخدام ترخيص تجريبي | استخدم ملف ترخيص صالح (`Aspose.Total.lic`). | +| الإخراج غير واضح | إزالة التعرج مُعطلة | عيّن `imageOptions.UseAntialiasing = true`. | +| النص يبدو رفيعًا | التلميحات مُعطلة | عيّن `textOptions.UseHinting = true`. | + +## الخلاصة + +أصبح لديك الآن حل شامل من البداية إلى النهاية لـ **render html to png** في C#. غطّى الدرس تثبيت Aspose.HTML، إنشاء مستند HTML، تطبيق تنسيق غامق‑مائل، تمكين إزالة التعرج وتلميحات النص، وأخيرًا كتابة ملف PNG إلى القرص. + +من هنا يمكنك استكشاف: + +* **convert html to image** للمعالجة الدفعية لقوالب البريد الإلكتروني. +* التحويل إلى PDF عن طريق استبدال `ImageRenderer` بـ `PdfRenderer`. +* استخدام واجهة DOM الخاصة بـ Aspose.HTML لتعديل HTML قبل التحويل. + +لا تتردد في تجربة CSS مختلف، أو قماش (canvas) أكبر، أو صيغ إخراج بديلة. نتمنى لك تحويلًا سعيدًا! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية استخدام Aspose لتحويل HTML إلى PNG – دليل خطوة بخطوة](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [كيفية تحويل HTML إلى PNG باستخدام Aspose – دليل كامل](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [تحويل HTML إلى PNG في .NET باستخدام Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/chinese/net/generate-jpg-and-png-images/_index.md b/html/chinese/net/generate-jpg-and-png-images/_index.md index 3a7bc53dc3..3f078a5880 100644 --- a/html/chinese/net/generate-jpg-and-png-images/_index.md +++ b/html/chinese/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET 提供了一种将 HTML 转换为图像的简单方法。 了解如何在使用 Aspose.HTML for .NET 将 DOCX 文档转换为 PNG 或 JPG 图像时启用抗锯齿,以提升图像质量。 ### [使用 C# 将 docx 转换为 png 并创建 zip 存档教程](./convert-docx-to-png-create-zip-archive-c-tutorial/) 学习如何使用 C# 将 DOCX 文档转换为 PNG 图像并打包为 ZIP 文件的完整步骤。 +### [在 C# 中将 HTML 渲染为 PNG – 完整指南](./render-html-to-png-in-c-complete-guide/) +本教程详细介绍如何使用 Aspose.HTML for .NET 在 C# 中将 HTML 渲染为 PNG 图像的完整步骤。 ## 结论 diff --git a/html/chinese/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/chinese/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..a74bfc8393 --- /dev/null +++ b/html/chinese/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,334 @@ +--- +category: general +date: 2026-08-06 +description: 使用 Aspose.HTML 在 C# 中将 HTML 渲染为 PNG。学习如何将 HTML 转换为图像、应用字体样式、抗锯齿和文本提示,全部在一个可运行的示例中。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: zh +lastmod: 2026-08-06 +og_description: 使用 Aspose.HTML for .NET 将 HTML 渲染为 PNG。本教程展示如何将 HTML 转换为图像,应用粗斜体样式、抗锯齿和文本提示。 +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: 在 C# 中将 HTML 渲染为 PNG – 使用 Aspose.HTML 的逐步指南 +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: 在 C# 中将 HTML 渲染为 PNG – 完整指南 +url: /zh/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-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**,本指南将向您展示如何使用 Aspose.HTML for .NET 完成此操作。您还将看到如何 **convert html to image**,并控制字体样式、抗锯齿和文字提示,以便最终的 PNG 在任何屏幕上都保持清晰。 + +我们将逐步演示每个必需的步骤——从安装 NuGet 包到生成可投入生产的 PNG 文件。教程结束时,您将拥有一个自包含、可运行的程序,能够直接嵌入任何 C# 项目中。 + +## 您将学习的内容 + +* 如何在 .NET 项目中设置 Aspose.HTML。 +* 如何创建内存中的 HTML 文档并应用 `WebFontStyle.BoldItalic` 枚举。 +* 如何启用抗锯齿和文字提示以获得更平滑的渲染。 +* 如何使用 `ImageRenderer` 将文档渲染为 PNG 文件。 +* 常见的变体,例如渲染为其他图像格式或缩放输出。 + +无需外部工具或手动图像转换步骤——所有操作均通过代码完成。 + +## 前提条件 + +* .NET 6.0 SDK 或更高版本(代码同样适用于 .NET Framework 4.7+)。 +* Visual Studio 2022(或任何支持 C# 的 IDE)。 +* 有效的 Aspose.HTML for .NET 许可证(或免费评估密钥)。 +* 对 C# 语法有基本了解。 + +> **专业提示:** 如果您使用的是免费评估版,生成的 PNG 将包含水印。购买许可证后会自动去除水印。 + +--- + +## 将 html 转换为图像 – 环境设置 + +1. **创建一个新的控制台项目** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **添加 Aspose.HTML NuGet 包** + + ```bash + dotnet add package Aspose.HTML + ``` + + 此命令会拉取渲染 HTML 为图像所需的所有程序集。 + +3. **(可选)添加许可证文件** + + 将您的 `Aspose.Total.lic` 文件放置在项目根目录,并在 `Program.cs` 开头添加以下代码行: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + 许可证步骤对免费试用不是必需的,但它可以防止出现水印。 + +## 使用 Aspose.HTML 将 html 渲染为 png + +本教程的核心是一个五步流程,与你提供的代码相对应。每一步都会详细解释,以便您了解 **为什么** 需要此调用,而不仅仅是 **它做了什么**。 + +### 步骤 1:创建 HTML 文档 + +我们从一个包含使用 Arial 字体样式的段落的最小 HTML 字符串开始。使用 `HTMLDocument` 可以完全在内存中工作——无需创建临时文件。 + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*为什么重要:* `HTMLDocument` 解析标记并构建渲染器可以遍历的 DOM。由于文档驻留在内存中,操作快速且线程安全。 + +### 步骤 2:使用 `WebFontStyle` 应用粗斜体样式 + +Aspose.HTML 提供了 `WebFontStyle` 枚举,用于组合常见的 CSS font‑weight 和 font‑style 值。将其设置为 `BoldItalic` 可使文本同时呈现粗体和斜体,而无需编写额外的 CSS。 + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **为什么使用 `WebFontStyle`?** +> 它消除了嵌入 style 块或外部样式表的需求,减少了在服务器端渲染图像时需要管理的 HTML 量。 + +### 步骤 3:启用抗锯齿以获得更平滑的边缘 + +抗锯齿可以平滑形状和文本的边缘,尤其在高 DPI 显示器上减少锯齿像素。 + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*影响:* 当 `UseAntialiasing` 为 `true` 时,渲染器会使用子像素算法,生成更清晰的 PNG,尤其在对角线或小字号时效果显著。 + +### 步骤 4:激活文字提示 + +文字提示将字形对齐到像素网格,使字符在低分辨率下看起来更清晰。 + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*何时禁用:* 如果您之后要渲染基于矢量的 PDF,可能会跳过提示以保留原始轮廓。对于光栅 PNG 输出,提示几乎总是有益的。 + +### 步骤 5:将文档渲染为 PNG 文件 + +最后,我们创建 `ImageRenderer`,传入文档和两个选项对象,并将输出写入磁盘。 + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +该调用会阻塞,直至文件完全写入,确保程序退出时 `output.png` 已存在。 + +#### 预期输出 + +运行程序后会在项目文件夹中生成 **output.png**。该图像显示了使用 Arial 粗斜体的 **Hello**,居中于白色背景,且因抗锯齿和提示而拥有平滑的边缘。 + +{.img-fluid alt="渲染 html 为 png 示例输出"} + +> **注意:** 上图为占位符。在您自己的项目中,PNG 将反映您提供的确切 HTML。 + +--- + +## 完整、可运行的源代码 + +下面是完整的 `Program.cs` 文件。将其复制到您之前创建的控制台项目中,恢复 NuGet 包,然后运行 `dotnet run`。 + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +运行程序会输出: + +``` +HTML has been rendered to PNG successfully. +``` + +并在可执行文件旁生成 `output.png`。 + +--- + +## 变体和边缘情况 + +### 渲染为其他图像格式 + +`ImageRenderer` 支持 BMP、GIF、JPEG 和 TIFF。修改 `RenderToFile` 中的文件扩展名,并可选地调整 `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### 缩放输出 + +如果需要更高分辨率的 PNG(例如用于视网膜显示),请设置 `ImageWidth` 和 `ImageHeight` 属性: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +渲染器将在指定尺寸下光栅化 HTML,同时保持矢量质量。 + +### 处理复杂的 CSS + +Aspose.HTML 完全支持外部样式表、媒体查询和 SVG。只需从文件或 URL 加载 HTML 即可: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +相同的渲染管道适用,因此您可以 **convert html to image** 任意网页,而不仅限于简单字符串。 + +### 线程安全注意事项 + +`HTMLDocument` 和 `ImageRenderer` 不是线程安全的。如果需要并行渲染多个页面,请为每个线程创建单独的 `HTMLDocument` 实例,或使用线程池模式。 + +--- + +## 常见陷阱及避免方法 + +| 问题 | 产生原因 | 解决方案 | +|-------|----------------|-----| +| PNG 是空白或缺少文字 | 服务器上未找到字体 | 在机器上安装所需字体,或通过 CSS `@font-face` 嵌入字体。 | +| 出现水印 | 使用评估许可证 | 使用有效的许可证文件(`Aspose.Total.lic`)。 | +| 输出模糊 | 抗锯齿未启用 | 设置 `imageOptions.UseAntialiasing = true`。 | +| 文字看起来很细 | 提示未启用 | 设置 `textOptions.UseHinting = true`。 | + +## 结论 + +您现在拥有一个完整、端到端的 **render html to png** C# 解决方案。本教程涵盖了安装 Aspose.HTML、创建 HTML 文档、应用粗斜体样式、启用抗锯齿和文字提示,最后将 PNG 写入磁盘。 + +接下来您可以探索: + +* **Convert html to image** 用于批量处理电子邮件模板。 +* 通过将 `ImageRenderer` 替换为 `PdfRenderer` 来渲染为 PDF。 +* 使用 Aspose.HTML 的 DOM API 在渲染前操作 HTML。 + +随意尝试不同的 CSS、更大的画布或其他输出格式。祝您渲染愉快! + +## 接下来您应该学习什么? + +以下教程涵盖与本指南技术密切相关的主题。每个资源都包含完整的可运行代码示例和逐步说明,帮助您掌握更多 API 功能,并在自己的项目中探索替代实现方案。 + +- [如何使用 Aspose 将 HTML 渲染为 PNG – 步骤指南](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [如何使用 Aspose 将 HTML 渲染为 PNG – 完整指南](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [.NET 中使用 Aspose.HTML 将 HTML 转换为 PNG](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/czech/net/generate-jpg-and-png-images/_index.md b/html/czech/net/generate-jpg-and-png-images/_index.md index 11b9c84651..40c499e199 100644 --- a/html/czech/net/generate-jpg-and-png-images/_index.md +++ b/html/czech/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Naučte se používat Aspose.HTML pro .NET k manipulaci s dokumenty HTML, převo Naučte se, jak při převodu dokumentů DOCX na PNG nebo JPG povolit antialiasing pro hladší výstup. ### [Převod docx na png – vytvoření zip archivu C# tutoriál](./convert-docx-to-png-create-zip-archive-c-tutorial/) Naučte se převést soubory DOCX na PNG a zabalit je do ZIP archivu pomocí C# a Aspose.HTML. +### [Vykreslete HTML do PNG v C# – kompletní průvodce](./render-html-to-png-in-c-complete-guide/) +Kompletní návod, jak pomocí Aspose.HTML pro .NET převést HTML na PNG v jazyce C#. ## Závěr diff --git a/html/czech/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/czech/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..ce70c9ba4d --- /dev/null +++ b/html/czech/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,331 @@ +--- +category: general +date: 2026-08-06 +description: Vykreslete HTML do PNG pomocí Aspose.HTML v C#. Naučte se, jak převést + HTML na obrázek, aplikovat styly písma, antialiasing a hintování textu v jediném + spustitelném příkladu. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: cs +lastmod: 2026-08-06 +og_description: Vykreslete HTML do PNG pomocí Aspose.HTML pro .NET. Tento tutoriál + ukazuje, jak převést HTML na obrázek, použít stylování tučného a kurzívního textu, + antialiasing a hintování textu. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Vykreslete HTML do PNG v C# – krok za krokem s Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: Vykreslení HTML do PNG v C# – kompletní průvodce +url: /cs/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render html do png v C# – kompletní průvodce + +Pokud potřebujete **render html to png** rychle a spolehlivě, tento průvodce vám ukáže přesně, jak to provést pomocí Aspose.HTML pro .NET. Také uvidíte, jak **convert html to image** při řízení stylu písma, antialiasingu a textového hintingu, aby finální PNG vypadalo ostře na jakékoli obrazovce. + +Provedeme vás všemi potřebnými kroky – od instalace NuGet balíčku až po vytvoření produkčně připraveného PNG souboru. Na konci tutoriálu budete mít samostatný, spustitelný program, který můžete vložit do libovolného C# projektu. + +## Co se naučíte + +* Jak nastavit Aspose.HTML v .NET projektu. +* Jak vytvořit HTML dokument v paměti a použít výčtový typ `WebFontStyle.BoldItalic`. +* Jak povolit antialiasing a text hinting pro hladší vykreslování. +* Jak vykreslit dokument do PNG souboru pomocí `ImageRenderer`. +* Běžné varianty, jako je vykreslování do jiných formátů obrázků nebo škálování výstupu. + +Nejsou vyžadovány žádné externí nástroje ani ruční kroky převodu obrázků – vše probíhá programově. + +## Požadavky + +* .NET 6.0 SDK nebo novější (kód také funguje s .NET Framework 4.7+). +* Visual Studio 2022 (nebo jakékoli IDE podporující C#). +* Aktivní licence Aspose.HTML pro .NET (nebo bezplatný evaluační klíč). +* Základní znalost syntaxe C#. + +> **Pro tip:** Pokud používáte bezplatnou evaluační verzi, vygenerovaný PNG bude obsahovat vodoznak. Zakoupená licence jej automaticky odstraní. + +--- + +## Convert html to image – nastavení prostředí + +1. **Create a new console project** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Add the Aspose.HTML NuGet package** + + ```bash + dotnet add package Aspose.HTML + ``` + + This command pulls in all the assemblies you need for rendering HTML to images. + +3. **(Optional) Add a license file** + + (Volitelné) Přidejte licenční soubor. + Umístěte soubor `Aspose.Total.lic` do kořenového adresáře projektu a přidejte následující řádek na začátek souboru `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + +## Render html do png pomocí Aspose.HTML + +Jádrem tutoriálu je pětikrokový proces, který odráží poskytnutý kód. Každý krok je podrobně vysvětlen, abyste pochopili **proč** je volání nutné, nejen **co** dělá. + +### Krok 1: Vytvořte HTML dokument + +Začínáme s minimálním HTML řetězcem, který obsahuje odstavec stylizovaný fontem Arial. Použití `HTMLDocument` nám umožňuje pracovat kompletně v paměti – žádné dočasné soubory nejsou vytvářeny. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Proč je to důležité:* `HTMLDocument` parsuje značkování a vytváří DOM, který může renderer procházet. Protože dokument existuje v paměti, operace je rychlá a thread‑safe. + +### Krok 2: Aplikujte tučné‑kurzívy styl pomocí `WebFontStyle` + +Aspose.HTML poskytuje výčtový typ `WebFontStyle` pro kombinaci běžných hodnot CSS font‑weight a font‑style. Nastavením na `BoldItalic` způsobí, že text bude zároveň tučný a kurzívní bez nutnosti psát další CSS. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Proč použít `WebFontStyle`?** +> Odstraňuje potřebu vkládat blok stylů nebo externí stylesheet, čímž snižuje množství HTML, které musíte spravovat při vykreslování obrázků na serveru. + +### Krok 3: Povolit antialiasing pro hladší hrany + +Antialiasing vyhlazuje okraje tvarů a textu, snižuje zubaté pixely zejména na displejích s vysokým DPI. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Dopad:* Když je `UseAntialiasing` nastaveno na `true`, renderer použije sub‑pixelový algoritmus, který poskytuje čistější PNG, zejména pro diagonální čáry nebo malé velikosti písma. + +### Krok 4: Aktivujte text hinting + +Text hinting zarovnává glyfy k pixelové mřížce, což způsobuje, že znaky vypadají ostřeji při nízkých rozlišeních. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*Kdy vypnout:* Pokud později renderujete vektorové PDF, můžete hinting vynechat, aby byl zachován původní obrys. Pro rasterový PNG výstup je hinting téměř vždy výhodný. + +### Krok 5: Vykreslete dokument do PNG souboru + +Nakonec vytvoříme `ImageRenderer`, předáme dokument a dva objekty s možnostmi a zapíšeme výstup na disk. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +Volání blokuje, dokud není soubor plně zapsán, což zaručuje, že `output.png` existuje při ukončení programu. + +#### Očekávaný výstup + +Spuštěním programu se vytvoří **output.png** ve složce projektu. Obrázek zobrazuje slovo **Hello** v Arial, tučně‑kurzíva, vycentrované na bílém pozadí, s hladkými okraji díky antialiasingu a hintingu. + +{.img-fluid alt="Render html to png example output"} + +> **Poznámka:** Obrázek výše je zástupný. Ve vašem vlastním projektu bude PNG odrážet přesně HTML, které jste poskytli. + +## Kompletní, spustitelný zdrojový kód + +Níže je kompletní soubor `Program.cs`. Zkopírujte jej do konzolového projektu, který jste vytvořili dříve, obnovte NuGet balíčky a spusťte `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Spuštění programu vypíše: + +``` +HTML has been rendered to PNG successfully. +``` + +a vytvoří `output.png` vedle spustitelného souboru. + +## Varianty a okrajové případy + +### Vykreslování do jiných formátů obrázků + +`ImageRenderer` podporuje BMP, GIF, JPEG a TIFF. Změňte příponu souboru v `RenderToFile` a případně upravte `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Škálování výstupu + +Pokud potřebujete PNG s vyšším rozlišením (např. pro Retina displeje), nastavte vlastnosti `ImageWidth` a `ImageHeight`: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +Renderer rasterizuje HTML ve zadané velikosti a zároveň zachová vektorovou kvalitu. + +### Práce s komplexním CSS + +Aspose.HTML plně podporuje externí styly, media queries a SVG. Stačí načíst HTML ze souboru nebo URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +Stejný renderovací pipeline se použije, takže můžete **convert html to image** pro jakoukoli webovou stránku, nejen pro jednoduché řetězce. + +### Úvahy o thread‑safety + +`HTMLDocument` a `ImageRenderer` nejsou thread‑safe. Pokud potřebujete renderovat mnoho stránek paralelně, vytvořte samostatnou instanci `HTMLDocument` pro každý vlákno nebo použijte vzor thread‑pool. + +## Běžné úskalí a jak se jim vyhnout + +| Problém | Proč k tomu dochází | Řešení | +|-------|----------------|-----| +| PNG je prázdný nebo chybí text | Písmo nebylo nalezeno na serveru | Nainstalujte požadované písmo na stroj nebo jej vložte pomocí CSS `@font-face`. | +| Objevuje se vodoznak | Použita evaluační licence | Použijte platný licenční soubor (`Aspose.Total.lic`). | +| Výstup je rozmazaný | Antialiasing je vypnutý | Nastavte `imageOptions.UseAntialiasing = true`. | +| Text vypadá tenký | Hinting je vypnutý | Nastavte `textOptions.UseHinting = true`. | + +## Závěr + +Nyní máte robustní end‑to‑end řešení pro **render html to png** v C#. Tutoriál pokryl instalaci Aspose.HTML, vytvoření HTML dokumentu, aplikaci tučně‑kurzívy stylu, povolení antialiasingu a text hintingu a nakonec zápis PNG souboru na disk. + +Odtud můžete dále zkoumat: + +* **Convert html to image** pro dávkové zpracování e‑mailových šablon. +* Renderování do PDF výměnou `ImageRenderer` za `PdfRenderer`. +* Použití DOM API Aspose.HTML k manipulaci s HTML před renderováním. + +Neváhejte experimentovat s různým CSS, většími plátny nebo alternativními výstupními formáty. Šťastné renderování! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Convert HTML to PNG in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/dutch/net/generate-jpg-and-png-images/_index.md b/html/dutch/net/generate-jpg-and-png-images/_index.md index e05f0c0a7d..b87c78f2ea 100644 --- a/html/dutch/net/generate-jpg-and-png-images/_index.md +++ b/html/dutch/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Leer hoe u Aspose.HTML voor .NET kunt gebruiken om HTML-documenten te bewerken, Leer hoe u antialiasing inschakelt bij het omzetten van DOCX-bestanden naar PNG- of JPG-afbeeldingen met Aspose.HTML. ### [docx naar png converteren – zip-archief maken C#-tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Leer hoe u een DOCX-bestand naar PNG converteert en de resultaten in een zip-archief opslaat met C# en Aspose.HTML. +### [Render html naar png in C# – volledige gids](./render-html-to-png-in-c-complete-guide/) +Leer stap voor stap hoe u HTML naar PNG rendert in C# met Aspose.HTML, inclusief codevoorbeelden en configuratie. ## Conclusie diff --git a/html/dutch/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/dutch/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..d0f690b97a --- /dev/null +++ b/html/dutch/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,336 @@ +--- +category: general +date: 2026-08-06 +description: Render html naar png met Aspose.HTML in C#. Leer hoe je html naar afbeelding + kunt converteren, lettertype‑stijlen, anti‑aliasing en tekst‑hinting kunt toepassen + in één uitvoerbaar voorbeeld. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: nl +lastmod: 2026-08-06 +og_description: Render html naar png met Aspose.HTML voor .NET. Deze tutorial laat + zien hoe je html naar afbeelding converteert, vet‑cursieve opmaak toepast, antialiasing + en teksthinting. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Render html naar png in C# – stap‑voor‑stap met Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: HTML renderen naar PNG in C# – volledige gids +url: /nl/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render html naar png in C# – volledige gids + +Als je snel en betrouwbaar **html naar png wilt renderen**, laat deze gids je precies zien hoe je dat doet met Aspose.HTML voor .NET. Je ziet ook hoe je **html naar afbeelding kunt converteren** terwijl je de lettertype‑stijl, antialiasing en text hinting regelt, zodat de uiteindelijke PNG er scherp uitziet op elk scherm. + +We lopen elke vereiste stap door — van het installeren van het NuGet‑pakket tot het produceren van een productie‑klare PNG‑bestand. Aan het einde van de tutorial heb je een zelfstandige, uitvoerbare programma dat je in elk C#‑project kunt plaatsen. + +## Wat je zult leren + +* Hoe je Aspose.HTML instelt in een .NET‑project. +* Hoe je een in‑memory HTML‑document maakt en de `WebFontStyle.BoldItalic`‑enum toepast. +* Hoe je antialiasing en text hinting inschakelt voor vloeiendere weergave. +* Hoe je het document rendert naar een PNG‑bestand met `ImageRenderer`. +* Veelvoorkomende variaties zoals renderen naar andere afbeeldingsformaten of het schalen van de output. + +Er zijn geen externe tools of handmatige afbeeldingsconversiestappen nodig — alles gebeurt programmatisch. + +## Vereisten + +* .NET 6.0 SDK of later (de code werkt ook met .NET Framework 4.7+). +* Visual Studio 2022 (of een IDE die C# ondersteunt). +* Een actieve Aspose.HTML for .NET‑licentie (of een gratis evaluatiesleutel). +* Basiskennis van C#‑syntaxis. + +> **Pro tip:** Als je de gratis evaluatie gebruikt, zal de gegenereerde PNG een watermerk bevatten. Een aangeschafte licentie verwijdert dit automatisch. + +--- + +## Convert html naar afbeelding – de omgeving instellen + +1. **Maak een nieuw console‑project** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Voeg het Aspose.HTML NuGet‑pakket toe** + + ```bash + dotnet add package Aspose.HTML + ``` + + Dit commando haalt alle assemblies op die je nodig hebt voor het renderen van HTML naar afbeeldingen. + +3. **(Optioneel) Voeg een licentiebestand toe** + + Plaats je `Aspose.Total.lic`‑bestand in de project‑root en voeg de volgende regel toe aan het begin van `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + De licentiestap is niet vereist voor de gratis proefversie, maar voorkomt het watermerk. + +## Render html naar png met Aspose.HTML + +De kern van de tutorial is een proces van vijf stappen dat de code die je hebt opgegeven weerspiegelt. Elke stap wordt in detail uitgelegd zodat je begrijpt **waarom** de aanroep nodig is, en niet alleen **wat** het doet. + +### Stap 1: Maak het HTML‑document + +We beginnen met een minimale HTML‑string die een alinea bevat met het lettertype Arial. Met `HTMLDocument` kunnen we volledig in het geheugen werken — er worden geen tijdelijke bestanden aangemaakt. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Waarom dit belangrijk is:* `HTMLDocument` parseert de markup en bouwt een DOM op die de renderer kan doorlopen. Omdat het document in het geheugen leeft, is de bewerking snel en thread‑safe. + +### Stap 2: Pas vet‑cursieve opmaak toe met `WebFontStyle` + +Aspose.HTML biedt de `WebFontStyle`‑enumeratie om veelvoorkomende CSS‑font‑weight‑ en font‑style‑waarden te combineren. Door deze op `BoldItalic` te zetten, verschijnt de tekst zowel vet als cursief zonder extra CSS te schrijven. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Waarom `WebFontStyle` gebruiken?** +> Het elimineert de noodzaak om een style‑block of extern stylesheet in te sluiten, waardoor de hoeveelheid HTML die je moet beheren bij het renderen van server‑side afbeeldingen wordt verminderd. + +### Stap 3: Schakel antialiasing in voor vloeiendere randen + +Antialiasing maakt de randen van vormen en tekst gladder, waardoor gekartelde pixels worden verminderd, vooral op high‑DPI‑schermen. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Impact:* Wanneer `UseAntialiasing` `true` is, past de renderer een sub‑pixel‑algoritme toe dat een schonere PNG oplevert, vooral voor diagonale lijnen of kleine lettergroottes. + +### Stap 4: Activeer text hinting + +Text hinting legt glyphs uit op het pixelraster, waardoor tekens scherper lijken bij lage resoluties. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*Wanneer uit te schakelen:* Als je later vector‑gebaseerde PDF's rendert, kun je hinting overslaan om de originele omtrek te behouden. Voor raster‑PNG‑output is hinting bijna altijd voordelig. + +### Stap 5: Render het document naar een PNG‑bestand + +Tot slot maken we een `ImageRenderer`, geven we het document en de twee optionele objecten door, en schrijven we de output naar schijf. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +De aanroep blokkeert tot het bestand volledig is geschreven, waardoor gegarandeerd wordt dat `output.png` bestaat wanneer het programma eindigt. + +#### Verwachte output + +Het uitvoeren van het programma maakt **output.png** aan in de projectmap. De afbeelding toont het woord **Hello** in Arial, vet‑cursief, gecentreerd op een witte achtergrond, met gladde randen dankzij antialiasing en hinting. + +{.img-fluid alt="Render html naar png voorbeeldoutput"} + +> **Opmerking:** De bovenstaande afbeelding is een tijdelijke aanduiding. In je eigen project zal de PNG de exacte HTML weergeven die je hebt opgegeven. + +--- + +## Volledige, uitvoerbare broncode + +Hieronder staat het volledige `Program.cs`‑bestand. Kopieer het naar het console‑project dat je eerder hebt aangemaakt, herstel de NuGet‑pakketten, en voer `dotnet run` uit. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Het uitvoeren van het programma geeft het volgende weer: + +``` +HTML has been rendered to PNG successfully. +``` + +en maakt `output.png` aan naast het uitvoerbare bestand. + +--- + +## Variaties en randgevallen + +### Renderen naar andere afbeeldingsformaten + +`ImageRenderer` ondersteunt BMP, GIF, JPEG en TIFF. Verander de bestandsextensie in `RenderToFile` en pas eventueel `ImageRenderingOptions` aan: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Schalen van de output + +Als je een PNG met hogere resolutie nodig hebt (bijv. voor retina‑schermen), stel je de eigenschappen `ImageWidth` en `ImageHeight` in: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +De renderer rastert de HTML op de opgegeven grootte terwijl de vectorkwaliteit behouden blijft. + +### Omgaan met complexe CSS + +Aspose.HTML ondersteunt volledig externe stylesheets, media queries en SVG. Laad gewoon de HTML vanuit een bestand of URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +Dezelfde render‑pipeline is van toepassing, zodat je **html naar afbeelding kunt converteren** voor elke webpagina, niet alleen eenvoudige strings. + +### Overwegingen omtrent thread‑veiligheid + +`HTMLDocument` en `ImageRenderer` zijn niet thread‑safe. Als je veel pagina's parallel moet renderen, maak dan een aparte `HTMLDocument`‑instantie per thread of gebruik een thread‑pool‑patroon. + +## Veelvoorkomende valkuilen en hoe ze te vermijden + +| Probleem | Waarom het gebeurt | Oplossing | +|----------|--------------------|-----------| +| PNG is leeg of mist tekst | Lettertype niet gevonden op de server | Installeer het vereiste lettertype op de machine of embed het via CSS `@font-face`. | +| Watermerk verschijnt | Evaluatielicentie gebruikt | Pas een geldige licentiebestand toe (`Aspose.Total.lic`). | +| Uitvoer is onscherp | Antialiasing uitgeschakeld | Stel `imageOptions.UseAntialiasing = true` in. | +| Tekst ziet er dun uit | Hinting uitgeschakeld | Stel `textOptions.UseHinting = true` in. | + +## Conclusie + +Je hebt nu een solide, end‑to‑end oplossing om **html naar png te renderen** in C#. De tutorial behandelde het installeren van Aspose.HTML, het maken van een HTML‑document, het toepassen van vet‑cursieve opmaak, het inschakelen van antialiasing en text hinting, en tenslotte het schrijven van een PNG‑bestand naar schijf. + +Vanaf hier kun je verkennen: + +* **html naar afbeelding converteren** voor batchverwerking van e‑mailtemplates. +* Renderen naar PDF door `ImageRenderer` te vervangen door `PdfRenderer`. +* Gebruik van Aspose.HTML’s DOM‑API om HTML te manipuleren vóór het renderen. + +Voel je vrij om te experimenteren met verschillende CSS, grotere canvassen, of alternatieve uitvoerformaten. Veel renderplezier! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe Aspose te gebruiken om HTML naar PNG te renderen – Stapsgewijze gids](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Hoe HTML naar PNG te renderen met Aspose – Complete gids](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [HTML naar PNG converteren in .NET met Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/english/net/generate-jpg-and-png-images/_index.md b/html/english/net/generate-jpg-and-png-images/_index.md index 3cc4b6acdf..a170b9d07a 100644 --- a/html/english/net/generate-jpg-and-png-images/_index.md +++ b/html/english/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Learn to use Aspose.HTML for .NET to manipulate HTML documents, convert HTML to Learn how to enable antialiasing for sharper PNG/JPG output when converting DOCX files using Aspose.HTML for .NET. ### [convert docx to png – create zip archive c# tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Learn how to convert DOCX files to PNG images and package them into a ZIP archive using C# and Aspose.HTML. +### [Render html to png in C# – complete guide](./render-html-to-png-in-c-complete-guide/) +A comprehensive guide on rendering HTML to PNG using C# and Aspose.HTML, covering setup, code examples, and optimization tips. ## Conclusion diff --git a/html/english/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/english/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..45ff9d69f6 --- /dev/null +++ b/html/english/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,342 @@ +--- +category: general +date: 2026-08-06 +description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: en +lastmod: 2026-08-06 +og_description: Render html to png using Aspose.HTML for .NET. This tutorial shows + how to convert html to image, apply bold‑italic styling, antialiasing, and text + hinting. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Render html to png in C# – step‑by‑step with Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: Render html to png in C# – complete guide +url: /net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-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 guide + +If you need to **render html to png** quickly and reliably, this guide shows you exactly how to do it with Aspose.HTML for .NET. You’ll also see how to **convert html to image** while controlling font style, antialiasing, and text hinting, so the final PNG looks sharp on any screen. + +We’ll walk through every required step—from installing the NuGet package to producing a production‑ready PNG file. By the end of the tutorial you’ll have a self‑contained, runnable program that you can drop into any C# project. + +## What you’ll learn + +* How to set up Aspose.HTML in a .NET project. +* How to create an in‑memory HTML document and apply the `WebFontStyle.BoldItalic` enum. +* How to enable antialiasing and text hinting for smoother rendering. +* How to render the document to a PNG file using `ImageRenderer`. +* Common variations such as rendering to other image formats or scaling the output. + +No external tools or manual image conversion steps are required—everything happens programmatically. + +## Prerequisites + +* .NET 6.0 SDK or later (the code also works with .NET Framework 4.7+). +* Visual Studio 2022 (or any IDE that supports C#). +* An active Aspose.HTML for .NET license (or a free evaluation key). +* Basic familiarity with C# syntax. + +> **Pro tip:** If you are using the free evaluation, the generated PNG will contain a watermark. A purchased license removes it automatically. + +--- + +## Convert html to image – setting up the environment + +1. **Create a new console project** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Add the Aspose.HTML NuGet package** + + ```bash + dotnet add package Aspose.HTML + ``` + + This command pulls in all the assemblies you need for rendering HTML to images. + +3. **(Optional) Add a license file** + + Place your `Aspose.Total.lic` file in the project root and add the following line at the start of `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + The license step is not required for the free trial, but it prevents the watermark. + +## Render html to png with Aspose.HTML + +The core of the tutorial is a five‑step process that mirrors the code you provided. Each step is explained in detail so you understand **why** the call is necessary, not just **what** it does. + +### Step 1: Create the HTML document + +We start with a minimal HTML string that contains a paragraph styled with the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary files are created. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Why this matters:* `HTMLDocument` parses the markup and builds a DOM that the renderer can traverse. Because the document lives in memory, the operation is fast and thread‑safe. + +### Step 2: Apply bold‑italic styling with `WebFontStyle` + +Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS font‑weight and font‑style values. Setting it to `BoldItalic` makes the text appear both bold and italic without writing additional CSS. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Why use `WebFontStyle`?** +> It eliminates the need to embed a style block or external stylesheet, reducing the amount of HTML you have to manage when rendering server‑side images. + +### Step 3: Enable antialiasing for smoother edges + +Antialiasing smooths the borders of shapes and text, reducing jagged pixels especially on high‑DPI displays. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Impact:* When `UseAntialiasing` is `true`, the renderer applies a sub‑pixel algorithm that yields a cleaner PNG, particularly for diagonal lines or small font sizes. + +### Step 4: Activate text hinting + +Text hinting aligns glyphs to the pixel grid, making characters look sharper at low resolutions. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*When to disable:* If you are rendering vector‑based PDFs later, you might skip hinting to preserve the original outline. For raster PNG output, hinting is almost always beneficial. + +### Step 5: Render the document to a PNG file + +Finally, we create an `ImageRenderer`, pass the document and the two option objects, and write the output to disk. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +The call blocks until the file is fully written, guaranteeing that `output.png` exists when the program exits. + +#### Expected output + +Running the program creates **output.png** in the project folder. The image shows the word **Hello** in Arial, bold‑italic, centered on a white background, with smooth edges thanks to antialiasing and hinting. + +{.img-fluid alt="Render html to png example output"} + +> **Note:** The image above is a placeholder. In your own project the PNG will reflect the exact HTML you supplied. + +--- + +## Full, runnable source code + +Below is the complete `Program.cs` file. Copy it into the console project you created earlier, restore NuGet packages, and run `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Running the program prints: + +``` +HTML has been rendered to PNG successfully. +``` + +and creates `output.png` next to the executable. + +--- + +## Variations and edge cases + +### Rendering to other image formats + +`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension in `RenderToFile` and optionally adjust `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Scaling the output + +If you need a higher‑resolution PNG (e.g., for retina displays), set the `ImageWidth` and `ImageHeight` properties: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +The renderer will rasterize the HTML at the specified size while preserving vector quality. + +### Handling complex CSS + +Aspose.HTML fully supports external stylesheets, media queries, and SVG. Just load the HTML from a file or URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +The same rendering pipeline applies, so you can **convert html to image** for any web page, not only simple strings. + +### Thread‑safety considerations + +`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to render many pages in parallel, create a separate `HTMLDocument` instance per thread or use a thread‑pool pattern. + +--- + +## Common pitfalls and how to avoid them + +| Issue | Why it happens | Fix | +|-------|----------------|-----| +| PNG is blank or missing text | Font not found on the server | Install the required font on the machine or embed it via CSS `@font-face`. | +| Watermark appears | Evaluation license used | Apply a valid license file (`Aspose.Total.lic`). | +| Output is blurry | Antialiasing disabled | Set `imageOptions.UseAntialiasing = true`. | +| Text looks thin | Hinting disabled | Set `textOptions.UseHinting = true`. | + +--- + +## Conclusion + +You now have a solid, end‑to‑end solution to **render html to png** in C#. The tutorial covered installing Aspose.HTML, creating an HTML document, applying bold‑italic styling, enabling antialiasing and text hinting, and finally writing a PNG file to disk. + +From here you can explore: + +* **Convert html to image** for batch processing of email templates. +* Rendering to PDF by swapping `ImageRenderer` with `PdfRenderer`. +* Using Aspose.HTML’s DOM API to manipulate HTML before rendering. + +Feel free to experiment with different CSS, larger canvases, or alternative output formats. Happy rendering! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Convert HTML to PNG in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/english/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/og-image.png b/html/english/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/og-image.png new file mode 100644 index 0000000000..d5aa675c5c Binary files /dev/null and b/html/english/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/og-image.png differ diff --git a/html/french/net/generate-jpg-and-png-images/_index.md b/html/french/net/generate-jpg-and-png-images/_index.md index 59ca2dad12..914cf9a861 100644 --- a/html/french/net/generate-jpg-and-png-images/_index.md +++ b/html/french/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Apprenez à utiliser Aspose.HTML pour .NET pour manipuler des documents HTML, co Apprenez à activer l'anticrénelage pour améliorer la qualité des images PNG/JPG générées à partir de documents DOCX avec Aspose.HTML. ### [Convertir docx en png – créer une archive zip tutoriel C#](./convert-docx-to-png-create-zip-archive-c-tutorial/) Apprenez à convertir des fichiers DOCX en images PNG et à les compresser dans une archive ZIP avec C#. +### [Rendu HTML en PNG en C# – guide complet](./render-html-to-png-in-c-complete-guide/) +Apprenez à convertir du HTML en images PNG avec C# grâce à un guide complet pas à pas. ## Conclusion diff --git a/html/french/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/french/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..35e4930278 --- /dev/null +++ b/html/french/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,332 @@ +--- +category: general +date: 2026-08-06 +description: Rendre le HTML en PNG avec Aspose.HTML en C#. Apprenez comment convertir + le HTML en image, appliquer les styles de police, l'anticrénelage et le hinting + du texte dans un exemple unique et exécutable. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: fr +lastmod: 2026-08-06 +og_description: Rendre le HTML en PNG avec Aspose.HTML pour .NET. Ce tutoriel montre + comment convertir le HTML en image, appliquer le style gras‑italique, l'anticrénelage + et le hinting du texte. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Rendre le HTML en PNG en C# – étape par étape avec Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: Rendre le HTML en PNG avec C# – guide complet +url: /fr/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Rendu html en png en C# – guide complet + +Si vous devez **rendre html en png** rapidement et de manière fiable, ce guide vous montre exactement comment le faire avec Aspose.HTML pour .NET. Vous verrez également comment **convertir html en image** tout en contrôlant le style de police, l'anticrénelage et le hinting du texte, afin que le PNG final soit net sur n'importe quel écran. + +Nous parcourrons chaque étape requise — de l'installation du package NuGet à la production d'un fichier PNG prêt pour la production. À la fin du tutoriel, vous disposerez d'un programme autonome et exécutable que vous pourrez intégrer à n'importe quel projet C#. + +## Ce que vous allez apprendre + +* Comment configurer Aspose.HTML dans un projet .NET. +* Comment créer un document HTML en mémoire et appliquer l'énumération `WebFontStyle.BoldItalic`. +* Comment activer l'anticrénelage et le hinting du texte pour un rendu plus fluide. +* Comment rendre le document en fichier PNG à l'aide de `ImageRenderer`. +* Variantes courantes telles que le rendu vers d'autres formats d'image ou le redimensionnement de la sortie. + +Aucun outil externe ou étape de conversion d'image manuelle n'est requis — tout se fait programmatiquement. + +## Prérequis + +* SDK .NET 6.0 ou ultérieur (le code fonctionne également avec .NET Framework 4.7+). +* Visual Studio 2022 (ou tout IDE supportant C#). +* Une licence active d'Aspose.HTML pour .NET (ou une clé d'évaluation gratuite). +* Familiarité de base avec la syntaxe C#. + +> **Conseil de pro :** Si vous utilisez l'évaluation gratuite, le PNG généré contiendra un filigrane. Une licence achetée le supprime automatiquement. + +--- + +## Convertir html en image – configuration de l'environnement + +1. **Créer un nouveau projet console** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Ajouter le package NuGet Aspose.HTML** + + ```bash + dotnet add package Aspose.HTML + ``` + + Cette commande récupère toutes les assemblées dont vous avez besoin pour rendre le HTML en images. + +3. **(Optionnel) Ajouter un fichier de licence** + + Placez votre fichier `Aspose.Total.lic` à la racine du projet et ajoutez la ligne suivante au début de `Program.cs` : + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + L'étape de licence n'est pas requise pour l'essai gratuit, mais elle empêche le filigrane. + +## Rendre html en png avec Aspose.HTML + +Le cœur du tutoriel est un processus en cinq étapes qui reflète le code que vous avez fourni. Chaque étape est expliquée en détail afin que vous compreniez **pourquoi** l'appel est nécessaire, et pas seulement **ce que** il fait. + +### Étape 1 : Créer le document HTML + +Nous commençons avec une chaîne HTML minimale contenant un paragraphe stylisé avec la police Arial. L'utilisation de `HTMLDocument` nous permet de travailler entièrement en mémoire — aucun fichier temporaire n'est créé. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Pourquoi c'est important :* `HTMLDocument` analyse le balisage et construit un DOM que le moteur de rendu peut parcourir. Comme le document vit en mémoire, l'opération est rapide et thread‑safe. + +### Étape 2 : Appliquer le style gras‑italique avec `WebFontStyle` + +Aspose.HTML expose l'énumération `WebFontStyle` pour combiner les valeurs courantes de `font-weight` et `font-style` en CSS. La définir sur `BoldItalic` rend le texte à la fois gras et italique sans écrire de CSS supplémentaire. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Pourquoi utiliser `WebFontStyle` ?** +> Cela élimine le besoin d'intégrer un bloc de style ou une feuille de style externe, réduisant ainsi la quantité de HTML à gérer lors du rendu d'images côté serveur. + +### Étape 3 : Activer l'anticrénelage pour des bords plus lisses + +L'anticrénelage lisse les bordures des formes et du texte, réduisant les pixels irréguliers, notamment sur les écrans haute‑DPI. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Impact :* Lorsque `UseAntialiasing` est `true`, le moteur de rendu applique un algorithme sous‑pixel qui produit un PNG plus net, en particulier pour les lignes diagonales ou les petites tailles de police. + +### Étape 4 : Activer le hinting du texte + +Le hinting du texte aligne les glyphes sur la grille de pixels, rendant les caractères plus nets à basse résolution. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*Quand désactiver :* Si vous rendez plus tard des PDF basés sur le vecteur, vous pouvez ignorer le hinting pour préserver le contour original. Pour une sortie PNG raster, le hinting est presque toujours bénéfique. + +### Étape 5 : Rendre le document en fichier PNG + +Enfin, nous créons un `ImageRenderer`, transmettons le document ainsi que les deux objets d'options, et écrivons la sortie sur le disque. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +L'appel bloque jusqu'à ce que le fichier soit entièrement écrit, garantissant que `output.png` existe lorsque le programme se termine. + +#### Sortie attendue + +L'exécution du programme crée **output.png** dans le dossier du projet. L'image montre le mot **Hello** en Arial, gras‑italique, centré sur un fond blanc, avec des bords lisses grâce à l'anticrénelage et au hinting. + +{.img-fluid alt="Exemple de sortie de rendu html en png"} + +> **Note :** L'image ci‑dessus est un espace réservé. Dans votre propre projet, le PNG reflétera le HTML exact que vous avez fourni. + +## Code source complet et exécutable + +Ci‑dessous se trouve le fichier complet `Program.cs`. Copiez‑le dans le projet console que vous avez créé précédemment, restaurez les packages NuGet, et exécutez `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Running the program prints: + +``` +HTML has been rendered to PNG successfully. +``` + +et crée `output.png` à côté de l'exécutable. + +## Variantes et cas particuliers + +### Rendu vers d'autres formats d'image + +`ImageRenderer` prend en charge BMP, GIF, JPEG et TIFF. Changez l'extension du fichier dans `RenderToFile` et ajustez éventuellement `ImageRenderingOptions` : + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Redimensionner la sortie + +Si vous avez besoin d'un PNG à plus haute résolution (par ex., pour les écrans Retina), définissez les propriétés `ImageWidth` et `ImageHeight` : + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +Le moteur de rendu rasterisera le HTML à la taille spécifiée tout en préservant la qualité vectorielle. + +### Gestion de CSS complexes + +Aspose.HTML prend entièrement en charge les feuilles de style externes, les media queries et le SVG. Chargez simplement le HTML depuis un fichier ou une URL : + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +Le même pipeline de rendu s'applique, vous pouvez donc **convertir html en image** pour n'importe quelle page web, pas seulement les chaînes simples. + +### Considérations de thread‑safety + +`HTMLDocument` et `ImageRenderer` ne sont pas thread‑safe. Si vous devez rendre de nombreuses pages en parallèle, créez une instance séparée de `HTMLDocument` par thread ou utilisez un modèle de pool de threads. + +## Pièges courants et comment les éviter + +| Problème | Pourquoi cela se produit | Solution | +|----------|--------------------------|----------| +| Le PNG est vide ou le texte manque | Police introuvable sur le serveur | Installez la police requise sur la machine ou intégrez‑la via CSS `@font-face`. | +| Le filigrane apparaît | Licence d'évaluation utilisée | Appliquez un fichier de licence valide (`Aspose.Total.lic`). | +| La sortie est floue | Anticrénelage désactivé | Définissez `imageOptions.UseAntialiasing = true`. | +| Le texte paraît fin | Hinting désactivé | Définissez `textOptions.UseHinting = true`. | + +## Conclusion + +Vous disposez maintenant d'une solution complète, de bout en bout, pour **rendre html en png** en C#. Le tutoriel a couvert l'installation d'Aspose.HTML, la création d'un document HTML, l'application du style gras‑italique, l'activation de l'anticrénelage et du hinting du texte, et enfin l'écriture d'un fichier PNG sur le disque. + +À partir d'ici, vous pouvez explorer : + +* **Convertir html en image** pour le traitement par lots de modèles d'e‑mail. +* Rendre en PDF en remplaçant `ImageRenderer` par `PdfRenderer`. +* Utiliser l'API DOM d'Aspose.HTML pour manipuler le HTML avant le rendu. + +N'hésitez pas à expérimenter avec différents CSS, des canevas plus grands, ou des formats de sortie alternatifs. Bon rendu ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s'appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités d'API supplémentaires et à explorer des approches d'implémentation alternatives dans vos propres projets. + +- [Comment utiliser Aspose pour rendre HTML en PNG – Guide étape par étape](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Comment rendre HTML en PNG avec Aspose – Guide complet](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Convertir HTML en PNG en .NET avec Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/german/net/generate-jpg-and-png-images/_index.md b/html/german/net/generate-jpg-and-png-images/_index.md index 8c24c45378..3f20f1f1d2 100644 --- a/html/german/net/generate-jpg-and-png-images/_index.md +++ b/html/german/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML-Dokumente bearbeiten, HTML Erfahren Sie, wie Sie beim Konvertieren von DOCX-Dokumenten in PNG oder JPG Antialiasing aktivieren, um hochwertige Bilder zu erhalten. ### [DOCX in PNG konvertieren – ZIP-Archiv erstellen C#‑Tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Erfahren Sie, wie Sie DOCX‑Dateien in PNG‑Bilder umwandeln und diese in ein ZIP‑Archiv packen – Schritt‑für‑Schritt‑Anleitung in C#. +### [HTML in PNG rendern in C# – vollständige Anleitung](./render-html-to-png-in-c-complete-guide/) +Erfahren Sie, wie Sie HTML mit Aspose.HTML in C# vollständig in PNG-Bilder konvertieren. ## Abschluss diff --git a/html/german/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/german/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..673793abb4 --- /dev/null +++ b/html/german/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,340 @@ +--- +category: general +date: 2026-08-06 +description: Rendern Sie HTML zu PNG mit Aspose.HTML in C#. Erfahren Sie, wie Sie + HTML in ein Bild konvertieren, Schriftstile, Antialiasing und Text‑Hinting in einem + einzigen, ausführbaren Beispiel anwenden. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: de +lastmod: 2026-08-06 +og_description: Rendern Sie HTML zu PNG mit Aspose.HTML für .NET. Dieses Tutorial + zeigt, wie man HTML in ein Bild konvertiert, fett‑kursiven Stil anwendet, Antialiasing + und Text‑Hinting verwendet. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: HTML in C# zu PNG rendern – Schritt für Schritt mit Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: HTML zu PNG rendern in C# – vollständiger Leitfaden +url: /de/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render html to png in C# – vollständige Anleitung + +Wenn Sie **HTML schnell und zuverlässig in PNG rendern** möchten, zeigt Ihnen diese Anleitung genau, wie das mit Aspose.HTML für .NET funktioniert. Sie sehen außerdem, wie Sie **HTML in ein Bild konvertieren** und dabei Schriftstil, Antialiasing und Text‑Hinting steuern, sodass das endgültige PNG auf jedem Bildschirm scharf aussieht. + +Wir gehen jeden erforderlichen Schritt durch – von der Installation des NuGet‑Pakets bis hin zur Erstellung einer produktions‑reifen PNG‑Datei. Am Ende des Tutorials besitzen Sie ein eigenständiges, ausführbares Programm, das Sie in jedes C#‑Projekt einbinden können. + +## Was Sie lernen werden + +* Wie Sie Aspose.HTML in einem .NET‑Projekt einrichten. +* Wie Sie ein HTML‑Dokument im Speicher erstellen und das `WebFontStyle.BoldItalic`‑Enum anwenden. +* Wie Sie Antialiasing und Text‑Hinting aktivieren, um ein glatteres Rendering zu erzielen. +* Wie Sie das Dokument mit `ImageRenderer` in eine PNG‑Datei rendern. +* Häufige Varianten wie das Rendern in andere Bildformate oder das Skalieren der Ausgabe. + +Keine externen Tools oder manuelle Bildkonvertierungsschritte sind nötig – alles geschieht programmgesteuert. + +## Voraussetzungen + +* .NET 6.0 SDK oder höher (der Code funktioniert auch mit .NET Framework 4.7+). +* Visual Studio 2022 (oder jede IDE, die C# unterstützt). +* Eine aktive Aspose.HTML für .NET‑Lizenz (oder ein kostenloser Evaluierungsschlüssel). +* Grundlegende Kenntnisse der C#‑Syntax. + +> **Pro‑Tipp:** Wenn Sie die kostenlose Evaluierung verwenden, enthält das erzeugte PNG ein Wasserzeichen. Eine gekaufte Lizenz entfernt es automatisch. + +--- + +## Convert html to image – Umgebung einrichten + +1. **Neues Konsolenprojekt erstellen** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Aspose.HTML NuGet‑Paket hinzufügen** + + ```bash + dotnet add package Aspose.HTML + ``` + + Dieser Befehl zieht alle Assemblies, die Sie zum Rendern von HTML zu Bildern benötigen. + +3. **(Optional) Lizenzdatei hinzufügen** + + Platzieren Sie Ihre `Aspose.Total.lic`‑Datei im Projektstamm und fügen Sie die folgende Zeile am Anfang von `Program.cs` ein: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + Der Lizenzschritt ist für die kostenlose Testversion nicht erforderlich, verhindert jedoch das Wasserzeichen. + +## Render html to png with Aspose.HTML + +Der Kern des Tutorials ist ein fünf‑stufiger Prozess, der den bereitgestellten Code widerspiegelt. Jeder Schritt wird im Detail erklärt, sodass Sie **warum** der Aufruf nötig ist, und nicht nur **was** er bewirkt, verstehen. + +### Schritt 1: HTML‑Dokument erstellen + +Wir beginnen mit einem minimalen HTML‑String, der einen Absatz im Arial‑Font enthält. Mit `HTMLDocument` arbeiten wir vollständig im Speicher – es werden keine temporären Dateien erzeugt. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Warum das wichtig ist:* `HTMLDocument` analysiert das Markup und baut ein DOM, das der Renderer traversieren kann. Da das Dokument im Speicher lebt, ist die Operation schnell und thread‑sicher. + +### Schritt 2: Fettdruck‑kursiv‑Stil mit `WebFontStyle` anwenden + +Aspose.HTML stellt das `WebFontStyle`‑Enum bereit, um gängige CSS‑Werte für `font-weight` und `font-style` zu kombinieren. Die Einstellung auf `BoldItalic` lässt den Text sowohl fett als auch kursiv erscheinen, ohne zusätzliches CSS zu schreiben. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Warum `WebFontStyle` verwenden?** +> Es eliminiert die Notwendigkeit, einen Style‑Block oder ein externes Stylesheet einzubetten, und reduziert die Menge an HTML, die Sie beim serverseitigen Rendern von Bildern verwalten müssen. + +### Schritt 3: Antialiasing für glattere Kanten aktivieren + +Antialiasing glättet die Ränder von Formen und Text und reduziert gezackte Pixel, besonders auf hochauflösenden Displays. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Auswirkung:* Wenn `UseAntialiasing` auf `true` gesetzt ist, wendet der Renderer einen Sub‑Pixel‑Algorithmus an, der ein saubereres PNG erzeugt – insbesondere bei diagonalen Linien oder kleinen Schriftgrößen. + +### Schritt 4: Text‑Hinting aktivieren + +Text‑Hinting richtet Glyphen am Pixelraster aus, sodass Zeichen bei niedrigen Auflösungen schärfer wirken. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*Wann deaktivieren:* Wenn Sie später vektorbasierte PDFs rendern, können Sie das Hinting überspringen, um die ursprüngliche Kontur zu erhalten. Für Raster‑PNG‑Ausgaben ist Hinting fast immer vorteilhaft. + +### Schritt 5: Dokument in eine PNG‑Datei rendern + +Zum Schluss erstellen wir einen `ImageRenderer`, übergeben das Dokument sowie die beiden Optionsobjekte und schreiben die Ausgabe auf die Festplatte. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +Der Aufruf blockiert, bis die Datei vollständig geschrieben ist, sodass `output.png` beim Programmende existiert. + +#### Erwartete Ausgabe + +Beim Ausführen des Programms wird **output.png** im Projektordner erstellt. Das Bild zeigt das Wort **Hello** in Arial, fett‑kursiv, zentriert auf einem weißen Hintergrund, mit glatten Kanten dank Antialiasing und Hinting. + +{.img-fluid alt="Beispielausgabe Render html to png"} + +> **Hinweis:** Das obige Bild ist ein Platzhalter. In Ihrem eigenen Projekt wird das PNG den genauen HTML‑Inhalt wiedergeben, den Sie bereitgestellt haben. + +--- + +## Vollständiger, ausführbarer Quellcode + +Unten finden Sie die komplette `Program.cs`. Kopieren Sie sie in das zuvor erstellte Konsolenprojekt, stellen Sie die NuGet‑Pakete wieder her und führen Sie `dotnet run` aus. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Beim Ausführen des Programms wird ausgegeben: + +``` +HTML has been rendered to PNG successfully. +``` + +und `output.png` wird neben der ausführbaren Datei erstellt. + +--- + +## Varianten und Sonderfälle + +### Rendern in andere Bildformate + +`ImageRenderer` unterstützt BMP, GIF, JPEG und TIFF. Ändern Sie die Dateierweiterung in `RenderToFile` und passen Sie optional `ImageRenderingOptions` an: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Ausgabe skalieren + +Wenn Sie ein hochauflösendes PNG benötigen (z. B. für Retina‑Displays), setzen Sie die Eigenschaften `ImageWidth` und `ImageHeight`: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +Der Renderer rastert das HTML in der angegebenen Größe, wobei die Vektorqualität erhalten bleibt. + +### Komplexes CSS verarbeiten + +Aspose.HTML unterstützt vollständig externe Stylesheets, Media Queries und SVG. Laden Sie das HTML einfach aus einer Datei oder URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +Die gleiche Rendering‑Pipeline wird verwendet, sodass Sie **HTML in ein Bild konvertieren** können für jede Webseite, nicht nur für einfache Strings. + +### Thread‑Sicherheit + +`HTMLDocument` und `ImageRenderer` sind nicht thread‑sicher. Wenn Sie viele Seiten parallel rendern müssen, erstellen Sie pro Thread eine separate `HTMLDocument`‑Instanz oder nutzen Sie ein Thread‑Pool‑Muster. + +--- + +## Häufige Stolperfallen und wie man sie vermeidet + +| Problem | Warum es passiert | Lösung | +|---------|-------------------|--------| +| PNG ist leer oder Text fehlt | Schriftart nicht auf dem Server gefunden | Installieren Sie die benötigte Schriftart auf dem Rechner oder betten Sie sie via CSS `@font-face` ein. | +| Wasserzeichen erscheint | Evaluierungslizenz verwendet | Gültige Lizenzdatei (`Aspose.Total.lic`) anwenden. | +| Ausgabe ist unscharf | Antialiasing deaktiviert | `imageOptions.UseAntialiasing = true` setzen. | +| Text wirkt dünn | Hinting deaktiviert | `textOptions.UseHinting = true` setzen. | + +--- + +## Fazit + +Sie verfügen nun über eine solide End‑zu‑End‑Lösung, um **HTML in PNG in C# zu rendern**. Das Tutorial behandelte die Installation von Aspose.HTML, das Erstellen eines HTML‑Dokuments, das Anwenden von fett‑kursiv‑Stil, das Aktivieren von Antialiasing und Text‑Hinting sowie das Schreiben einer PNG‑Datei auf die Festplatte. + +Ab hier können Sie Folgendes erkunden: + +* **HTML in ein Bild konvertieren** für die Stapelverarbeitung von E‑Mail‑Vorlagen. +* Rendering zu PDF, indem Sie `ImageRenderer` durch `PdfRenderer` ersetzen. +* Die DOM‑API von Aspose.HTML nutzen, um HTML vor dem Rendern zu manipulieren. + +Experimentieren Sie gern mit unterschiedlichem CSS, größeren Leinwänden oder alternativen Ausgabeformaten. Viel Spaß beim Rendern! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Convert HTML to PNG in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/greek/net/generate-jpg-and-png-images/_index.md b/html/greek/net/generate-jpg-and-png-images/_index.md index 5fd47cce36..113085a7fd 100644 --- a/html/greek/net/generate-jpg-and-png-images/_index.md +++ b/html/greek/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ url: /el/net/generate-jpg-and-png-images/ Μάθετε πώς να βελτιώσετε την ποιότητα των εικόνων ενεργοποιώντας το antialiasing κατά τη μετατροπή αρχείων DOCX σε PNG ή JPG. ### [Μετατροπή docx σε png – δημιουργία αρχείου zip με C# σεμινάριο](./convert-docx-to-png-create-zip-archive-c-tutorial/) Μάθετε πώς να μετατρέψετε αρχεία DOCX σε PNG και να δημιουργήσετε αρχείο ZIP χρησιμοποιώντας C#. +### [Απόδοση HTML σε PNG σε C# – πλήρης οδηγός](./render-html-to-png-in-c-complete-guide/) +Μάθετε πώς να μετατρέψετε HTML σε PNG χρησιμοποιώντας C# με έναν ολοκληρωμένο οδηγό βήμα προς βήμα. ## Σύναψη diff --git a/html/greek/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/greek/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..d1885196ce --- /dev/null +++ b/html/greek/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,340 @@ +--- +category: general +date: 2026-08-06 +description: Απόδοση HTML σε PNG με το Aspose.HTML σε C#. Μάθετε πώς να μετατρέπετε + HTML σε εικόνα, να εφαρμόζετε στυλ γραμματοσειράς, εξομάλυνση (antialiasing) και + υποδείξεις κειμένου σε ένα ενιαίο, εκτελέσιμο παράδειγμα. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: el +lastmod: 2026-08-06 +og_description: Απόδοση HTML σε PNG χρησιμοποιώντας το Aspose.HTML για .NET. Αυτό + το σεμινάριο δείχνει πώς να μετατρέψετε το HTML σε εικόνα, να εφαρμόσετε στυλ έντονο‑πλάγιο, + εξομάλυνση (antialiasing) και υποδείξεις κειμένου (text hinting). +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Απόδοση HTML σε PNG σε C# – βήμα‑βήμα με το Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: Μετατροπή HTML σε PNG σε C# – πλήρης οδηγός +url: /el/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Απόδοση html σε png σε C# – πλήρης οδηγός + +Αν χρειάζεστε **απόδοση html σε png** γρήγορα και αξιόπιστα, αυτός ο οδηγός σας δείχνει ακριβώς πώς να το κάνετε με το Aspose.HTML για .NET. Θα δείτε επίσης πώς να **μετατρέψετε html σε εικόνα** ελέγχοντας το στυλ γραμματοσειράς, το antialiasing και το text hinting, ώστε το τελικό PNG να φαίνεται καθαρό σε οποιαδήποτε οθόνη. + +Θα περάσουμε από κάθε απαιτούμενο βήμα—από την εγκατάσταση του πακέτου NuGet μέχρι την παραγωγή ενός έτοιμου για παραγωγή αρχείου PNG. Στο τέλος του tutorial θα έχετε ένα αυτόνομο, εκτελέσιμο πρόγραμμα που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο C#. + +## Τι θα μάθετε + +* Πώς να ρυθμίσετε το Aspose.HTML σε ένα έργο .NET. +* Πώς να δημιουργήσετε ένα HTML έγγραφο στη μνήμη και να εφαρμόσετε το enum `WebFontStyle.BoldItalic`. +* Πώς να ενεργοποιήσετε το antialiasing και το text hinting για πιο ομαλή απόδοση. +* Πώς να αποδώσετε το έγγραφο σε αρχείο PNG χρησιμοποιώντας το `ImageRenderer`. +* Συνήθεις παραλλαγές όπως απόδοση σε άλλες μορφές εικόνας ή κλιμάκωση του αποτελέσματος. + +Δεν απαιτούνται εξωτερικά εργαλεία ή χειροκίνητα βήματα μετατροπής εικόνας—όλα γίνονται προγραμματιστικά. + +## Προαπαιτούμενα + +* .NET 6.0 SDK ή νεότερο (ο κώδικας λειτουργεί επίσης με .NET Framework 4.7+). +* Visual Studio 2022 (ή οποιοδήποτε IDE που υποστηρίζει C#). +* Ένα ενεργό license του Aspose.HTML για .NET (ή ένα δωρεάν κλειδί αξιολόγησης). +* Βασική εξοικείωση με τη σύνταξη C#. + +> **Pro tip:** Αν χρησιμοποιείτε τη δωρεάν αξιολόγηση, το παραγόμενο PNG θα περιέχει υδατογράφημα. Ένα αγορασμένο license το αφαιρεί αυτόματα. + +--- + +## Convert html to image – ρύθμιση του περιβάλλοντος + +1. **Δημιουργήστε ένα νέο έργο console** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Προσθέστε το πακέτο NuGet Aspose.HTML** + + ```bash + dotnet add package Aspose.HTML + ``` + + Αυτή η εντολή φέρνει όλα τα assemblies που χρειάζεστε για την απόδοση HTML σε εικόνες. + +3. **(Προαιρετικά) Προσθέστε ένα αρχείο license** + + Τοποθετήστε το αρχείο `Aspose.Total.lic` στη ρίζα του έργου και προσθέστε την παρακάτω γραμμή στην αρχή του `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + Το βήμα του license δεν απαιτείται για τη δωρεάν δοκιμή, αλλά αποτρέπει το υδατογράφημα. + +## Απόδοση html σε png με Aspose.HTML + +Ο πυρήνας του tutorial είναι μια διαδικασία πέντε βημάτων που αντικατοπτρίζει τον κώδικα που παρέχετε. Κάθε βήμα εξηγείται λεπτομερώς ώστε να κατανοήσετε **γιατί** η κλήση είναι απαραίτητη, όχι μόνο **τι** κάνει. + +### Βήμα 1: Δημιουργία του HTML εγγράφου + +Ξεκινάμε με μια ελάχιστη συμβολοσειρά HTML που περιέχει μια παράγραφο με τη γραμματοσειρά Arial. Η χρήση του `HTMLDocument` μας επιτρέπει να δουλέψουμε εξ ολοκλήρου στη μνήμη—δεν δημιουργούνται προσωρινά αρχεία. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Γιατί είναι σημαντικό:* Το `HTMLDocument` αναλύει το markup και δημιουργεί ένα DOM που μπορεί να διασχίσει ο renderer. Επειδή το έγγραφο βρίσκεται στη μνήμη, η λειτουργία είναι γρήγορη και thread‑safe. + +### Βήμα 2: Εφαρμογή στυλ bold‑italic με `WebFontStyle` + +Το Aspose.HTML εκθέτει την απαρίθμηση `WebFontStyle` για να συνδυάσει κοινές τιμές CSS font‑weight και font‑style. Ορίζοντάς το σε `BoldItalic` κάνει το κείμενο να εμφανίζεται ταυτόχρονα έντονο και πλάγιο χωρίς επιπλέον CSS. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Γιατί να χρησιμοποιήσετε το `WebFontStyle`;** +> Απομακρύνει την ανάγκη ενσωμάτωσης ενός style block ή εξωτερικού stylesheet, μειώνοντας την ποσότητα HTML που πρέπει να διαχειριστείτε κατά την απόδοση εικόνων από τον server. + +### Βήμα 3: Ενεργοποίηση antialiasing για πιο ομαλές άκρες + +Το antialiasing εξομαλύνει τα σύνορα σχημάτων και κειμένου, μειώνοντας τα σκαλιστά pixel, ειδικά σε οθόνες υψηλής ανάλυσης. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Επίδραση:* Όταν το `UseAntialiasing` είναι `true`, ο renderer εφαρμόζει έναν αλγόριθμο sub‑pixel που παράγει ένα καθαρότερο PNG, ιδιαίτερα για διαγώνιες γραμμές ή μικρά μεγέθη γραμματοσειράς. + +### Βήμα 4: Ενεργοποίηση text hinting + +Το text hinting ευθυγραμμίζει τα glyphs στο πλέγμα pixel, κάνοντας τους χαρακτήρες να φαίνονται πιο οξείς σε χαμηλές αναλύσεις. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*Πότε να το απενεργοποιήσετε:* Αν αργότερα θα αποδίδετε PDF βασισμένα σε vector, μπορεί να παραλείψετε το hinting για να διατηρήσετε το αρχικό περίγραμμα. Για raster PNG έξοδο, το hinting είναι σχεδόν πάντα ωφέλιμο. + +### Βήμα 5: Απόδοση του εγγράφου σε αρχείο PNG + +Τέλος, δημιουργούμε ένα `ImageRenderer`, περνάμε το έγγραφο και τα δύο αντικείμενα επιλογών, και γράφουμε το αποτέλεσμα στο δίσκο. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +Η κλήση μπλοκάρει μέχρι να γραφτεί πλήρως το αρχείο, εξασφαλίζοντας ότι το `output.png` υπάρχει όταν το πρόγραμμα τερματίσει. + +#### Αναμενόμενο αποτέλεσμα + +Η εκτέλεση του προγράμματος δημιουργεί **output.png** στον φάκελο του έργου. Η εικόνα εμφανίζει τη λέξη **Hello** σε Arial, bold‑italic, κεντραρισμένη σε λευκό φόντο, με ομαλές άκρες χάρη στο antialiasing και το hinting. + +{.img-fluid alt="Παράδειγμα εξόδου render html σε png"} + +> **Σημείωση:** Η παραπάνω εικόνα είναι placeholder. Στο δικό σας έργο το PNG θα αντανακλά το ακριβές HTML που παρείχατε. + +--- + +## Πλήρης, εκτελέσιμος κώδικας + +Παρακάτω βρίσκεται το πλήρες αρχείο `Program.cs`. Αντιγράψτε το στο console project που δημιουργήσατε νωρίτερα, επαναφέρετε τα πακέτα NuGet και τρέξτε `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Η εκτέλεση του προγράμματος εκτυπώνει: + +``` +HTML has been rendered to PNG successfully. +``` + +και δημιουργεί το `output.png` δίπλα στο εκτελέσιμο. + +--- + +## Παραλλαγές και ειδικές περιπτώσεις + +### Απόδοση σε άλλες μορφές εικόνας + +Το `ImageRenderer` υποστηρίζει BMP, GIF, JPEG και TIFF. Αλλάξτε την επέκταση αρχείου στο `RenderToFile` και προαιρετικά προσαρμόστε το `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Κλιμάκωση του αποτελέσματος + +Αν χρειάζεστε PNG υψηλότερης ανάλυσης (π.χ. για οθόνες retina), ορίστε τις ιδιότητες `ImageWidth` και `ImageHeight`: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +Ο renderer θα rasterize το HTML στο καθορισμένο μέγεθος διατηρώντας την ποιότητα vector. + +### Διαχείριση σύνθετου CSS + +Το Aspose.HTML υποστηρίζει πλήρως εξωτερικά stylesheets, media queries και SVG. Απλώς φορτώστε το HTML από αρχείο ή URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +Η ίδια αλυσίδα απόδοσης εφαρμόζεται, ώστε να μπορείτε **convert html to image** για οποιαδήποτε ιστοσελίδα, όχι μόνο για απλές συμβολοσειρές. + +### Σκέψεις για thread‑safety + +Το `HTMLDocument` και το `ImageRenderer` δεν είναι thread‑safe. Αν χρειαστεί να αποδώσετε πολλές σελίδες παράλληλα, δημιουργήστε ξεχωριστό `HTMLDocument` ανά νήμα ή χρησιμοποιήστε ένα pattern thread‑pool. + +--- + +## Συχνά προβλήματα και πώς να τα αποφύγετε + +| Πρόβλημα | Γιατί συμβαίνει | Διόρθωση | +|----------|----------------|----------| +| Το PNG είναι κενό ή λείπουν κείμενα | Η γραμματοσειρά δεν βρέθηκε στον server | Εγκαταστήστε τη απαιτούμενη γραμματοσειρά στο μηχάνημα ή ενσωματώστε την μέσω CSS `@font-face`. | +| Εμφανίζεται υδατογράφημα | Χρησιμοποιείται license αξιολόγησης | Εφαρμόστε έγκυρο αρχείο license (`Aspose.Total.lic`). | +| Η έξοδος είναι θολή | Antialiasing απενεργοποιημένο | Ορίστε `imageOptions.UseAntialiasing = true`. | +| Το κείμενο φαίνεται λεπτό | Hinting απενεργοποιημένο | Ορίστε `textOptions.UseHinting = true`. | + +--- + +## Συμπέρασμα + +Τώρα έχετε μια σταθερή, ολοκληρωμένη λύση για **render html to png** σε C#. Το tutorial κάλυψε την εγκατάσταση του Aspose.HTML, τη δημιουργία HTML εγγράφου, την εφαρμογή στυλ bold‑italic, την ενεργοποίηση antialiasing και text hinting, και τέλος τη δημιουργία αρχείου PNG στο δίσκο. + +Από εδώ μπορείτε να εξερευνήσετε: + +* **Convert html to image** για μαζική επεξεργασία προτύπων email. +* Απόδοση σε PDF αντικαθιστώντας το `ImageRenderer` με `PdfRenderer`. +* Χρήση του DOM API του Aspose.HTML για να τροποποιήσετε το HTML πριν την απόδοση. + +Μη διστάσετε να πειραματιστείτε με διαφορετικό CSS, μεγαλύτερους καμβάδες ή εναλλακτικές μορφές εξόδου. Καλή απόδοση! + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κυριαρχήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στην υλοποίηση των δικών σας έργων. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Convert HTML to PNG in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hindi/net/generate-jpg-and-png-images/_index.md b/html/hindi/net/generate-jpg-and-png-images/_index.md index b35cbb62e1..adbee4a3cd 100644 --- a/html/hindi/net/generate-jpg-and-png-images/_index.md +++ b/html/hindi/net/generate-jpg-and-png-images/_index.md @@ -44,7 +44,9 @@ HTML दस्तावेज़ों में हेरफेर करने ### [DOCX को PNG/JPG में बदलते समय एंटीएलियासिंग कैसे सक्षम करें](./how-to-enable-antialiasing-when-converting-docx-to-png-jpg/) DOCX फ़ाइलों को PNG या JPG में परिवर्तित करते समय एंटीएलियासिंग को सक्षम करने के चरणों को जानें। ### [DOCX को PNG में परिवर्तित करें – ZIP आर्काइव बनाएं C# ट्यूटोरियल](./convert-docx-to-png-create-zip-archive-c-tutorial/) -C# में DOCX फ़ाइलों को PNG छवियों में बदलें और उन्हें ZIP आर्काइव में संकलित करना सीखें। चरण-दर-चरण मार्गदर्शिका। +C# में DOCX फ़ाइलों को PNG छवियों में बदलें और उन्हें ZIP आर्काइव में संकलित करना सीखें। चरण-दर-श... +### [C# में HTML को PNG में रेंडर करने का पूर्ण गाइड](./render-html-to-png-in-c-complete-guide/) +C# में HTML को PNG में रेंडर करने के लिए पूर्ण मार्गदर्शिका। ## निष्कर्ष diff --git a/html/hindi/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/hindi/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..2297e42ef4 --- /dev/null +++ b/html/hindi/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,340 @@ +--- +category: general +date: 2026-08-06 +description: Aspose.HTML का उपयोग करके C# में HTML को PNG में रेंडर करें। एक ही चलाने + योग्य उदाहरण में HTML को इमेज में बदलना, फ़ॉन्ट स्टाइल लागू करना, एंटीएलियासिंग + और टेक्स्ट हिन्टिंग कैसे करें, सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: hi +lastmod: 2026-08-06 +og_description: Aspose.HTML for .NET का उपयोग करके HTML को PNG में रेंडर करें। यह + ट्यूटोरियल दिखाता है कि HTML को इमेज में कैसे बदलें, बोल्ड‑इटैलिक स्टाइलिंग, एंटीएलियासिंग + और टेक्स्ट हिन्टिंग कैसे लागू करें। +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: C# में HTML को PNG में रेंडर करें – Aspose.HTML के साथ चरण‑दर‑चरण +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: C# में HTML को PNG में रेंडर करें – पूर्ण गाइड +url: /hi/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में HTML को PNG में रेंडर करें – पूर्ण गाइड + +यदि आपको **HTML को PNG में रेंडर** करने की आवश्यकता तेज़ और भरोसेमंद तरीके से है, तो यह गाइड Aspose.HTML for .NET के साथ इसे कैसे करना है, बिल्कुल दिखाता है। आप यह भी देखेंगे कि **HTML को इमेज में बदलें** कैसे फ़ॉन्ट स्टाइल, एंटी‑एलियासिंग और टेक्स्ट हिन्टिंग को नियंत्रित करते हुए किया जाए, ताकि अंतिम PNG किसी भी स्क्रीन पर तेज़ दिखे। + +हम हर आवश्यक चरण से गुजरेंगे—NuGet पैकेज को इंस्टॉल करने से लेकर प्रोडक्शन‑रेडी PNG फ़ाइल बनाने तक। ट्यूटोरियल के अंत तक आपके पास एक स्व-निहित, चलाने योग्य प्रोग्राम होगा जिसे आप किसी भी C# प्रोजेक्ट में डाल सकते हैं। + +## आप क्या सीखेंगे + +* .NET प्रोजेक्ट में Aspose.HTML सेट‑अप करना। +* मेमोरी में HTML डॉक्यूमेंट बनाना और `WebFontStyle.BoldItalic` एन्नम लागू करना। +* स्मूद रेंडरिंग के लिए एंटी‑एलियासिंग और टेक्स्ट हिन्टिंग सक्षम करना। +* `ImageRenderer` का उपयोग करके डॉक्यूमेंट को PNG फ़ाइल में रेंडर करना। +* अन्य इमेज फ़ॉर्मेट में रेंडर करना या आउटपुट को स्केल करने जैसे सामान्य वैरिएशन। + +कोई बाहरी टूल या मैन्युअल इमेज कन्वर्ज़न स्टेप्स आवश्यक नहीं—सब कुछ प्रोग्रामेटिकली होता है। + +## पूर्वापेक्षाएँ + +* .NET 6.0 SDK या बाद का (कोड .NET Framework 4.7+ के साथ भी काम करता है)। +* Visual Studio 2022 (या कोई भी IDE जो C# सपोर्ट करता हो)। +* एक सक्रिय Aspose.HTML for .NET लाइसेंस (या फ्री इवैल्यूएशन की)। +* C# सिंटैक्स की बुनियादी समझ। + +> **Pro tip:** यदि आप फ्री इवैल्यूएशन का उपयोग कर रहे हैं, तो जेनरेटेड PNG में वॉटरमार्क होगा। खरीदा गया लाइसेंस इसे स्वचालित रूप से हटा देता है। + +--- + +## HTML को इमेज में बदलें – पर्यावरण सेट‑अप + +1. **एक नया कंसोल प्रोजेक्ट बनाएं** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Aspose.HTML NuGet पैकेज जोड़ें** + + ```bash + dotnet add package Aspose.HTML + ``` + + यह कमांड उन सभी असेंबलीज़ को लाता है जो HTML को इमेज में रेंडर करने के लिए आवश्यक हैं। + +3. **(वैकल्पिक) लाइसेंस फ़ाइल जोड़ें** + + अपने `Aspose.Total.lic` फ़ाइल को प्रोजेक्ट रूट में रखें और `Program.cs` की शुरुआत में निम्न पंक्ति जोड़ें: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + फ्री ट्रायल के लिए लाइसेंस स्टेप आवश्यक नहीं है, लेकिन यह वॉटरमार्क को रोकता है। + +## Aspose.HTML के साथ HTML को PNG में रेंडर करें + +ट्यूटोरियल का मूल भाग पाँच‑स्टेप प्रक्रिया है जो आपके द्वारा प्रदान किए गए कोड को प्रतिबिंबित करता है। प्रत्येक चरण को विस्तार से समझाया गया है ताकि आप **क्यों** कॉल आवश्यक है, न कि सिर्फ **क्या** करता है, समझ सकें। + +### चरण 1: HTML डॉक्यूमेंट बनाएं + +हम एक न्यूनतम HTML स्ट्रिंग से शुरू करते हैं जिसमें Arial फ़ॉन्ट से स्टाइल किया गया पैराग्राफ है। `HTMLDocument` का उपयोग करके हम पूरी तरह मेमोरी में काम करते हैं—कोई अस्थायी फ़ाइल नहीं बनती। + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*यह क्यों महत्वपूर्ण है:* `HTMLDocument` मार्कअप को पार्स करता है और एक DOM बनाता है जिसे रेंडरर ट्रैवर्स कर सकता है। क्योंकि डॉक्यूमेंट मेमोरी में रहता है, ऑपरेशन तेज़ और थ्रेड‑सेफ़ होता है। + +### चरण 2: `WebFontStyle` के साथ बोल्ड‑इटैलिक स्टाइल लागू करें + +Aspose.HTML `WebFontStyle` एन्नम को एक्सपोज़ करता है जिससे सामान्य CSS फ़ॉन्ट‑वेट और फ़ॉन्ट‑स्टाइल मानों को मिलाया जा सकता है। इसे `BoldItalic` पर सेट करने से टेक्स्ट बोल्ड और इटैलिक दोनों दिखता है, बिना अतिरिक्त CSS लिखे। + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **`WebFontStyle` क्यों उपयोग करें?** +> यह स्टाइल ब्लॉक या एक्सटर्नल स्टाइलशीट एम्बेड करने की आवश्यकता को समाप्त करता है, जिससे सर्वर‑साइड इमेज रेंडरिंग के समय आपको प्रबंधित करने वाले HTML की मात्रा घट जाती है। + +### चरण 3: स्मूथ एजेज़ के लिए एंटी‑एलियासिंग सक्षम करें + +एंटी‑एलियासिंग आकारों और टेक्स्ट की किनारों को स्मूद करता है, जिससे हाई‑DPI डिस्प्ले पर जगरिंग पिक्सेल कम होते हैं। + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*प्रभाव:* जब `UseAntialiasing` `true` होता है, तो रेंडरर एक सब‑पिक्सेल एल्गोरिद्म लागू करता है जो एक साफ़ PNG देता है, विशेषकर डायगोनल लाइन्स या छोटे फ़ॉन्ट साइज के लिए। + +### चरण 4: टेक्स्ट हिन्टिंग सक्रिय करें + +टेक्स्ट हिन्टिंग ग्लिफ़्स को पिक्सेल ग्रिड पर संरेखित करता है, जिससे लो‑रेज़ोल्यूशन पर कैरेक्टर्स तेज़ दिखते हैं। + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*कब डिसेबल करें:* यदि आप बाद में वेक्टर‑बेस्ड PDFs रेंडर कर रहे हैं, तो मूल आउटलाइन को संरक्षित रखने के लिए हिन्टिंग को स्किप कर सकते हैं। रास्टर PNG आउटपुट के लिए हिन्टिंग लगभग हमेशा फायदेमंद होती है। + +### चरण 5: डॉक्यूमेंट को PNG फ़ाइल में रेंडर करें + +अंत में, हम `ImageRenderer` बनाते हैं, डॉक्यूमेंट और दो विकल्प ऑब्जेक्ट्स पास करते हैं, और आउटपुट को डिस्क पर लिखते हैं। + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +यह कॉल तब तक ब्लॉक करता है जब तक फ़ाइल पूरी तरह लिख नहीं जाती, जिससे प्रोग्राम के समाप्त होने पर `output.png` मौजूद रहता है। + +#### अपेक्षित आउटपुट + +प्रोग्राम चलाने पर **output.png** प्रोजेक्ट फ़ोल्डर में बनता है। इमेज में सफ़ेद बैकग्राउंड पर Arial, बोल्ड‑इटैलिक में शब्द **Hello** केंद्रित दिखता है, एंटी‑एलियासिंग और हिन्टिंग के कारण किनारे स्मूद होते हैं। + +{.img-fluid alt="Render html to png example output"} + +> **नोट:** ऊपर की इमेज एक प्लेसहोल्डर है। आपके अपने प्रोजेक्ट में PNG आपके द्वारा प्रदान किए गए सटीक HTML को दर्शाएगा। + +--- + +## पूर्ण, चलाने योग्य स्रोत कोड + +नीचे पूरा `Program.cs` फ़ाइल दिया गया है। इसे पहले बनाए गए कंसोल प्रोजेक्ट में कॉपी करें, NuGet पैकेज रीस्टोर करें, और `dotnet run` चलाएँ। + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +प्रोग्राम चलाने पर प्रिंट होता है: + +``` +HTML has been rendered to PNG successfully. +``` + +और `output.png` एक्सीक्यूटेबल के बगल में बन जाता है। + +--- + +## वैरिएशन और एज केस + +### अन्य इमेज फ़ॉर्मेट में रेंडर करना + +`ImageRenderer` BMP, GIF, JPEG, और TIFF को सपोर्ट करता है। `RenderToFile` में फ़ाइल एक्सटेंशन बदलें और वैकल्पिक रूप से `ImageRenderingOptions` को समायोजित करें: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### आउटपुट को स्केल करना + +यदि आपको हाई‑रेज़ोल्यूशन PNG चाहिए (जैसे रेटिना डिस्प्ले के लिए), तो `ImageWidth` और `ImageHeight` प्रॉपर्टीज़ सेट करें: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +रेंडरर निर्दिष्ट आकार पर HTML को रास्टराइज़ करेगा जबकि वेक्टर क्वालिटी बरकरार रहेगी। + +### जटिल CSS को संभालना + +Aspose.HTML पूरी तरह से एक्सटर्नल स्टाइलशीट, मीडिया क्वेरी, और SVG को सपोर्ट करता है। बस HTML को फ़ाइल या URL से लोड करें: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +समान रेंडरिंग पाइपलाइन लागू होती है, इसलिए आप **HTML को इमेज में बदलें** किसी भी वेब पेज के लिए कर सकते हैं, न कि केवल सरल स्ट्रिंग्स के लिए। + +### थ्रेड‑सेफ़्टी विचार + +`HTMLDocument` और `ImageRenderer` थ्रेड‑सेफ़ नहीं हैं। यदि आपको कई पेज़ समानांतर में रेंडर करने हैं, तो प्रत्येक थ्रेड के लिए अलग `HTMLDocument` इंस्टेंस बनाएं या थ्रेड‑पूल पैटर्न उपयोग करें। + +--- + +## सामान्य pitfalls और उनका समाधान + +| समस्या | क्यों होता है | समाधान | +|-------|----------------|-----| +| PNG खाली या टेक्स्ट नहीं दिख रहा | सर्वर पर फ़ॉन्ट नहीं मिला | मशीन पर आवश्यक फ़ॉन्ट इंस्टॉल करें या CSS `@font-face` के माध्यम से एम्बेड करें। | +| वॉटरमार्क दिखाई दे रहा है | इवैल्यूएशन लाइसेंस उपयोग किया गया | वैध लाइसेंस फ़ाइल (`Aspose.Total.lic`) लागू करें। | +| आउटपुट धुंधला है | एंटी‑एलियासिंग डिसेबल है | `imageOptions.UseAntialiasing = true` सेट करें। | +| टेक्स्ट पतला दिख रहा है | हिन्टिंग डिसेबल है | `textOptions.UseHinting = true` सेट करें। | + +--- + +## निष्कर्ष + +अब आपके पास C# में **HTML को PNG में रेंडर** करने का एक ठोस, एंड‑टू‑एंड समाधान है। ट्यूटोरियल ने Aspose.HTML को इंस्टॉल करना, HTML डॉक्यूमेंट बनाना, बोल्ड‑इटैलिक स्टाइल लागू करना, एंटी‑एलियासिंग और टेक्स्ट हिन्टिंग सक्षम करना, और अंत में PNG फ़ाइल डिस्क पर लिखना कवर किया। + +अब आप आगे खोज सकते हैं: + +* **HTML को इमेज में बदलें** बैच प्रोसेसिंग के लिए ईमेल टेम्प्लेट्स। +* `ImageRenderer` को `PdfRenderer` से बदलकर PDF में रेंडर करना। +* रेंडरिंग से पहले HTML को बदलने के लिए Aspose.HTML के DOM API का उपयोग करना। + +विभिन्न CSS, बड़े कैनवास, या वैकल्पिक आउटपुट फ़ॉर्मेट के साथ प्रयोग करने में संकोच न करें। हैप्पी रेंडरिंग! + +## अगला क्या सीखें? + +नीचे दिए गए ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोच को एक्सप्लोर कर सकें। + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Convert HTML to PNG in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hongkong/net/generate-jpg-and-png-images/_index.md b/html/hongkong/net/generate-jpg-and-png-images/_index.md index 33103bd045..a139db129e 100644 --- a/html/hongkong/net/generate-jpg-and-png-images/_index.md +++ b/html/hongkong/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET 提供了一種將 HTML 轉換為映像的簡單方法。 了解如何在使用 Aspose.HTML for .NET 將 DOCX 轉換為 PNG 或 JPG 時啟用抗鋸齒,以提升圖像品質。 ### [使用 Aspose.HTML 在 .NET 中將 docx 轉換為 png 並建立 zip 壓縮檔 C# 教學](./convert-docx-to-png-create-zip-archive-c-tutorial/) 學習如何使用 Aspose.HTML for .NET 將 docx 轉換為 png,並將圖像打包成 zip 壓縮檔的完整步驟。 +### [在 C# 中將 HTML 渲染為 PNG 完整指南](./render-html-to-png-in-c-complete-guide/) +學習如何在 C# 使用 Aspose.HTML 將 HTML 轉換為 PNG 圖像的完整步驟。 ## 結論 diff --git a/html/hongkong/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/hongkong/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..c3365c7f85 --- /dev/null +++ b/html/hongkong/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,336 @@ +--- +category: general +date: 2026-08-06 +description: 使用 Aspose.HTML 在 C# 中將 HTML 渲染為 PNG。學習如何將 HTML 轉換為圖像、套用字型樣式、抗鋸齒與文字微調,並以單一可執行範例示範。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: zh-hant +lastmod: 2026-08-06 +og_description: 使用 Aspose.HTML for .NET 將 HTML 渲染為 PNG。本教學展示如何將 HTML 轉換為圖像、套用粗斜體樣式、抗鋸齒以及文字微調。 +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: 在 C# 中將 HTML 渲染為 PNG – 使用 Aspose.HTML 的逐步教學 +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: 在 C# 中將 HTML 轉換為 PNG – 完整指南 +url: /zh-hant/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-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**,本指南將向您展示如何使用 Aspose.HTML for .NET 完成此操作。您還將看到如何 **convert html to image**,同時控制字體樣式、抗鋸齒和文字 hinting,使最終的 PNG 在任何螢幕上都保持清晰。 + +我們將逐步說明所有必要步驟——從安裝 NuGet 套件到產生可投入生產環境的 PNG 檔案。完成本教學後,您將擁有一個自包含、可執行的程式,能直接放入任何 C# 專案中使用。 + +## 您將學到 + +* 如何在 .NET 專案中設定 Aspose.HTML。 +* 如何建立記憶體中的 HTML 文件並套用 `WebFontStyle.BoldItalic` 列舉。 +* 如何啟用抗鋸齒和文字 hinting 以獲得更平滑的渲染。 +* 如何使用 `ImageRenderer` 將文件渲染為 PNG 檔案。 +* 常見變化,例如渲染為其他影像格式或調整輸出尺寸。 + +不需要任何外部工具或手動影像轉換步驟——所有操作皆以程式方式完成。 + +## 先決條件 + +* .NET 6.0 SDK 或更新版本(程式碼亦相容於 .NET Framework 4.7+)。 +* Visual Studio 2022(或任何支援 C# 的 IDE)。 +* 有效的 Aspose.HTML for .NET 授權(或免費評估金鑰)。 +* 具備基本的 C# 語法知識。 + +> **專業提示:** 若您使用免費評估版,產生的 PNG 會包含浮水印。購買授權後會自動移除。 + +--- + +## 將 html 轉換為影像 – 環境設定 + +1. **建立新的主控台專案** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **加入 Aspose.HTML NuGet 套件** + + ```bash + dotnet add package Aspose.HTML + ``` + + 此指令會下載所有渲染 HTML 為影像所需的組件。 + +3. **(可選) 新增授權檔案** + + 將您的 `Aspose.Total.lic` 檔案放在專案根目錄,並在 `Program.cs` 開頭加入以下程式碼: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + 授權步驟對於免費試用不是必須的,但可避免浮水印。 + +## 使用 Aspose.HTML 將 html 轉換為 png + +本教學的核心是一個五步驟流程,與您提供的程式碼相呼應。每一步都會詳細說明,以便您了解 **為何** 需要此呼叫,而不僅是 **它做了什麼**。 + +### 步驟 1:建立 HTML 文件 + +我們從一段最小的 HTML 字串開始,內含使用 Arial 字體樣式的段落。使用 `HTMLDocument` 讓我們完全在記憶體中操作——不會產生暫存檔案。 + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*為什麼這很重要:* `HTMLDocument` 會解析標記並建立渲染器可遍歷的 DOM。由於文件位於記憶體中,操作快速且具執行緒安全性。 + +### 步驟 2:使用 `WebFontStyle` 套用粗斜體樣式 + +Aspose.HTML 提供 `WebFontStyle` 列舉,以結合常見的 CSS font‑weight 與 font‑style 值。將其設定為 `BoldItalic` 可讓文字同時呈現粗體與斜體,無需額外的 CSS。 + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **為何使用 `WebFontStyle`?** +> 它消除嵌入 style 區塊或外部樣式表的需求,減少在伺服器端渲染影像時必須管理的 HTML 量。 + +### 步驟 3:啟用抗鋸齒以獲得更平滑的邊緣 + +抗鋸齒會平滑形狀與文字的邊緣,特別是在高 DPI 螢幕上減少鋸齒狀像素。 + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*影響:* 當 `UseAntialiasing` 為 `true` 時,渲染器會套用次像素演算法,產生更乾淨的 PNG,尤其在斜線或小字體尺寸時更為明顯。 + +### 步驟 4:啟用文字 hinting + +文字 hinting 會將字形對齊至像素格,讓字符在低解析度下看起來更銳利。 + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*何時停用:* 若您之後要渲染向量式 PDF,可能會跳過 hinting 以保留原始輪廓。對於點陣 PNG 輸出,hinting 幾乎總是有益的。 + +### 步驟 5:將文件渲染為 PNG 檔案 + +最後,我們建立 `ImageRenderer`,傳入文件與兩個選項物件,並將輸出寫入磁碟。 + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +此呼叫會阻塞直至檔案完整寫入,確保程式結束時 `output.png` 已存在。 + +#### 預期輸出 + +執行程式會在專案資料夾產生 **output.png**。影像顯示以 Arial 粗斜體呈現的 **Hello** 文字,置中於白色背景,並因抗鋸齒與 hinting 而擁有平滑的邊緣。 + +{.img-fluid alt="渲染 html 為 png 範例輸出"} + +> **注意:** 上圖僅為佔位圖。於您自己的專案中,PNG 會呈現您提供的完整 HTML。 + +--- + +## 完整、可執行的原始碼 + +以下為完整的 `Program.cs` 檔案。將其複製到先前建立的主控台專案中,還原 NuGet 套件,然後執行 `dotnet run`。 + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +執行程式會輸出: + +``` +HTML has been rendered to PNG successfully. +``` + +並在可執行檔旁產生 `output.png`。 + +--- + +## 變體與邊緣案例 + +### 渲染為其他影像格式 + +`ImageRenderer` 支援 BMP、GIF、JPEG 與 TIFF。變更 `RenderToFile` 的副檔名,並視需要調整 `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### 調整輸出尺寸 + +若您需要更高解析度的 PNG(例如 Retina 螢幕),請設定 `ImageWidth` 與 `ImageHeight` 屬性: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +渲染器會在指定尺寸下光柵化 HTML,同時保留向量品質。 + +### 處理複雜 CSS + +Aspose.HTML 完全支援外部樣式表、媒體查詢與 SVG。只要從檔案或 URL 載入 HTML 即可: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +相同的渲染流程仍然適用,您可以 **convert html to image** 任意網頁,而不僅限於簡單字串。 + +### 執行緒安全性考量 + +`HTMLDocument` 與 `ImageRenderer` 並非執行緒安全。若需平行渲染多頁,請為每個執行緒建立獨立的 `HTMLDocument` 實例,或使用執行緒池模式。 + +--- + +## 常見陷阱與避免方法 + +| 問題 | 發生原因 | 解決方式 | +|-------|----------------|-----| +| PNG 為空白或缺少文字 | 伺服器上找不到字體 | 在機器上安裝所需字體,或透過 CSS `@font-face` 嵌入字體。 | +| 出現浮水印 | 使用評估授權 | 套用有效的授權檔案 (`Aspose.Total.lic`)。 | +| 輸出模糊 | 未啟用抗鋸齒 | 將 `imageOptions.UseAntialiasing = true` 設為 true。 | +| 文字看起來很細 | 未啟用 hinting | 將 `textOptions.UseHinting = true` 設為 true。 | + +--- + +## 結論 + +您現在已擁有一套完整、端對端的 **render html to png** 解決方案於 C#。本教學涵蓋了安裝 Aspose.HTML、建立 HTML 文件、套用粗斜體樣式、啟用抗鋸齒與文字 hinting,最後將 PNG 檔寫入磁碟。 + +接下來您可以進一步探索: + +* **Convert html to image** 以批次處理電子郵件範本。 +* 透過將 `ImageRenderer` 換成 `PdfRenderer` 來渲染為 PDF。 +* 使用 Aspose.HTML 的 DOM API 在渲染前操作 HTML。 + +歡迎嘗試不同的 CSS、較大的畫布或其他輸出格式。祝渲染愉快! + +## 接下來您應該學習什麼? + +以下教學涵蓋與本指南緊密相關的主題,並以此為基礎。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助您精通更多 API 功能,並在自己的專案中探索替代實作方式。 + +- [如何使用 Aspose 渲染 HTML 為 PNG – 步驟說明指南](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [如何使用 Aspose 渲染 HTML 為 PNG – 完整指南](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [.NET 使用 Aspose.HTML 將 HTML 轉換為 PNG](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hungarian/net/generate-jpg-and-png-images/_index.md b/html/hungarian/net/generate-jpg-and-png-images/_index.md index dc2c2b0acd..4ec21b3a13 100644 --- a/html/hungarian/net/generate-jpg-and-png-images/_index.md +++ b/html/hungarian/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Tanulja meg az Aspose.HTML for .NET használatát HTML-dokumentumok kezeléséhe Ismerje meg, hogyan állíthatja be az antialiasingot a DOCX dokumentumok PNG vagy JPG képekké konvertálásakor az Aspose.HTML for .NET használatával. ### [docx konvertálása png-re – zip archívum létrehozása C# oktatóanyag](./convert-docx-to-png-create-zip-archive-c-tutorial/) Ismerje meg, hogyan konvertálhat docx fájlokat png képekké, majd csomagolhatja őket zip archívumba C#-ban az Aspose.HTML segítségével. +### [HTML renderelése PNG-re C#-ban – teljes útmutató](./render-html-to-png-in-c-complete-guide/) +Ismerje meg, hogyan konvertálhatja HTML-t PNG képpé C#-ban az Aspose.HTML for .NET segítségével, részletes lépésekkel. ## Következtetés diff --git a/html/hungarian/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/hungarian/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..61309cd267 --- /dev/null +++ b/html/hungarian/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,340 @@ +--- +category: general +date: 2026-08-06 +description: HTML renderelése PNG-be az Aspose.HTML használatával C#-ban. Tanulja + meg, hogyan konvertálhatja a HTML-t képpé, alkalmazhat betűstílusokat, antialiasingot + és szöveg hintelést egyetlen, futtatható példában. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: hu +lastmod: 2026-08-06 +og_description: HTML renderelése PNG-be az Aspose.HTML for .NET segítségével. Ez az + útmutató bemutatja, hogyan lehet a HTML-t képpé konvertálni, félkövér‑dőlt stílusokat + alkalmazni, antialiasingot és szöveg‑hintelést használni. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: HTML renderelése PNG-re C#‑ban – lépésről‑lépésre az Aspose.HTML‑el. +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: HTML renderelése PNG-re C#-ban – teljes útmutató +url: /hu/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-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 guide + +Ha **html-t png‑re szeretnél renderelni** gyorsan és megbízhatóan, ez az útmutató pontosan megmutatja, hogyan teheted meg az Aspose.HTML for .NET segítségével. Emellett láthatod, hogyan **konvertálj html‑t képre**, miközben a betűstílust, az antialiasingot és a szöveg‑hintinget is szabályozod, így a végső PNG minden képernyőn élesnek tűnik. + +Végigvezetünk minden szükséges lépésen – a NuGet‑csomag telepítésétől a production‑kész PNG fájl előállításáig. A tutorial végére egy önálló, futtatható programod lesz, amelyet bármely C# projektbe beilleszthetsz. + +## What you’ll learn + +* Hogyan állítsd be az Aspose.HTML‑t egy .NET projektben. +* Hogyan hozz létre memóriában lévő HTML‑dokumentumot, és alkalmazd a `WebFontStyle.BoldItalic` enumot. +* Hogyan engedélyezd az antialiasingot és a szöveg‑hintinget a simább rendereléshez. +* Hogyan rendereld a dokumentumot PNG fájlba az `ImageRenderer` használatával. +* Gyakori variációk, például más képformátumokba renderelés vagy a kimenet méretezése. + +Nem szükséges külső eszköz vagy manuális képkonvertálás – minden programozottan történik. + +## Prerequisites + +* .NET 6.0 SDK vagy újabb (a kód .NET Framework 4.7+‑vel is működik). +* Visual Studio 2022 (vagy bármely C#‑ot támogató IDE). +* Aktív Aspose.HTML for .NET licenc (vagy ingyenes értékelő kulcs). +* Alapvető C# szintaxis ismeret. + +> **Pro tip:** Ha az ingyenes értékelőt használod, a generált PNG vízjelet tartalmaz. A megvásárolt licenc automatikusan eltávolítja azt. + +--- + +## Convert html to image – setting up the environment + +1. **Create a new console project** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Add the Aspose.HTML NuGet package** + + ```bash + dotnet add package Aspose.HTML + ``` + + Ez a parancs letölti az összes szükséges assembly‑t a HTML képekké rendereléséhez. + +3. **(Optional) Add a license file** + + Helyezd el az `Aspose.Total.lic` fájlt a projekt gyökerében, és add hozzá a következő sort a `Program.cs` elejéhez: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + A licenc lépés nem kötelező az ingyenes próbaidőszakban, de eltávolítja a vízjelet. + +## Render html to png with Aspose.HTML + +A tutorial magja egy öt lépésből álló folyamat, amely tükrözi a megadott kódot. Minden lépést részletesen magyarázunk, hogy megértsd **miért** szükséges a hívás, ne csak **mit** csinál. + +### Step 1: Create the HTML document + +Kezdünk egy minimális HTML‑stringgel, amely egy Arial betűtípussal formázott bekezdést tartalmaz. A `HTMLDocument` használatával teljesen memóriában dolgozunk – nem jönnek létre ideiglenes fájlok. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Why this matters:* A `HTMLDocument` feldolgozza a markupot és felépíti a DOM‑ot, amelyet a renderelő bejárhat. Mivel a dokumentum memóriában él, a művelet gyors és szálbiztos. + +### Step 2: Apply bold‑italic styling with `WebFontStyle` + +Az Aspose.HTML a `WebFontStyle` enumerációval teszi lehetővé a gyakori CSS `font-weight` és `font-style` értékek kombinálását. `BoldItalic` beállításával a szöveg egyszerre lesz félkövér és dőlt, anélkül, hogy további CSS‑t kellene írni. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Why use `WebFontStyle`?** +> Ez megszünteti a style‑block vagy külső stylesheet beágyazásának szükségességét, csökkentve a rendereléshez szükséges HTML mennyiségét. + +### Step 3: Enable antialiasing for smoother edges + +Az antialiasing simítja a formák és a szöveg szélét, csökkentve a lépcsőzetes pixeleket, különösen a nagy DPI‑s kijelzőkön. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Impact:* Ha a `UseAntialiasing` `true`, a renderelő egy al-pixel algoritmust alkalmaz, amely tisztább PNG‑t eredményez, különösen átlós vonalak vagy kis betűméretek esetén. + +### Step 4: Activate text hinting + +A szöveg‑hinting a glifeket a pixelrácshoz igazítja, így a karakterek alacsony felbontáson is élesebben jelennek meg. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*When to disable:* Ha később vektor‑alapú PDF‑eket renderelsz, előfordulhat, hogy kihagyod a hintinget, hogy megőrizd az eredeti körvonalat. Raster PNG kimenetnél a hinting szinte mindig előnyös. + +### Step 5: Render the document to a PNG file + +Végül létrehozunk egy `ImageRenderer`‑t, átadjuk a dokumentumot és a két opciós objektumot, majd a kimenetet leírjuk a lemezre. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +A hívás blokkol, amíg a fájl teljesen le nem íródik, garantálva, hogy a program kilépésekor már létezik az `output.png`. + +#### Expected output + +A program futtatása **output.png**‑t hoz létre a projekt mappájában. A kép a **Hello** szót mutatja Arial, félkövér‑dőlt betűtípussal, fehér háttéren, a sima éleknek köszönhetően antialiasing és hinting segítségével. + +{.img-fluid alt="Render html to png example output"} + +> **Note:** A fenti kép csak helyőrző. A saját projektedben a PNG pontosan azt a HTML‑t tükrözi, amit megadtál. + +--- + +## Full, runnable source code + +Az alábbiakban a teljes `Program.cs` fájl látható. Másold be a korábban létrehozott konzolprojektbe, állítsd vissza a NuGet csomagokat, és futtasd a `dotnet run` parancsot. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +A program futtatása a következőt írja ki: + +``` +HTML has been rendered to PNG successfully. +``` + +és létrehozza az `output.png`‑t a futtatható fájl mellett. + +--- + +## Variations and edge cases + +### Rendering to other image formats + +Az `ImageRenderer` támogatja a BMP, GIF, JPEG és TIFF formátumokat. Csak módosítsd a fájlkiterjesztést a `RenderToFile`‑ban, és opcionálisan állítsd be az `ImageRenderingOptions`‑t: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Scaling the output + +Ha nagy felbontású PNG‑re van szükséged (pl. retina kijelzőkhöz), állítsd be az `ImageWidth` és `ImageHeight` tulajdonságokat: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +A renderelő a megadott méretben rasterizálja a HTML‑t, miközben megőrzi a vektor‑minőséget. + +### Handling complex CSS + +Az Aspose.HTML teljes mértékben támogatja a külső stíluslapokat, media query‑ket és az SVG‑t. Egyszerűen töltsd be a HTML‑t fájlból vagy URL‑ről: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +Ugyanaz a renderelési csővezeték alkalmazható, így **convert html to image** bármely weboldalhoz, nem csak egyszerű stringekhez. + +### Thread‑safety considerations + +A `HTMLDocument` és az `ImageRenderer` nem szálbiztos. Ha sok oldalt kell párhuzamosan renderelned, hozz létre egy külön `HTMLDocument` példányt szálanként, vagy használj thread‑pool mintát. + +--- + +## Common pitfalls and how to avoid them + +| Issue | Why it happens | Fix | +|-------|----------------|-----| +| PNG is blank or missing text | Font not found on the server | Install the required font on the machine or embed it via CSS `@font-face`. | +| Watermark appears | Evaluation license used | Apply a valid license file (`Aspose.Total.lic`). | +| Output is blurry | Antialiasing disabled | Set `imageOptions.UseAntialiasing = true`. | +| Text looks thin | Hinting disabled | Set `textOptions.UseHinting = true`. | + +--- + +## Conclusion + +Most már van egy szilárd, vég‑től‑végig megoldásod a **render html to png** feladatra C#‑ban. A tutorial bemutatta az Aspose.HTML telepítését, egy HTML‑dokumentum létrehozását, a félkövér‑dőlt stílus alkalmazását, az antialiasing és a text hinting engedélyezését, valamint a PNG fájl lemezre írását. + +Innen tovább felfedezheted: + +* **Convert html to image** kötegelt e‑mail sablonok feldolgozásához. +* PDF renderelés `ImageRenderer` helyett `PdfRenderer` használatával. +* Az Aspose.HTML DOM API‑jának használata a HTML módosításához renderelés előtt. + +Nyugodtan kísérletezz különböző CSS‑ekkel, nagyobb vásznakkal vagy alternatív kimeneti formátumokkal. Boldog renderelést! + +## What Should You Learn Next? + +A következő tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás tartalmaz teljes, működő kódrészleteket és lépésről‑lépésre magyarázatokat, hogy további API‑funkciókat saját projektjeidben is könnyedén alkalmazhasd. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Convert HTML to PNG in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/indonesian/net/generate-jpg-and-png-images/_index.md b/html/indonesian/net/generate-jpg-and-png-images/_index.md index 4e885ce325..51576b8315 100644 --- a/html/indonesian/net/generate-jpg-and-png-images/_index.md +++ b/html/indonesian/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Pelajari cara menggunakan Aspose.HTML untuk .NET guna memanipulasi dokumen HTML, Pelajari cara mengaktifkan antialiasing untuk meningkatkan kualitas gambar PNG atau JPG saat mengonversi dokumen DOCX menggunakan Aspose.HTML. ### [Konversi DOCX ke PNG – Membuat Arsip ZIP dengan C# Tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Pelajari cara mengonversi file DOCX menjadi PNG dan mengemasnya ke dalam arsip ZIP menggunakan C# dengan Aspose.HTML. +### [Render HTML ke PNG dalam C# – panduan lengkap](./render-html-to-png-in-c-complete-guide/) +Panduan lengkap untuk merender HTML menjadi gambar PNG menggunakan C# dengan Aspose.HTML. ## Kesimpulan diff --git a/html/indonesian/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/indonesian/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..389571f45d --- /dev/null +++ b/html/indonesian/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,340 @@ +--- +category: general +date: 2026-08-06 +description: Render HTML ke PNG dengan Aspose.HTML di C#. Pelajari cara mengonversi + HTML menjadi gambar, menerapkan gaya font, antialiasing, dan hinting teks dalam + satu contoh yang dapat dijalankan. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: id +lastmod: 2026-08-06 +og_description: Render HTML ke PNG menggunakan Aspose.HTML untuk .NET. Tutorial ini + menunjukkan cara mengonversi HTML ke gambar, menerapkan gaya tebal‑miring, antialiasing, + dan hinting teks. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Render html ke png di C# – langkah demi langkah dengan Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: Render HTML ke PNG di C# – panduan lengkap +url: /id/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-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 lengkap + +Jika Anda perlu **render html ke png** dengan cepat dan andal, panduan ini menunjukkan secara tepat cara melakukannya dengan Aspose.HTML untuk .NET. Anda juga akan melihat cara **mengonversi html ke gambar** sambil mengontrol gaya font, antialiasing, dan text hinting, sehingga PNG akhir terlihat tajam di layar apa pun. + +Kami akan mel walkthrough setiap langkah yang diperlukan—dari menginstal paket NuGet hingga menghasilkan file PNG siap produksi. Pada akhir tutorial Anda akan memiliki program mandiri yang dapat dijalankan dan dapat Anda masukkan ke proyek C# mana pun. + +## Apa yang akan Anda pelajari + +* Cara menyiapkan Aspose.HTML dalam proyek .NET. +* Cara membuat dokumen HTML dalam memori dan menerapkan enum `WebFontStyle.BoldItalic`. +* Cara mengaktifkan antialiasing dan text hinting untuk rendering yang lebih halus. +* Cara merender dokumen ke file PNG menggunakan `ImageRenderer`. +* Variasi umum seperti merender ke format gambar lain atau mengubah skala output. + +Tidak diperlukan alat eksternal atau langkah konversi gambar manual—semuanya terjadi secara programatik. + +## Prasyarat + +* .NET 6.0 SDK atau yang lebih baru (kode juga berfungsi dengan .NET Framework 4.7+). +* Visual Studio 2022 (atau IDE apa pun yang mendukung C#). +* Lisensi Aspose.HTML untuk .NET yang aktif (atau kunci evaluasi gratis). +* Familiaritas dasar dengan sintaks C#. + +> **Pro tip:** Jika Anda menggunakan evaluasi gratis, PNG yang dihasilkan akan berisi watermark. Lisensi yang dibeli akan menghapusnya secara otomatis. + +--- + +## Mengonversi html ke gambar – menyiapkan lingkungan + +1. **Buat proyek konsol baru** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Tambahkan paket NuGet Aspose.HTML** + + ```bash + dotnet add package Aspose.HTML + ``` + + Perintah ini mengunduh semua assembly yang Anda perlukan untuk merender HTML ke gambar. + +3. **(Opsional) Tambahkan file lisensi** + + Tempatkan file `Aspose.Total.lic` Anda di root proyek dan tambahkan baris berikut di awal `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + Langkah lisensi tidak diperlukan untuk percobaan gratis, tetapi mencegah watermark. + +## Render html ke png dengan Aspose.HTML + +Inti tutorial ini adalah proses lima langkah yang mencerminkan kode yang Anda berikan. Setiap langkah dijelaskan secara detail sehingga Anda memahami **mengapa** pemanggilan tersebut diperlukan, bukan hanya **apa** yang dilakukannya. + +### Langkah 1: Buat dokumen HTML + +Kami memulai dengan string HTML minimal yang berisi paragraf dengan gaya font Arial. Menggunakan `HTMLDocument` memungkinkan kami bekerja sepenuhnya dalam memori—tidak ada file sementara yang dibuat. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Mengapa ini penting:* `HTMLDocument` mem-parsing markup dan membangun DOM yang dapat dilalui renderer. Karena dokumen berada di memori, operasi ini cepat dan thread‑safe. + +### Langkah 2: Terapkan gaya tebal‑miring dengan `WebFontStyle` + +Aspose.HTML menyediakan enumerasi `WebFontStyle` untuk menggabungkan nilai CSS font‑weight dan font‑style yang umum. Menetapkannya ke `BoldItalic` membuat teks tampil tebal dan miring tanpa menulis CSS tambahan. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Mengapa menggunakan `WebFontStyle`?** +> Ini menghilangkan kebutuhan untuk menyematkan blok gaya atau stylesheet eksternal, mengurangi jumlah HTML yang harus Anda kelola saat merender gambar di sisi server. + +### Langkah 3: Aktifkan antialiasing untuk tepi yang lebih halus + +Antialiasing melicinkan batas bentuk dan teks, mengurangi piksel bergerigi terutama pada tampilan high‑DPI. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Dampak:* Ketika `UseAntialiasing` bernilai `true`, renderer menerapkan algoritma sub‑pixel yang menghasilkan PNG yang lebih bersih, terutama untuk garis diagonal atau ukuran font kecil. + +### Langkah 4: Aktifkan text hinting + +Text hinting menyelaraskan glyph ke grid piksel, membuat karakter tampak lebih tajam pada resolusi rendah. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*Kapan harus menonaktifkan:* Jika Anda nanti merender PDF berbasis vektor, Anda mungkin melewatkan hinting untuk mempertahankan outline asli. Untuk output PNG raster, hinting hampir selalu menguntungkan. + +### Langkah 5: Render dokumen ke file PNG + +Akhirnya, kami membuat `ImageRenderer`, melewatkan dokumen dan dua objek opsi, dan menulis output ke disk. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +Pemanggilan ini memblokir hingga file selesai ditulis, memastikan bahwa `output.png` ada saat program berakhir. + +#### Output yang diharapkan + +Menjalankan program membuat **output.png** di folder proyek. Gambar menampilkan kata **Hello** dalam Arial, tebal‑miring, terpusat pada latar putih, dengan tepi halus berkat antialiasing dan hinting. + +{.img-fluid alt="Contoh output render html ke png"} + +> **Catatan:** Gambar di atas adalah placeholder. Dalam proyek Anda sendiri PNG akan mencerminkan HTML persis yang Anda berikan. + +--- + +## Kode sumber lengkap yang dapat dijalankan + +Berikut adalah file `Program.cs` lengkap. Salin ke proyek konsol yang Anda buat sebelumnya, pulihkan paket NuGet, dan jalankan `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Menjalankan program mencetak: + +``` +HTML has been rendered to PNG successfully. +``` + +dan membuat `output.png` di samping executable. + +--- + +## Variasi dan kasus tepi + +### Merender ke format gambar lain + +`ImageRenderer` mendukung BMP, GIF, JPEG, dan TIFF. Ubah ekstensi file di `RenderToFile` dan opsional sesuaikan `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Mengubah skala output + +Jika Anda membutuhkan PNG resolusi lebih tinggi (mis., untuk tampilan retina), atur properti `ImageWidth` dan `ImageHeight`: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +Renderer akan meraster HTML pada ukuran yang ditentukan sambil mempertahankan kualitas vektor. + +### Menangani CSS kompleks + +Aspose.HTML sepenuhnya mendukung stylesheet eksternal, media query, dan SVG. Cukup muat HTML dari file atau URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +Pipeline rendering yang sama berlaku, sehingga Anda dapat **mengonversi html ke gambar** untuk halaman web apa pun, tidak hanya string sederhana. + +### Pertimbangan thread‑safety + +`HTMLDocument` dan `ImageRenderer` tidak thread‑safe. Jika Anda perlu merender banyak halaman secara paralel, buat instance `HTMLDocument` terpisah per thread atau gunakan pola thread‑pool. + +--- + +## Kesalahan umum dan cara menghindarinya + +| Masalah | Mengapa terjadi | Solusi | +|-------|----------------|-----| +| PNG kosong atau teks tidak muncul | Font tidak ditemukan di server | Instal font yang diperlukan di mesin atau sematkan melalui CSS `@font-face`. | +| Watermark muncul | Lisensi evaluasi digunakan | Terapkan file lisensi yang valid (`Aspose.Total.lic`). | +| Output buram | Antialiasing dinonaktifkan | Set `imageOptions.UseAntialiasing = true`. | +| Teks terlihat tipis | Hinting dinonaktifkan | Set `textOptions.UseHinting = true`. | + +--- + +## Kesimpulan + +Anda kini memiliki solusi lengkap end‑to‑end untuk **render html ke png** di C#. Tutorial ini mencakup instalasi Aspose.HTML, pembuatan dokumen HTML, penerapan gaya tebal‑miring, mengaktifkan antialiasing dan text hinting, dan akhirnya menulis file PNG ke disk. + +Dari sini Anda dapat menjelajahi: + +* **Mengonversi html ke gambar** untuk pemrosesan batch template email. +* Merender ke PDF dengan mengganti `ImageRenderer` dengan `PdfRenderer`. +* Menggunakan DOM API Aspose.HTML untuk memanipulasi HTML sebelum rendering. + +Silakan bereksperimen dengan CSS yang berbeda, kanvas yang lebih besar, atau format output alternatif. Selamat merender! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait erat yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber mencakup contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan menjelajahi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [Cara Menggunakan Aspose untuk Merender HTML ke PNG – Panduan Langkah‑per‑Langkah](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Cara Merender HTML ke PNG dengan Aspose – Panduan Lengkap](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Mengonversi HTML ke PNG di .NET dengan Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/italian/net/generate-jpg-and-png-images/_index.md b/html/italian/net/generate-jpg-and-png-images/_index.md index f6e8b2d8a7..c1703e5ae9 100644 --- a/html/italian/net/generate-jpg-and-png-images/_index.md +++ b/html/italian/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Impara a usare Aspose.HTML per .NET per manipolare documenti HTML, convertire HT Scopri come abilitare l'antialiasing durante la conversione di documenti DOCX in immagini PNG o JPG con Aspose.HTML per .NET. ### [Converti docx in PNG – crea archivio zip C# tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Impara a convertire documenti DOCX in PNG e a comprimerli in un archivio ZIP usando C# e Aspose.HTML. +### [Render HTML in PNG con C# – guida completa](./render-html-to-png-in-c-complete-guide/) +Scopri come convertire HTML in immagini PNG usando C# con Aspose.HTML, passo dopo passo, con esempi pratici. ## Conclusione diff --git a/html/italian/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/italian/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..7c59e40669 --- /dev/null +++ b/html/italian/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,340 @@ +--- +category: general +date: 2026-08-06 +description: Renderizza HTML in PNG con Aspose.HTML in C#. Scopri come convertire + HTML in immagine, applicare stili di carattere, antialiasing e hinting del testo + in un unico esempio eseguibile. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: it +lastmod: 2026-08-06 +og_description: Renderizza HTML in PNG usando Aspose.HTML per .NET. Questo tutorial + mostra come convertire HTML in immagine, applicare lo stile grassetto‑corsivo, l'anti‑aliasing + e il hinting del testo. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Renderizza HTML in PNG in C# – passo passo con Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: Renderizza HTML in PNG in C# – guida completa +url: /it/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Renderizza html in png in C# – guida completa + +Se hai bisogno di **renderizzare html in png** rapidamente e in modo affidabile, questa guida ti mostra esattamente come farlo con Aspose.HTML per .NET. Vedrai anche come **convertire html in immagine** controllando lo stile del font, l'antialiasing e il text hinting, così il PNG finale appare nitido su qualsiasi schermo. + +Percorreremo tutti i passaggi necessari—dall'installazione del pacchetto NuGet alla produzione di un file PNG pronto per la produzione. Alla fine del tutorial avrai un programma autonomo, eseguibile, che potrai inserire in qualsiasi progetto C#. + +## Cosa imparerai + +* Come configurare Aspose.HTML in un progetto .NET. +* Come creare un documento HTML in memoria e applicare l’enumerazione `WebFontStyle.BoldItalic`. +* Come abilitare l'antialiasing e il text hinting per un rendering più fluido. +* Come renderizzare il documento in un file PNG usando `ImageRenderer`. +* Varianti comuni, come il rendering in altri formati immagine o il ridimensionamento dell'output. + +Nessuno strumento esterno o passaggi manuali di conversione immagine è necessario—tutto avviene programmaticamente. + +## Prerequisiti + +* .NET 6.0 SDK o successivo (il codice funziona anche con .NET Framework 4.7+). +* Visual Studio 2022 (o qualsiasi IDE che supporti C#). +* Una licenza attiva di Aspose.HTML per .NET (o una chiave di valutazione gratuita). +* Familiarità di base con la sintassi C#. + +> **Pro tip:** Se utilizzi la valutazione gratuita, il PNG generato conterrà una filigrana. Una licenza acquistata la rimuove automaticamente. + +--- + +## Convertire html in immagine – configurare l'ambiente + +1. **Create a new console project** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Add the Aspose.HTML NuGet package** + + ```bash + dotnet add package Aspose.HTML + ``` + + This command pulls in all the assemblies you need for rendering HTML to images. + +3. **(Optional) Add a license file** + + Place your `Aspose.Total.lic` file in the project root and add the following line at the start of `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + The license step is not required for the free trial, but it prevents the watermark. + +## Renderizzare html in png con Aspose.HTML + +Il nucleo del tutorial è un processo in cinque passaggi che rispecchia il codice fornito. Ogni passo è spiegato in dettaglio così capirai **perché** la chiamata è necessaria, non solo **cosa** fa. + +### Passo 1: Creare il documento HTML + +Iniziamo con una stringa HTML minimale che contiene un paragrafo stilizzato con il font Arial. Usare `HTMLDocument` ci permette di lavorare interamente in memoria—non vengono creati file temporanei. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Perché è importante:* `HTMLDocument` analizza il markup e costruisce un DOM che il renderer può attraversare. Poiché il documento vive in memoria, l'operazione è veloce e thread‑safe. + +### Passo 2: Applicare lo stile grassetto‑corsivo con `WebFontStyle` + +Aspose.HTML espone l’enumerazione `WebFontStyle` per combinare i valori CSS comuni di font‑weight e font‑style. Impostandola su `BoldItalic` il testo appare sia in grassetto che in corsivo senza scrivere CSS aggiuntivo. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Perché usare `WebFontStyle`?** +> Elimina la necessità di incorporare un blocco di stile o un foglio di stile esterno, riducendo la quantità di HTML da gestire durante il rendering di immagini lato server. + +### Passo 3: Abilitare l'antialiasing per bordi più lisci + +L'antialiasing smussa i bordi di forme e testo, riducendo i pixel a scalini soprattutto su display ad alta DPI. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Impatto:* Quando `UseAntialiasing` è `true`, il renderer applica un algoritmo sub‑pixel che produce un PNG più pulito, in particolare per linee diagonali o font di piccole dimensioni. + +### Passo 4: Attivare il text hinting + +Il text hinting allinea i glifi alla griglia dei pixel, rendendo i caratteri più nitidi a bassa risoluzione. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*Quando disabilitarlo:* Se in seguito renderizzi PDF basati su vettori, potresti saltare l'hinting per preservare il contorno originale. Per l'output PNG raster, l'hinting è quasi sempre vantaggioso. + +### Passo 5: Renderizzare il documento in un file PNG + +Infine, creiamo un `ImageRenderer`, passiamo il documento e i due oggetti di opzione, e scriviamo l'output su disco. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +La chiamata blocca l'esecuzione finché il file non è completamente scritto, garantendo che `output.png` esista al termine del programma. + +#### Output previsto + +L'esecuzione del programma crea **output.png** nella cartella del progetto. L'immagine mostra la parola **Hello** in Arial, grassetto‑corsivo, centrata su uno sfondo bianco, con bordi lisci grazie a antialiasing e hinting. + +{.img-fluid alt="Esempio di output di render html in png"} + +> **Nota:** L'immagine sopra è un segnaposto. Nel tuo progetto il PNG rifletterà l'HTML esatto fornito. + +--- + +## Codice sorgente completo e eseguibile + +Di seguito trovi il file `Program.cs` completo. Copialo nel progetto console creato in precedenza, ripristina i pacchetti NuGet e avvia `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +L'esecuzione del programma stampa: + +``` +HTML has been rendered to PNG successfully. +``` + +e crea `output.png` accanto all'eseguibile. + +--- + +## Varianti e casi limite + +### Renderizzare in altri formati immagine + +`ImageRenderer` supporta BMP, GIF, JPEG e TIFF. Cambia l'estensione del file in `RenderToFile` e, se necessario, regola `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Ridimensionare l'output + +Se ti serve un PNG a risoluzione più alta (ad esempio per display Retina), imposta le proprietà `ImageWidth` e `ImageHeight`: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +Il renderer rasterizzerà l'HTML nella dimensione specificata mantenendo la qualità vettoriale. + +### Gestire CSS complessi + +Aspose.HTML supporta pienamente fogli di stile esterni, media query e SVG. Basta caricare l'HTML da un file o da un URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +La stessa pipeline di rendering si applica, così puoi **convertire html in immagine** per qualsiasi pagina web, non solo per stringhe semplici. + +### Considerazioni sulla thread‑safety + +`HTMLDocument` e `ImageRenderer` non sono thread‑safe. Se devi renderizzare molte pagine in parallelo, crea un'istanza separata di `HTMLDocument` per ogni thread o utilizza un pattern di thread‑pool. + +--- + +## Problemi comuni e come evitarli + +| Problema | Perché accade | Soluzione | +|----------|----------------|-----------| +| PNG è vuoto o manca il testo | Font non trovato sul server | Installa il font richiesto sulla macchina o incorporalo tramite CSS `@font-face`. | +| Appare la filigrana | Licenza di valutazione utilizzata | Applica un file di licenza valido (`Aspose.Total.lic`). | +| L'output è sfocato | Antialiasing disabilitato | Imposta `imageOptions.UseAntialiasing = true`. | +| Il testo appare sottile | Hinting disabilitato | Imposta `textOptions.UseHinting = true`. | + +--- + +## Conclusione + +Ora disponi di una soluzione solida, end‑to‑end, per **renderizzare html in png** in C#. Il tutorial ha coperto l'installazione di Aspose.HTML, la creazione di un documento HTML, l'applicazione dello stile grassetto‑corsivo, l'abilitazione di antialiasing e text hinting, e infine la scrittura di un file PNG su disco. + +Da qui puoi approfondire: + +* **Convertire html in immagine** per l'elaborazione batch di template email. +* Renderizzare in PDF sostituendo `ImageRenderer` con `PdfRenderer`. +* Usare l'API DOM di Aspose.HTML per manipolare l'HTML prima del rendering. + +Sentiti libero di sperimentare con CSS diversi, canvas più grandi o formati di output alternativi. Buon rendering! + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Come usare Aspose per renderizzare HTML in PNG – Guida passo‑passo](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Come renderizzare HTML in PNG con Aspose – Guida completa](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Convertire HTML in PNG in .NET con Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/japanese/net/generate-jpg-and-png-images/_index.md b/html/japanese/net/generate-jpg-and-png-images/_index.md index 57de57175f..99d03b0d7f 100644 --- a/html/japanese/net/generate-jpg-and-png-images/_index.md +++ b/html/japanese/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,7 @@ Aspose.HTML for .NET を使用して HTML ドキュメントを操作したり DOCX 文書を PNG または JPG 画像に変換する際に、アンチエイリアシングを有効にして高品質な出力を得る手順を解説します。 ### [DOCX を PNG に変換 – ZIP アーカイブを作成する C# チュートリアル](./convert-docx-to-png-create-zip-archive-c-tutorial/) C# で DOCX を PNG に変換し、ZIP アーカイブを作成する方法を学びます。 +### [C# で HTML を PNG にレンダリングする完全ガイド](./render-html-to-png-in-c-complete-guide/) ## 結論 diff --git a/html/japanese/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/japanese/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..4d303fb61e --- /dev/null +++ b/html/japanese/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,334 @@ +--- +category: general +date: 2026-08-06 +description: C# で Aspose.HTML を使用して HTML を PNG にレンダリングします。HTML を画像に変換し、フォントスタイル、アンチエイリアス、テキストヒンティングを適用する方法を、単一の実行可能サンプルで学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: ja +lastmod: 2026-08-06 +og_description: .NET 用 Aspose.HTML を使用して HTML を PNG にレンダリングします。このチュートリアルでは、HTML を画像に変換し、太字・斜体のスタイリング、アンチエイリアシング、テキストヒンティングを適用する方法を示します。 +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: C#でHTMLをPNGにレンダリング – Aspose.HTMLでステップバイステップ +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: C#でHTMLをPNGにレンダリングする完全ガイド +url: /ja/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で HTML を PNG にレンダリングする – 完全ガイド + +HTML を **PNG にレンダリング** したい場合、Aspose.HTML for .NET を使えば迅速かつ確実に実現できます。このガイドでは、フォントスタイル、アンチエイリアシング、テキストヒンティングを制御しながら **HTML を画像に変換** する方法を詳しく解説します。最終的な PNG はどの画面でも鮮明に表示されます。 + +NuGet パッケージのインストールから、実運用可能な PNG ファイルの生成まで、必要な手順をすべて解説します。チュートリアルの最後までに、任意の C# プロジェクトに組み込める、自己完結型の実行可能プログラムが手に入ります。 + +## 学べること + +* .NET プロジェクトへの Aspose.HTML の設定方法 +* メモリ上で HTML ドキュメントを作成し、`WebFontStyle.BoldItalic` 列挙体を適用する方法 +* アンチエイリアシングとテキストヒンティングを有効にして滑らかな描画を実現する方法 +* `ImageRenderer` を使ってドキュメントを PNG ファイルにレンダリングする手順 +* 他の画像形式へのレンダリングや出力サイズのスケーリングなど、一般的なバリエーション + +外部ツールや手動での画像変換は不要です。すべてプログラム上で完結します。 + +## 前提条件 + +* .NET 6.0 SDK 以降(.NET Framework 4.7+ でも動作します) +* Visual Studio 2022(または C# をサポートする任意の IDE) +* 有効な Aspose.HTML for .NET ライセンス(または無料評価キー) +* C# の基本的な構文に関する知識 + +> **プロのコツ:** 無料評価版を使用している場合、生成される PNG に透かしが入ります。購入ライセンスを適用すると自動的に透かしが除去されます。 + +--- + +## Convert html to image – 環境設定 + +1. **新しいコンソールプロジェクトを作成** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Aspose.HTML NuGet パッケージを追加** + + ```bash + dotnet add package Aspose.HTML + ``` + + このコマンドで、HTML を画像にレンダリングするために必要なすべてのアセンブリが取得されます。 + +3. **(オプション)ライセンスファイルを追加** + + プロジェクトのルートに `Aspose.Total.lic` ファイルを配置し、`Program.cs` の先頭に次の行を追加します。 + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + 無料トライアルでも透かしは入りますが、ライセンスを設定すると透かしが除去されます。 + +## Aspose.HTML で html を png にレンダリング + +本チュートリアルの中心は、提供されたコードに対応した 5 ステップのプロセスです。各ステップでは、**何を** 行うかだけでなく、**なぜ** その呼び出しが必要なのかも詳しく説明します。 + +### Step 1: HTML ドキュメントの作成 + +Arial フォントでスタイル付けされた段落を含む最小限の HTML 文字列から開始します。`HTMLDocument` を使用することで、完全にメモリ上で作業でき、テンポラリファイルは生成されません。 + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*重要性:* `HTMLDocument` はマークアップを解析し、レンダラが走査できる DOM を構築します。ドキュメントがメモリ上にあるため、処理は高速でスレッドセーフです。 + +### Step 2: `WebFontStyle` で太字‑斜体を適用 + +Aspose.HTML は `WebFontStyle` 列挙体を提供し、一般的な CSS の `font-weight` と `font-style` の組み合わせを簡単に指定できます。`BoldItalic` を設定すると、追加の CSS を書かずにテキストを太字かつ斜体にできます。 + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **`WebFontStyle` を使う理由** +> スタイルブロックや外部スタイルシートを埋め込む必要がなくなるため、サーバーサイドで画像を生成する際の HTML 管理が大幅に簡素化されます。 + +### Step 3: アンチエイリアシングを有効化して滑らかなエッジに + +アンチエイリアシングは形状やテキストの境界を滑らかにし、特に高 DPI ディスプレイでのギザギザを低減します。 + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*影響:* `UseAntialiasing` が `true` の場合、サブピクセルアルゴリズムが適用され、特に斜め線や小さなフォントサイズでクリーンな PNG が生成されます。 + +### Step 4: テキストヒンティングを有効化 + +テキストヒンティングはグリフをピクセルグリッドに合わせ、低解像度でも文字をシャープに見せます。 + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*無効にすべきケース:* 後でベクターベースの PDF を生成する場合は、元のアウトラインを保持するためにヒンティングをスキップすることがあります。ラスタ PNG 出力では、ほぼ常に有効にした方が良いです。 + +### Step 5: ドキュメントを PNG ファイルにレンダリング + +最後に `ImageRenderer` を作成し、ドキュメントとオプションオブジェクトを渡して出力をディスクに書き込みます。 + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +この呼び出しはファイルが完全に書き込まれるまでブロックされるため、プログラム終了時に `output.png` が確実に存在します。 + +#### 期待される出力 + +プログラム実行後、プロジェクトフォルダーに **output.png** が作成されます。画像は白背景に Arial の太字‑斜体「Hello」テキストが中央に配置され、アンチエイリアシングとヒンティングによりエッジが滑らかです。 + +{.img-fluid alt="Render html to png example output"} + +> **注:** 上の画像はプレースホルダーです。実際のプロジェクトでは、提供した HTML に合わせた PNG が生成されます。 + +--- + +## 完全な実行可能ソースコード + +以下が `Program.cs` の全コードです。先ほど作成したコンソールプロジェクトに貼り付け、NuGet パッケージを復元して `dotnet run` を実行してください。 + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +プログラム実行時の出力: + +``` +HTML has been rendered to PNG successfully. +``` + +そして実行ファイルの隣に `output.png` が生成されます。 + +--- + +## バリエーションとエッジケース + +### 他の画像形式へのレンダリング + +`ImageRenderer` は BMP、GIF、JPEG、TIFF もサポートしています。`RenderToFile` の拡張子を変更し、必要に応じて `ImageRenderingOptions` を調整してください。 + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### 出力のスケーリング + +Retina ディスプレイ向けに高解像度 PNG が必要な場合は、`ImageWidth` と `ImageHeight` プロパティを設定します。 + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +指定したサイズで HTML がラスタライズされ、ベクタ品質が保たれます。 + +### 複雑な CSS の取り扱い + +Aspose.HTML は外部スタイルシート、メディアクエリ、SVG をフルサポートします。HTML をファイルまたは URL からロードすれば同じパイプラインで **HTML を画像に変換** できます。 + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +### スレッドセーフの考慮 + +`HTMLDocument` と `ImageRenderer` はスレッドセーフではありません。多数のページを並列でレンダリングする場合は、スレッドごとに別々の `HTMLDocument` インスタンスを作成するか、スレッドプールパターンを採用してください。 + +--- + +## よくある落とし穴と回避策 + +| 問題 | 発生原因 | 対策 | +|------|----------|------| +| PNG が空白または文字が表示されない | サーバーにフォントがインストールされていない | 必要なフォントをマシンにインストールするか、CSS の `@font-face` で埋め込む | +| 透かしが表示される | 評価版ライセンスを使用している | 有効なライセンスファイル(`Aspose.Total.lic`)を適用する | +| 出力がぼやける | アンチエイリアシングが無効 | `imageOptions.UseAntialiasing = true` を設定 | +| 文字が細く見える | ヒンティングが無効 | `textOptions.UseHinting = true` を設定 | + +--- + +## 結論 + +これで **C# で HTML を PNG にレンダリング** するための、実践的かつエンドツーエンドのソリューションが手に入りました。チュートリアルでは、Aspose.HTML のインストール、HTML ドキュメントの作成、太字‑斜体スタイルの適用、アンチエイリアシングとテキストヒンティングの有効化、そして PNG ファイルへの書き出しまでを網羅しました。 + +次のステップとしては: + +* バッチ処理で **HTML を画像に変換** する +* `ImageRenderer` を `PdfRenderer` に置き換えて PDF にレンダリング +* Aspose.HTML の DOM API を使って、レンダリング前に HTML を操作 + +さまざまな CSS、キャンバスサイズ、出力形式で実験してみてください。快適なレンダリングをお楽しみください! + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで学んだ技術を応用した関連トピックを扱っています。各リソースには、ステップバイステップの解説と完全なコード例が含まれています。 + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Convert HTML to PNG in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/korean/net/generate-jpg-and-png-images/_index.md b/html/korean/net/generate-jpg-and-png-images/_index.md index 2f2fd11d08..7099a8e427 100644 --- a/html/korean/net/generate-jpg-and-png-images/_index.md +++ b/html/korean/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET을 .NET 프로젝트에 통합하는 것은 번거롭지 DOCX 문서를 PNG 또는 JPG 이미지로 변환할 때 안티앨리어싱을 적용하는 방법을 단계별로 안내합니다. ### [DOCX를 PNG로 변환하고 ZIP 아카이브 만들기 C# 튜토리얼](./convert-docx-to-png-create-zip-archive-c-tutorial/) C#을 사용해 DOCX 파일을 PNG 이미지로 변환하고, 결과를 ZIP 파일로 압축하는 방법을 단계별로 안내합니다. +### [C#에서 HTML을 PNG로 렌더링하는 완전 가이드](./render-html-to-png-in-c-complete-guide/) +C#을 사용해 HTML을 PNG 이미지로 변환하는 전체 과정과 코드를 단계별로 안내합니다. ## 결론 diff --git a/html/korean/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/korean/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..f06e52567d --- /dev/null +++ b/html/korean/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,336 @@ +--- +category: general +date: 2026-08-06 +description: C#에서 Aspose.HTML을 사용해 HTML을 PNG로 렌더링합니다. HTML을 이미지로 변환하고, 폰트 스타일 적용, + 안티앨리어싱 및 텍스트 힌팅을 하나의 실행 가능한 예제로 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: ko +lastmod: 2026-08-06 +og_description: Aspose.HTML for .NET을 사용하여 HTML을 PNG로 렌더링합니다. 이 튜토리얼에서는 HTML을 이미지로 + 변환하고, 굵은‑기울임 스타일을 적용하며, 안티앨리어싱 및 텍스트 힌팅을 수행하는 방법을 보여줍니다. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: C#에서 HTML을 PNG로 렌더링 – Aspose.HTML를 사용한 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: C#에서 HTML을 PNG로 렌더링하기 – 완전 가이드 +url: /ko/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 HTML을 PNG로 렌더링 – 완전 가이드 + +빠르고 안정적으로 **HTML을 PNG로 렌더링**해야 한다면, 이 가이드는 Aspose.HTML for .NET을 사용하여 정확히 어떻게 하는지 보여줍니다. 또한 **HTML을 이미지로 변환**하면서 글꼴 스타일, 안티앨리어싱, 텍스트 힌팅을 제어하는 방법을 확인할 수 있어 최종 PNG가 어떤 화면에서도 선명하게 표시됩니다. + +NuGet 패키지 설치부터 프로덕션 수준의 PNG 파일 생성까지 필요한 모든 단계를 차근차근 안내합니다. 튜토리얼이 끝날 때쯤이면 어떤 C# 프로젝트에든 넣어 사용할 수 있는 독립 실행형 프로그램을 얻게 됩니다. + +## 배울 내용 + +* .NET 프로젝트에 Aspose.HTML을 설정하는 방법. +* 메모리 내 HTML 문서를 생성하고 `WebFontStyle.BoldItalic` 열거형을 적용하는 방법. +* 부드러운 렌더링을 위해 안티앨리어싱과 텍스트 힌팅을 활성화하는 방법. +* `ImageRenderer`를 사용해 문서를 PNG 파일로 렌더링하는 방법. +* 다른 이미지 형식으로 렌더링하거나 출력 크기를 조정하는 등 일반적인 변형 방법. + +외부 도구나 수동 이미지 변환 단계가 필요하지 않습니다—모든 작업이 프로그래밍 방식으로 이루어집니다. + +## 사전 요구 사항 + +* .NET 6.0 SDK 이상(코드는 .NET Framework 4.7+에서도 작동합니다). +* Visual Studio 2022(또는 C#을 지원하는 IDE). +* 활성화된 Aspose.HTML for .NET 라이선스(또는 무료 평가 키). +* C# 구문에 대한 기본적인 이해. + +> **프로 팁:** 무료 평가판을 사용하는 경우 생성된 PNG에 워터마크가 포함됩니다. 구매한 라이선스를 적용하면 자동으로 제거됩니다. + +--- + +## HTML을 이미지로 변환 – 환경 설정 + +1. **새 콘솔 프로젝트 만들기** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Aspose.HTML NuGet 패키지 추가** + + ```bash + dotnet add package Aspose.HTML + ``` + + 이 명령은 HTML을 이미지로 렌더링하는 데 필요한 모든 어셈블리를 가져옵니다. + +3. **(선택) 라이선스 파일 추가** + + 프로젝트 루트에 `Aspose.Total.lic` 파일을 배치하고 `Program.cs` 시작 부분에 다음 줄을 추가합니다: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + 무료 평가판에서는 라이선스 단계가 필요 없지만, 워터마크를 방지할 수 있습니다. + +## Aspose.HTML으로 HTML을 PNG로 렌더링 + +튜토리얼의 핵심은 제공된 코드를 그대로 따라가는 다섯 단계 프로세스입니다. 각 단계는 왜 해당 호출이 필요한지(**why**)와 무엇을 하는지(**what**)를 자세히 설명합니다. + +### 단계 1: HTML 문서 만들기 + +Arial 글꼴로 스타일링된 단락을 포함하는 최소 HTML 문자열로 시작합니다. `HTMLDocument`를 사용하면 완전히 메모리 내에서 작업할 수 있어 임시 파일이 생성되지 않습니다. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*왜 중요한가:* `HTMLDocument`는 마크업을 파싱하고 렌더러가 순회할 수 있는 DOM을 구축합니다. 문서가 메모리 내에 존재하므로 작업이 빠르고 스레드‑안전합니다. + +### 단계 2: `WebFontStyle`으로 굵게‑기울임 스타일 적용 + +Aspose.HTML은 일반적인 CSS font-weight와 font-style 값을 결합할 수 있는 `WebFontStyle` 열거형을 제공합니다. 이를 `BoldItalic`으로 설정하면 추가 CSS를 작성하지 않고도 텍스트가 굵게와 기울임 모두 적용됩니다. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **왜 `WebFontStyle`을 사용하나요?** +> 스타일 블록이나 외부 스타일시트를 삽입할 필요가 없어 서버‑사이드 이미지 렌더링 시 관리해야 할 HTML 양을 줄여줍니다. + +### 단계 3: 부드러운 가장자리를 위한 안티앨리어싱 활성화 + +안티앨리어싱은 도형과 텍스트의 경계를 부드럽게 하여, 특히 고해상도 디스플레이에서 거친 픽셀을 감소시킵니다. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*영향:* `UseAntialiasing`이 `true`이면 렌더러가 서브픽셀 알고리즘을 적용해 더 깨끗한 PNG를 생성합니다. 특히 대각선 선이나 작은 글꼴 크기에서 효과적입니다. + +### 단계 4: 텍스트 힌팅 활성화 + +텍스트 힌팅은 글리프를 픽셀 그리드에 맞추어 저해상도에서도 문자 모양을 더 선명하게 만듭니다. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*비활성화 시점:* 나중에 벡터 기반 PDF를 렌더링할 경우 원본 윤곽을 유지하기 위해 힌팅을 생략할 수 있습니다. 래스터 PNG 출력에서는 힌팅이 거의 항상 유리합니다. + +### 단계 5: 문서를 PNG 파일로 렌더링 + +마지막으로 `ImageRenderer`를 생성하고 문서와 두 옵션 객체를 전달한 뒤, 출력을 디스크에 기록합니다. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +이 호출은 파일이 완전히 기록될 때까지 차단되므로 프로그램 종료 시 `output.png`가 존재함을 보장합니다. + +#### 예상 출력 + +프로그램을 실행하면 프로젝트 폴더에 **output.png**가 생성됩니다. 이미지에는 Arial 글꼴의 굵게‑기울임 **Hello** 텍스트가 흰색 배경 중앙에 표시되며, 안티앨리어싱과 힌팅 덕분에 가장자리가 부드럽습니다. + +{.img-fluid alt="Render html to png 예시 출력"} + +> **참고:** 위 이미지는 자리표시자입니다. 실제 프로젝트에서는 제공한 HTML과 정확히 일치하는 PNG가 생성됩니다. + +--- + +## 전체 실행 가능한 소스 코드 + +아래는 전체 `Program.cs` 파일입니다. 앞서 만든 콘솔 프로젝트에 복사하고, NuGet 패키지를 복원한 뒤 `dotnet run`을 실행하세요. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +프로그램을 실행하면 다음이 출력됩니다: + +``` +HTML has been rendered to PNG successfully. +``` + +그리고 실행 파일 옆에 `output.png`가 생성됩니다. + +--- + +## 변형 및 엣지 케이스 + +### 다른 이미지 형식으로 렌더링 + +`ImageRenderer`는 BMP, GIF, JPEG, TIFF를 지원합니다. `RenderToFile`의 파일 확장자를 변경하고 필요에 따라 `ImageRenderingOptions`를 조정하세요: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### 출력 스케일링 + +고해상도 PNG가 필요할 경우(예: 레티나 디스플레이), `ImageWidth`와 `ImageHeight` 속성을 설정합니다: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +렌더러는 지정된 크기로 HTML을 래스터화하면서 벡터 품질을 유지합니다. + +### 복잡한 CSS 처리 + +Aspose.HTML은 외부 스타일시트, 미디어 쿼리, SVG를 완전히 지원합니다. 파일이나 URL에서 HTML을 로드하기만 하면 됩니다: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +동일한 렌더링 파이프라인이 적용되므로 단순 문자열뿐 아니라 모든 웹 페이지를 **HTML을 이미지로 변환**할 수 있습니다. + +### 스레드 안전성 고려 사항 + +`HTMLDocument`와 `ImageRenderer`는 스레드 안전하지 않습니다. 여러 페이지를 병렬로 렌더링해야 한다면 스레드당 별도의 `HTMLDocument` 인스턴스를 만들거나 스레드 풀 패턴을 사용하세요. + +--- + +## 흔히 발생하는 실수와 회피 방법 + +| 문제 | 발생 원인 | 해결 방법 | +|-------|----------------|-----| +| PNG가 비어 있거나 텍스트가 누락됨 | 서버에 글꼴이 없음 | 필요한 글꼴을 머신에 설치하거나 CSS `@font-face`로 포함하세요. | +| 워터마크가 표시됨 | 평가 라이선스 사용 | 유효한 라이선스 파일(`Aspose.Total.lic`)을 적용하세요. | +| 출력이 흐릿함 | 안티앨리어싱 비활성화 | `imageOptions.UseAntialiasing = true` 로 설정하세요. | +| 텍스트가 얇게 보임 | 힌팅 비활성화 | `textOptions.UseHinting = true` 로 설정하세요. | + +## 결론 + +이제 C#에서 **HTML을 PNG로 렌더링**하기 위한 견고한 엔드‑투‑엔드 솔루션을 갖추었습니다. 튜토리얼에서는 Aspose.HTML 설치, HTML 문서 생성, 굵게‑기울임 스타일 적용, 안티앨리어싱 및 텍스트 힌팅 활성화, 그리고 최종적으로 PNG 파일을 디스크에 저장하는 과정을 다루었습니다. + +다음 단계로는 다음을 탐색할 수 있습니다: + +* 이메일 템플릿의 일괄 처리를 위한 **HTML을 이미지로 변환**. +* `ImageRenderer`를 `PdfRenderer`로 교체하여 PDF로 렌더링. +* 렌더링 전에 HTML을 조작하기 위한 Aspose.HTML의 DOM API 사용. + +다양한 CSS, 더 큰 캔버스, 혹은 다른 출력 형식으로 실험해 보세요. 즐거운 렌더링 되세요! + +## 다음에 배울 내용은? + +다음 튜토리얼은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료에는 단계별 설명과 함께 완전한 코드 예제가 포함되어 있어 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색하는 데 도움이 됩니다. + +- [Aspose를 사용해 HTML을 PNG로 렌더링하는 방법 – 단계별 가이드](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Aspose로 HTML을 PNG로 렌더링하는 방법 – 완전 가이드](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [.NET에서 Aspose.HTML을 사용해 HTML을 PNG로 변환하기](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/polish/net/generate-jpg-and-png-images/_index.md b/html/polish/net/generate-jpg-and-png-images/_index.md index fff5f7a92b..a9ed5e1d64 100644 --- a/html/polish/net/generate-jpg-and-png-images/_index.md +++ b/html/polish/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,7 @@ Naucz się używać Aspose.HTML dla .NET do manipulowania dokumentami HTML, konw Dowiedz się, jak włączyć antyaliasing przy konwersji dokumentów DOCX do formatów PNG i JPG przy użyciu Aspose.HTML. ### [Konwertuj docx do png – utwórz archiwum zip w C# – samouczek](./convert-docx-to-png-create-zip-archive-c-tutorial/) Dowiedz się, jak konwertować pliki DOCX na obrazy PNG i spakować je do archiwum ZIP przy użyciu C# i Aspose.HTML. +### [Renderowanie HTML do PNG w C# – kompletny przewodnik](./render-html-to-png-in-c-complete-guide/) ## Wniosek diff --git a/html/polish/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/polish/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..51dc2b96ca --- /dev/null +++ b/html/polish/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,340 @@ +--- +category: general +date: 2026-08-06 +description: Renderuj HTML do PNG przy użyciu Aspose.HTML w C#. Dowiedz się, jak konwertować + HTML na obraz, stosować style czcionek, antyaliasing i podpowiedzi tekstowe w jednym, + gotowym do uruchomienia przykładzie. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: pl +lastmod: 2026-08-06 +og_description: Renderuj HTML do PNG przy użyciu Aspose.HTML dla .NET. Ten samouczek + pokazuje, jak konwertować HTML na obraz, zastosować stylizację pogrubioną‑pochyloną, + antyaliasing oraz hinting tekstu. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Renderowanie HTML do PNG w C# – krok po kroku z Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: Renderowanie HTML do PNG w C# – kompletny przewodnik +url: /pl/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< 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 + +Jeśli potrzebujesz szybko i niezawodnie **renderować html do png**, ten przewodnik pokaże Ci dokładnie, jak to zrobić przy użyciu Aspose.HTML dla .NET. Zobaczysz także, jak **konwertować html na obraz** kontrolując styl czcionki, antyaliasing i hinting tekstu, tak aby końcowy PNG wyglądał ostro na każdym ekranie. + +Przejdziemy przez każdy wymagany krok — od instalacji pakietu NuGet po wyprodukowanie gotowego do produkcji pliku PNG. Po zakończeniu samouczka będziesz mieć samodzielny, uruchamialny program, który możesz wstawić do dowolnego projektu C#. + +## Czego się nauczysz + +* Jak skonfigurować Aspose.HTML w projekcie .NET. +* Jak utworzyć dokument HTML w pamięci i zastosować wyliczenie `WebFontStyle.BoldItalic`. +* Jak włączyć antyaliasing i hinting tekstu dla płynniejszego renderowania. +* Jak renderować dokument do pliku PNG przy użyciu `ImageRenderer`. +* Typowe warianty, takie jak renderowanie do innych formatów obrazu lub skalowanie wyniku. + +Żadne zewnętrzne narzędzia ani ręczne kroki konwersji obrazu nie są wymagane — wszystko odbywa się programowo. + +## Wymagania wstępne + +* .NET 6.0 SDK lub nowszy (kod działa również z .NET Framework 4.7+). +* Visual Studio 2022 (lub dowolne IDE obsługujące C#). +* Aktywna licencja Aspose.HTML for .NET (lub darmowy klucz ewaluacyjny). +* Podstawowa znajomość składni C#. + +> **Wskazówka:** Jeśli używasz darmowej wersji ewaluacyjnej, wygenerowany PNG będzie zawierał znak wodny. Zakupiona licencja usuwa go automatycznie. + +--- + +## Konwertowanie html na obraz – przygotowanie środowiska + +1. **Utwórz nowy projekt konsolowy** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Dodaj pakiet NuGet Aspose.HTML** + + ```bash + dotnet add package Aspose.HTML + ``` + + To polecenie pobiera wszystkie zestawy, których potrzebujesz do renderowania HTML do obrazów. + +3. **(Opcjonalnie) Dodaj plik licencyjny** + + Umieść plik `Aspose.Total.lic` w katalogu głównym projektu i dodaj następującą linię na początku `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + Krok licencjonowania nie jest wymagany w wersji próbnej, ale zapobiega pojawieniu się znaku wodnego. + +## Renderowanie html do png przy użyciu Aspose.HTML + +Podstawą samouczka jest pięcioetapowy proces odzwierciedlający podany kod. Każdy krok jest szczegółowo wyjaśniony, abyś rozumiał **dlaczego** wywołanie jest potrzebne, a nie tylko **co** robi. + +### Krok 1: Utwórz dokument HTML + +Zaczynamy od minimalnego łańcucha HTML, który zawiera akapit sformatowany czcionką Arial. Użycie `HTMLDocument` pozwala pracować wyłącznie w pamięci — nie są tworzone żadne pliki tymczasowe. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Dlaczego to jest ważne:* `HTMLDocument` parsuje znacznik i buduje DOM, który renderer może przeglądać. Ponieważ dokument istnieje w pamięci, operacja jest szybka i bezpieczna wątkowo. + +### Krok 2: Zastosuj styl pogrubiony‑pochylony za pomocą `WebFontStyle` + +Aspose.HTML udostępnia wyliczenie `WebFontStyle`, aby połączyć typowe wartości CSS `font-weight` i `font-style`. Ustawienie go na `BoldItalic` sprawia, że tekst jest jednocześnie pogrubiony i pochylony bez dodatkowego CSS. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Dlaczego używać `WebFontStyle`?** +> Eliminujesz potrzebę osadzania bloku stylów lub zewnętrznego arkusza stylów, zmniejszając ilość HTML, którą musisz zarządzać przy renderowaniu obrazów po stronie serwera. + +### Krok 3: Włącz antyaliasing dla płynniejszych krawędzi + +Antialiasing wygładza krawędzie kształtów i tekstu, redukując ząbkowane piksele, szczególnie na wyświetlaczach o wysokiej rozdzielczości DPI. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Wpływ:* Gdy `UseAntialiasing` jest ustawione na `true`, renderer stosuje algorytm sub‑pikselowy, który daje czystszy PNG, szczególnie przy liniach ukośnych lub małych rozmiarach czcionki. + +### Krok 4: Aktywuj hinting tekstu + +Hinting tekstu wyrównuje glify do siatki pikseli, sprawiając, że znaki wyglądają ostrzej przy niskich rozdzielczościach. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*Kiedy wyłączyć:* Jeśli później renderujesz wektory PDF, możesz pominąć hinting, aby zachować oryginalny kontur. Dla wyjścia rastrowego PNG hinting jest prawie zawsze korzystny. + +### Krok 5: Renderuj dokument do pliku PNG + +Na koniec tworzymy `ImageRenderer`, przekazujemy dokument oraz dwa obiekty opcji i zapisujemy wynik na dysku. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +Wywołanie blokuje się, dopóki plik nie zostanie w pełni zapisany, co gwarantuje, że `output.png` istnieje po zakończeniu programu. + +#### Oczekiwany wynik + +Uruchomienie programu tworzy **output.png** w folderze projektu. Obraz przedstawia słowo **Hello** w Arial, pogrubione‑pochylone, wyśrodkowane na białym tle, z płynnymi krawędziami dzięki antyaliasingowi i hintingowi. + +{.img-fluid alt="Przykładowy wynik renderowania html do png"} + +> **Uwaga:** Powyższy obraz jest jedynie symbolem. W Twoim własnym projekcie PNG odzwierciedli dokładnie podany HTML. + +--- + +## Pełny, uruchamialny kod źródłowy + +Poniżej znajduje się kompletny plik `Program.cs`. Skopiuj go do wcześniej utworzonego projektu konsolowego, przywróć pakiety NuGet i uruchom `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Uruchomienie programu wypisuje: + +``` +HTML has been rendered to PNG successfully. +``` + +i tworzy `output.png` obok pliku wykonywalnego. + +--- + +## Warianty i przypadki brzegowe + +### Renderowanie do innych formatów obrazu + +`ImageRenderer` obsługuje BMP, GIF, JPEG i TIFF. Zmień rozszerzenie pliku w `RenderToFile` i opcjonalnie dostosuj `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Skalowanie wyjścia + +Jeśli potrzebujesz PNG o wyższej rozdzielczości (np. dla wyświetlaczy Retina), ustaw właściwości `ImageWidth` i `ImageHeight`: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +Renderer przetworzy HTML w podanym rozmiarze, zachowując jakość wektorową. + +### Obsługa złożonego CSS + +Aspose.HTML w pełni obsługuje zewnętrzne arkusze stylów, media queries i SVG. Po prostu wczytaj HTML z pliku lub URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +Ten sam pipeline renderowania ma zastosowanie, więc możesz **konwertować html na obraz** dla dowolnej strony internetowej, nie tylko prostych łańcuchów. + +### Rozważania dotyczące bezpieczeństwa wątków + +`HTMLDocument` i `ImageRenderer` nie są bezpieczne wątkowo. Jeśli musisz renderować wiele stron równocześnie, utwórz osobną instancję `HTMLDocument` dla każdego wątku lub zastosuj wzorzec puli wątków. + +--- + +## Typowe pułapki i jak ich uniknąć + +| Problem | Dlaczego się dzieje | Rozwiązanie | +|-------|----------------|-----| +| PNG jest pusty lub brakuje tekstu | Czcionka nie została znaleziona na serwerze | Zainstaluj wymaganą czcionkę na maszynie lub osadź ją za pomocą CSS `@font-face`. | +| Pojawia się znak wodny | Użyto licencji ewaluacyjnej | Użyj ważnego pliku licencyjnego (`Aspose.Total.lic`). | +| Wyjście jest rozmyte | Antialiasing wyłączony | Ustaw `imageOptions.UseAntialiasing = true`. | +| Tekst wygląda na cienki | Hinting wyłączony | Ustaw `textOptions.UseHinting = true`. | + +--- + +## Podsumowanie + +Masz teraz solidne, kompleksowe rozwiązanie do **renderowania html do png** w C#. Samouczek obejmował instalację Aspose.HTML, tworzenie dokumentu HTML, zastosowanie stylu pogrubiony‑pochylony, włączenie antyaliasingu i hintingu tekstu oraz zapis pliku PNG na dysku. + +Od tego momentu możesz eksplorować: + +* **Konwertować html na obraz** w celu przetwarzania wsadowego szablonów e‑mailowych. +* Renderowanie do PDF poprzez zamianę `ImageRenderer` na `PdfRenderer`. +* Korzystanie z API DOM Aspose.HTML do manipulacji HTML przed renderowaniem. + +Śmiało eksperymentuj z różnym CSS, większymi płótnami lub alternatywnymi formatami wyjściowymi. Szczęśliwego renderowania! + +## Co powinieneś się nauczyć dalej? + +Poniższe samouczki obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne, działające przykłady kodu oraz wyjaśnienia krok po kroku, pomagające opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Jak używać Aspose do renderowania HTML do PNG – przewodnik krok po kroku](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Jak renderować HTML do PNG przy użyciu Aspose – kompletny przewodnik](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Konwertowanie HTML do PNG w .NET z Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/portuguese/net/generate-jpg-and-png-images/_index.md b/html/portuguese/net/generate-jpg-and-png-images/_index.md index 25a4d8da7a..b73e7a7ba0 100644 --- a/html/portuguese/net/generate-jpg-and-png-images/_index.md +++ b/html/portuguese/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,7 @@ Aprenda a usar Aspose.HTML para .NET para manipular documentos HTML, converter H Aprenda a ativar antialiasing ao converter documentos DOCX em imagens PNG ou JPG usando Aspose.HTML para .NET. ### [Converter docx para png – criar arquivo zip em C# tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Aprenda a converter documentos DOCX em imagens PNG e compactá-los em um arquivo ZIP usando C# e Aspose.HTML. +### [Renderizar HTML para PNG em C# – guia completo](./render-html-to-png-in-c-complete-guide/) ## Conclusão diff --git a/html/portuguese/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/portuguese/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..6b57187d97 --- /dev/null +++ b/html/portuguese/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,332 @@ +--- +category: general +date: 2026-08-06 +description: Renderize HTML para PNG com Aspose.HTML em C#. Aprenda como converter + HTML em imagem, aplicar estilos de fonte, antialiasing e hinting de texto em um + único exemplo executável. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: pt +lastmod: 2026-08-06 +og_description: Renderize HTML para PNG usando Aspose.HTML para .NET. Este tutorial + mostra como converter HTML em imagem, aplicar estilo negrito‑itálico, antialiasing + e hinting de texto. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Renderizar HTML para PNG em C# – passo a passo com Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: Renderizar HTML para PNG em C# – guia completo +url: /pt/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Renderizar html para png em C# – guia completo + +Se você precisa **renderizar html para png** de forma rápida e confiável, este guia mostra exatamente como fazer isso com Aspose.HTML para .NET. Você também verá como **converter html para imagem** controlando o estilo da fonte, antialiasing e text hinting, para que o PNG final fique nítido em qualquer tela. + +Percorreremos cada passo necessário — desde a instalação do pacote NuGet até a produção de um arquivo PNG pronto para produção. Ao final do tutorial, você terá um programa autônomo e executável que pode ser inserido em qualquer projeto C#. + +## O que você aprenderá + +* Como configurar o Aspose.HTML em um projeto .NET. +* Como criar um documento HTML em memória e aplicar o enum `WebFontStyle.BoldItalic`. +* Como habilitar antialiasing e text hinting para renderização mais suave. +* Como renderizar o documento para um arquivo PNG usando `ImageRenderer`. +* Variações comuns, como renderizar para outros formatos de imagem ou dimensionar a saída. + +Nenhuma ferramenta externa ou etapas manuais de conversão de imagem são necessárias — tudo acontece programaticamente. + +## Pré-requisitos + +* .NET 6.0 SDK ou posterior (o código também funciona com .NET Framework 4.7+). +* Visual Studio 2022 (ou qualquer IDE que suporte C#). +* Uma licença ativa do Aspose.HTML for .NET (ou uma chave de avaliação gratuita). +* Familiaridade básica com a sintaxe C#. + +> **Dica profissional:** Se você estiver usando a avaliação gratuita, o PNG gerado conterá uma marca d'água. Uma licença comprada a remove automaticamente. + +--- + +## Converter html para imagem – configurando o ambiente + +1. **Criar um novo projeto de console** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Adicionar o pacote NuGet Aspose.HTML** + + ```bash + dotnet add package Aspose.HTML + ``` + + Este comando traz todas as assemblies necessárias para renderizar HTML em imagens. + +3. **(Opcional) Adicionar um arquivo de licença** + + Coloque seu arquivo `Aspose.Total.lic` na raiz do projeto e adicione a linha a seguir no início do `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + A etapa de licença não é necessária para a avaliação gratuita, mas impede a marca d'água. + +## Renderizar html para png com Aspose.HTML + +O núcleo do tutorial é um processo de cinco etapas que espelha o código fornecido. Cada etapa é explicada em detalhe para que você entenda **por que** a chamada é necessária, não apenas **o que** ela faz. + +### Etapa 1: Criar o documento HTML + +Começamos com uma string HTML mínima que contém um parágrafo estilizado com a fonte Arial. Usar `HTMLDocument` nos permite trabalhar totalmente na memória — nenhum arquivo temporário é criado. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Por que isso importa:* `HTMLDocument` analisa a marcação e constrói um DOM que o renderizador pode percorrer. Como o documento reside na memória, a operação é rápida e thread‑safe. + +### Etapa 2: Aplicar estilo negrito‑itálico com `WebFontStyle` + +Aspose.HTML expõe a enumeração `WebFontStyle` para combinar valores comuns de font‑weight e font‑style do CSS. Definir como `BoldItalic` faz o texto aparecer tanto em negrito quanto em itálico sem escrever CSS adicional. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Por que usar `WebFontStyle`?** +> Ele elimina a necessidade de incorporar um bloco de estilo ou folha de estilo externa, reduzindo a quantidade de HTML que você precisa gerenciar ao renderizar imagens no lado do servidor. + +### Etapa 3: Habilitar antialiasing para bordas mais suaves + +Antialiasing suaviza as bordas de formas e texto, reduzindo pixels serrilhados, especialmente em telas de alta DPI. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Impacto:* Quando `UseAntialiasing` está `true`, o renderizador aplica um algoritmo sub‑pixel que produz um PNG mais limpo, particularmente para linhas diagonais ou tamanhos de fonte pequenos. + +### Etapa 4: Ativar text hinting + +Text hinting alinha os glifos à grade de pixels, fazendo os caracteres parecerem mais nítidos em baixas resoluções. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*Quando desativar:* Se você estiver renderizando PDFs baseados em vetor posteriormente, pode pular o hinting para preservar o contorno original. Para saída PNG raster, o hinting é quase sempre benéfico. + +### Etapa 5: Renderizar o documento para um arquivo PNG + +Finalmente, criamos um `ImageRenderer`, passamos o documento e os dois objetos de opções, e gravamos a saída no disco. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +A chamada bloqueia até que o arquivo seja totalmente gravado, garantindo que `output.png` exista quando o programa terminar. + +#### Saída esperada + +Executar o programa cria **output.png** na pasta do projeto. A imagem mostra a palavra **Hello** em Arial, negrito‑itálico, centralizada em um fundo branco, com bordas suaves graças ao antialiasing e ao hinting. + +{.img-fluid alt="Exemplo de saída de renderização html para png"} + +> **Nota:** A imagem acima é um placeholder. No seu próprio projeto, o PNG refletirá o HTML exato que você forneceu. + +## Código-fonte completo e executável + +A seguir está o arquivo `Program.cs` completo. Copie-o para o projeto de console que você criou anteriormente, restaure os pacotes NuGet e execute `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Running the program prints: + +``` +HTML has been rendered to PNG successfully. +``` + +e cria `output.png` ao lado do executável. + +## Variações e casos de borda + +### Renderizando para outros formatos de imagem + +`ImageRenderer` suporta BMP, GIF, JPEG e TIFF. Altere a extensão do arquivo em `RenderToFile` e, opcionalmente, ajuste `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Dimensionando a saída + +Se você precisar de um PNG de alta resolução (por exemplo, para telas retina), defina as propriedades `ImageWidth` e `ImageHeight`: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +O renderizador rasterizará o HTML no tamanho especificado, preservando a qualidade vetorial. + +### Lidando com CSS complexo + +Aspose.HTML suporta totalmente folhas de estilo externas, media queries e SVG. Basta carregar o HTML de um arquivo ou URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +O mesmo pipeline de renderização se aplica, então você pode **converter html para imagem** para qualquer página web, não apenas strings simples. + +### Considerações sobre thread‑safety + +`HTMLDocument` e `ImageRenderer` não são thread‑safe. Se precisar renderizar muitas páginas em paralelo, crie uma instância separada de `HTMLDocument` por thread ou use um padrão de pool de threads. + +## Armadilhas comuns e como evitá‑las + +| Issue | Why it happens | Fix | +|-------|----------------|-----| +| PNG está em branco ou sem texto | Fonte não encontrada no servidor | Instale a fonte necessária na máquina ou incorpore-a via CSS `@font-face`. | +| Marca d'água aparece | Licença de avaliação usada | Aplique um arquivo de licença válido (`Aspose.Total.lic`). | +| Saída está borrada | Antialiasing desativado | Defina `imageOptions.UseAntialiasing = true`. | +| Texto parece fino | Hinting desativado | Defina `textOptions.UseHinting = true`. | + +## Conclusão + +Agora você tem uma solução completa e robusta para **renderizar html para png** em C#. O tutorial abordou a instalação do Aspose.HTML, a criação de um documento HTML, a aplicação de estilo negrito‑itálico, a habilitação de antialiasing e text hinting, e finalmente a gravação de um arquivo PNG no disco. + +A partir daqui, você pode explorar: + +* **Converter html para imagem** para processamento em lote de modelos de e‑mail. +* Renderizar para PDF trocando `ImageRenderer` por `PdfRenderer`. +* Usar a API DOM do Aspose.HTML para manipular HTML antes da renderização. + +Sinta-se à vontade para experimentar diferentes CSS, telas maiores ou formatos de saída alternativos. Boa renderização! + +## O que você deve aprender a seguir? + +Os tutoriais a seguir cobrem tópicos estreitamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Como usar Aspose para renderizar HTML para PNG – Guia passo a passo](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Como renderizar HTML para PNG com Aspose – Guia completo](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Converter HTML para PNG em .NET com Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/russian/net/generate-jpg-and-png-images/_index.md b/html/russian/net/generate-jpg-and-png-images/_index.md index 74f0059491..01e5ea257a 100644 --- a/html/russian/net/generate-jpg-and-png-images/_index.md +++ b/html/russian/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML для .NET предлагает простой метод прео Узнайте, как включить сглаживание при преобразовании DOCX в PNG или JPG с помощью Aspose.HTML для .NET. ### [Конвертация DOCX в PNG – создание ZIP-архива на C#](./convert-docx-to-png-create-zip-archive-c-tutorial/) Узнайте, как преобразовать файлы DOCX в PNG и упаковать их в ZIP-архив с помощью C# и Aspose.HTML. +### [Рендеринг HTML в PNG на C# – полное руководство](./render-html-to-png-in-c-complete-guide/) +Полное руководство по рендерингу HTML в PNG с помощью Aspose.HTML в C#. ## Заключение diff --git a/html/russian/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/russian/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..1c2c7fed86 --- /dev/null +++ b/html/russian/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,340 @@ +--- +category: general +date: 2026-08-06 +description: Рендеринг HTML в PNG с помощью Aspose.HTML на C#. Узнайте, как преобразовать + HTML в изображение, применить стили шрифтов, сглаживание и хинтинг текста в одном + готовом примере. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: ru +lastmod: 2026-08-06 +og_description: Рендеринг HTML в PNG с помощью Aspose.HTML для .NET. Этот учебник + показывает, как преобразовать HTML в изображение, применить полужирное и курсивное + оформление, сглаживание и хинтинг текста. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Преобразование HTML в PNG в C# – пошаговое руководство с Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: Рендер HTML в PNG на C# – полное руководство +url: /ru/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-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 guide + +Если вам нужно **быстро и надёжно отрисовать html в png**, это руководство покажет, как сделать это с помощью Aspose.HTML для .NET. Вы также увидите, как **конвертировать html в изображение**, управляя стилем шрифта, сглаживанием и подсказками текста, чтобы конечный PNG выглядел чётко на любом экране. + +Мы пройдём каждый необходимый шаг — от установки пакета NuGet до получения готового к использованию PNG‑файла. К концу урока у вас будет самостоятельная, исполняемая программа, которую можно добавить в любой проект C#. + +## What you’ll learn + +* Как настроить Aspose.HTML в проекте .NET. +* Как создать HTML‑документ в памяти и применить перечисление `WebFontStyle.BoldItalic`. +* Как включить сглаживание и подсказки текста для более плавного рендеринга. +* Как отрисовать документ в PNG‑файл с помощью `ImageRenderer`. +* Распространённые варианты, такие как рендеринг в другие форматы изображений или масштабирование вывода. + +Никакие внешние инструменты или ручные шаги конвертации изображений не требуются — всё происходит программно. + +## Prerequisites + +* .NET 6.0 SDK или новее (код также работает с .NET Framework 4.7+). +* Visual Studio 2022 (или любая IDE, поддерживающая C#). +* Действующая лицензия Aspose.HTML для .NET (или бесплатный оценочный ключ). +* Базовое знакомство с синтаксисом C#. + +> **Pro tip:** Если вы используете бесплатную оценочную версию, сгенерированный PNG будет содержать водяной знак. Приобретённая лицензия удалит его автоматически. + +--- + +## Convert html to image – setting up the environment + +1. **Create a new console project** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Add the Aspose.HTML NuGet package** + + ```bash + dotnet add package Aspose.HTML + ``` + + Эта команда загрузит все необходимые сборки для рендеринга HTML в изображения. + +3. **(Optional) Add a license file** + + Поместите файл `Aspose.Total.lic` в корень проекта и добавьте следующую строку в начало `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + Шаг с лицензией не обязателен для бесплатной пробной версии, но он устраняет водяной знак. + +## Render html to png with Aspose.HTML + +Ядро руководства — пятишаговый процесс, соответствующий приведённому коду. Каждый шаг подробно объяснён, чтобы вы понимали **почему** вызов необходим, а не только **что** он делает. + +### Step 1: Create the HTML document + +Мы начинаем с минимальной HTML‑строки, содержащей абзац, стилизованный шрифтом Arial. Использование `HTMLDocument` позволяет работать полностью в памяти — временные файлы не создаются. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Why this matters:* `HTMLDocument` разбирает разметку и строит DOM, по которому может проходить рендерер. Поскольку документ находится в памяти, операция быстра и потокобезопасна. + +### Step 2: Apply bold‑italic styling with `WebFontStyle` + +Aspose.HTML предоставляет перечисление `WebFontStyle` для комбинирования типичных значений CSS `font-weight` и `font-style`. Установка его в `BoldItalic` делает текст одновременно жирным и курсивным без необходимости писать дополнительный CSS. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Why use `WebFontStyle`?** +> Это устраняет необходимость встраивать блок стилей или внешнюю таблицу стилей, уменьшая объём HTML, который нужно управлять при серверном рендеринге изображений. + +### Step 3: Enable antialiasing for smoother edges + +Сглаживание (antialiasing) делает границы фигур и текста более плавными, уменьшая «зубцы», особенно на дисплеях с высоким DPI. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Impact:* Когда `UseAntialiasing` равно `true`, рендерер применяет субпиксельный алгоритм, дающий более чистый PNG, особенно для диагональных линий или небольших размеров шрифта. + +### Step 4: Activate text hinting + +Подсказки текста (text hinting) выравнивают глифы по пиксельной сетке, делая символы острее при низком разрешении. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*When to disable:* Если вы позже будете рендерить векторные PDF, подсказки можно отключить, чтобы сохранить оригинальный контур. Для растрового PNG‑вывода подсказки почти всегда полезны. + +### Step 5: Render the document to a PNG file + +Наконец, мы создаём `ImageRenderer`, передаём документ и два объекта параметров, а затем записываем результат на диск. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +Вызов блокирует выполнение до полного завершения записи файла, гарантируя, что `output.png` существует к моменту завершения программы. + +#### Expected output + +Запуск программы создаёт **output.png** в папке проекта. На изображении слово **Hello** шрифтом Arial, жирным курсивом, центрировано на белом фоне, с плавными краями благодаря сглаживанию и подсказкам. + +{.img-fluid alt="Пример вывода render html to png"} + +> **Note:** Изображение выше является заглушкой. В вашем собственном проекте PNG будет точно соответствовать предоставленному HTML. + +--- + +## Full, runnable source code + +Ниже приведён полный файл `Program.cs`. Скопируйте его в консольный проект, созданный ранее, восстановите пакеты NuGet и выполните `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Запуск программы выводит: + +``` +HTML has been rendered to PNG successfully. +``` + +и создаёт `output.png` рядом с исполняемым файлом. + +--- + +## Variations and edge cases + +### Rendering to other image formats + +`ImageRenderer` поддерживает BMP, GIF, JPEG и TIFF. Измените расширение файла в `RenderToFile` и при необходимости скорректируйте `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Scaling the output + +Если нужен PNG более высокого разрешения (например, для Retina‑дисплеев), задайте свойства `ImageWidth` и `ImageHeight`: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +Рендерер растеризует HTML в указанном размере, сохраняя векторное качество. + +### Handling complex CSS + +Aspose.HTML полностью поддерживает внешние таблицы стилей, медиазапросы и SVG. Просто загрузите HTML из файла или URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +Тот же конвейер рендеринга применяется, так что вы можете **конвертировать html в изображение** любой веб‑страницы, а не только простых строк. + +### Thread‑safety considerations + +`HTMLDocument` и `ImageRenderer` не являются потокобезопасными. Если требуется параллельный рендеринг множества страниц, создавайте отдельный экземпляр `HTMLDocument` для каждого потока или используйте шаблон пула потоков. + +--- + +## Common pitfalls and how to avoid them + +| Issue | Why it happens | Fix | +|-------|----------------|-----| +| PNG is blank or missing text | Font not found on the server | Install the required font on the machine or embed it via CSS `@font-face`. | +| Watermark appears | Evaluation license used | Apply a valid license file (`Aspose.Total.lic`). | +| Output is blurry | Antialiasing disabled | Set `imageOptions.UseAntialiasing = true`. | +| Text looks thin | Hinting disabled | Set `textOptions.UseHinting = true`. | + +--- + +## Conclusion + +Теперь у вас есть надёжное сквозное решение для **render html to png** в C#. В руководстве рассмотрены установка Aspose.HTML, создание HTML‑документа, применение стиля жирный‑курсив, включение сглаживания и подсказок текста, а также запись PNG‑файла на диск. + +Далее вы можете изучить: + +* **Convert html to image** для пакетной обработки шаблонов писем. +* Рендеринг в PDF, заменив `ImageRenderer` на `PdfRenderer`. +* Использование DOM‑API Aspose.HTML для манипуляций HTML перед рендерингом. + +Экспериментируйте с различными CSS, большими холстами или альтернативными форматами вывода. Приятного рендеринга! + +## What Should You Learn Next? + +Следующие руководства охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом гайде. Каждый ресурс содержит полностью работающие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Convert HTML to PNG in .NET with Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/spanish/net/generate-jpg-and-png-images/_index.md b/html/spanish/net/generate-jpg-and-png-images/_index.md index 4323c45918..19207e3fe6 100644 --- a/html/spanish/net/generate-jpg-and-png-images/_index.md +++ b/html/spanish/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aprenda a utilizar Aspose.HTML para .NET para manipular documentos HTML, convert Aprenda a activar el antialiasing al convertir documentos DOCX a imágenes PNG o JPG usando Aspose.HTML para .NET. ### [Convertir docx a PNG – crear archivo ZIP con C# tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Aprenda a convertir documentos DOCX a imágenes PNG y empaquetarlos en un archivo ZIP usando C#. +### [Renderizar HTML a PNG en C# – guía completa](./render-html-to-png-in-c-complete-guide/) +Aprenda a renderizar HTML a imágenes PNG usando C# con Aspose.HTML, paso a paso. ## Conclusión diff --git a/html/spanish/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/spanish/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..ba17cdbfa8 --- /dev/null +++ b/html/spanish/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,338 @@ +--- +category: general +date: 2026-08-06 +description: Renderiza HTML a PNG con Aspose.HTML en C#. Aprende a convertir HTML + en una imagen, aplicar estilos de fuente, antialiasing y hinting de texto en un + único ejemplo ejecutable. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: es +lastmod: 2026-08-06 +og_description: Renderiza HTML a PNG usando Aspose.HTML para .NET. Este tutorial muestra + cómo convertir HTML a imagen, aplicar estilo negrita‑cursiva, antialiasing y optimización + de texto. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Renderizar HTML a PNG en C# – paso a paso con Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: Renderizar HTML a PNG en C# – guía completa +url: /es/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Renderizar html a png en C# – guía completa + +Si necesitas **renderizar html a png** de forma rápida y fiable, esta guía te muestra exactamente cómo hacerlo con Aspose.HTML para .NET. También verás cómo **convertir html a imagen** controlando el estilo de fuente, antialiasing y text hinting, para que el PNG final se vea nítido en cualquier pantalla. + +Recorreremos cada paso necesario—desde instalar el paquete NuGet hasta producir un archivo PNG listo para producción. Al final del tutorial tendrás un programa autónomo y ejecutable que podrás incorporar a cualquier proyecto C#. + +## Lo que aprenderás + +* Cómo configurar Aspose.HTML en un proyecto .NET. +* Cómo crear un documento HTML en memoria y aplicar el enum `WebFontStyle.BoldItalic`. +* Cómo habilitar antialiasing y text hinting para un renderizado más suave. +* Cómo renderizar el documento a un archivo PNG usando `ImageRenderer`. +* Variaciones comunes como renderizar a otros formatos de imagen o escalar la salida. + +No se requieren herramientas externas ni pasos manuales de conversión de imágenes—todo ocurre programáticamente. + +## Requisitos previos + +* .NET 6.0 SDK o posterior (el código también funciona con .NET Framework 4.7+). +* Visual Studio 2022 (o cualquier IDE que soporte C#). +* Una licencia activa de Aspose.HTML para .NET (o una clave de evaluación gratuita). +* Familiaridad básica con la sintaxis de C#. + +> **Consejo profesional:** Si estás usando la evaluación gratuita, el PNG generado contendrá una marca de agua. Una licencia comprada la elimina automáticamente. + +--- + +## Convertir html a imagen – configurando el entorno + +1. **Crear un nuevo proyecto de consola** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Agregar el paquete NuGet Aspose.HTML** + + ```bash + dotnet add package Aspose.HTML + ``` + + Este comando descarga todos los ensamblados que necesitas para renderizar HTML a imágenes. + +3. **(Opcional) Añadir un archivo de licencia** + + Coloca tu archivo `Aspose.Total.lic` en la raíz del proyecto y agrega la siguiente línea al inicio de `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + El paso de licencia no es necesario para la prueba gratuita, pero evita la marca de agua. + +## Renderizar html a png con Aspose.HTML + +El núcleo del tutorial es un proceso de cinco pasos que refleja el código que proporcionaste. Cada paso se explica en detalle para que comprendas **por qué** la llamada es necesaria, no solo **qué** hace. + +### Paso 1: Crear el documento HTML + +Comenzamos con una cadena HTML mínima que contiene un párrafo con estilo de fuente Arial. Usar `HTMLDocument` nos permite trabajar completamente en memoria—no se crean archivos temporales. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Por qué es importante:* `HTMLDocument` analiza el marcado y construye un DOM que el renderizador puede recorrer. Como el documento vive en memoria, la operación es rápida y segura para subprocesos. + +### Paso 2: Aplicar estilo negrita‑cursiva con `WebFontStyle` + +Aspose.HTML expone la enumeración `WebFontStyle` para combinar valores comunes de CSS font‑weight y font‑style. Configurarla a `BoldItalic` hace que el texto aparezca tanto en negrita como en cursiva sin escribir CSS adicional. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **¿Por qué usar `WebFontStyle`?** +> Elimina la necesidad de incrustar un bloque de estilo o una hoja de estilo externa, reduciendo la cantidad de HTML que debes gestionar al renderizar imágenes del lado del servidor. + +### Paso 3: Habilitar antialiasing para bordes más suaves + +El antialiasing suaviza los bordes de formas y texto, reduciendo los píxeles dentados especialmente en pantallas de alta DPI. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Impacto:* Cuando `UseAntialiasing` es `true`, el renderizador aplica un algoritmo sub‑pixel que produce un PNG más limpio, particularmente para líneas diagonales o tamaños de fuente pequeños. + +### Paso 4: Activar text hinting + +El text hinting alinea los glifos a la cuadrícula de píxeles, haciendo que los caracteres se vean más nítidos en resoluciones bajas. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*Cuándo desactivar:* Si más adelante renderizas PDFs basados en vectores, podrías omitir el hinting para preservar el contorno original. Para salida PNG rasterizada, el hinting casi siempre es beneficioso. + +### Paso 5: Renderizar el documento a un archivo PNG + +Finalmente, creamos un `ImageRenderer`, pasamos el documento y los dos objetos de opciones, y escribimos la salida en disco. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +La llamada se bloquea hasta que el archivo se escribe completamente, garantizando que `output.png` exista cuando el programa finalice. + +#### Salida esperada + +Ejecutar el programa crea **output.png** en la carpeta del proyecto. La imagen muestra la palabra **Hello** en Arial, negrita‑cursiva, centrada en un fondo blanco, con bordes suaves gracias al antialiasing y al hinting. + +{.img-fluid alt="Ejemplo de salida de render html a png"} + +> **Nota:** La imagen anterior es un marcador de posición. En tu propio proyecto el PNG reflejará el HTML exacto que proporcionaste. + +--- + +## Código fuente completo y ejecutable + +A continuación se muestra el archivo completo `Program.cs`. Cópialo en el proyecto de consola que creaste antes, restaura los paquetes NuGet y ejecuta `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Running the program prints: + +``` +HTML has been rendered to PNG successfully. +``` + +y crea `output.png` junto al ejecutable. + +--- + +## Variaciones y casos límite + +### Renderizar a otros formatos de imagen + +`ImageRenderer` soporta BMP, GIF, JPEG y TIFF. Cambia la extensión del archivo en `RenderToFile` y opcionalmente ajusta `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Escalar la salida + +Si necesitas un PNG de mayor resolución (p. ej., para pantallas retina), establece las propiedades `ImageWidth` y `ImageHeight`: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +El renderizador rasterizará el HTML al tamaño especificado mientras preserva la calidad vectorial. + +### Manejo de CSS complejo + +Aspose.HTML soporta completamente hojas de estilo externas, media queries y SVG. Simplemente carga el HTML desde un archivo o URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +El mismo pipeline de renderizado se aplica, por lo que puedes **convertir html a imagen** para cualquier página web, no solo cadenas simples. + +### Consideraciones de seguridad en subprocesos + +`HTMLDocument` y `ImageRenderer` no son seguros para subprocesos. Si necesitas renderizar muchas páginas en paralelo, crea una instancia separada de `HTMLDocument` por subproceso o usa un patrón de pool de subprocesos. + +--- + +## Errores comunes y cómo evitarlos + +| Problema | Por qué ocurre | Solución | +|----------|----------------|----------| +| PNG está en blanco o falta texto | Fuente no encontrada en el servidor | Instala la fuente requerida en la máquina o incrústala mediante CSS `@font-face`. | +| Aparece marca de agua | Se utilizó una licencia de evaluación | Aplica un archivo de licencia válido (`Aspose.Total.lic`). | +| La salida está borrosa | Antialiasing deshabilitado | Establece `imageOptions.UseAntialiasing = true`. | +| El texto se ve delgado | Hinting deshabilitado | Establece `textOptions.UseHinting = true`. | + +## Conclusión + +Ahora tienes una solución sólida, de extremo a extremo, para **renderizar html a png** en C#. El tutorial cubrió la instalación de Aspose.HTML, la creación de un documento HTML, la aplicación de estilo negrita‑cursiva, la habilitación de antialiasing y text hinting, y finalmente la escritura de un archivo PNG en disco. + +A partir de aquí puedes explorar: + +* **Convertir html a imagen** para el procesamiento por lotes de plantillas de correo electrónico. +* Renderizar a PDF cambiando `ImageRenderer` por `PdfRenderer`. +* Usar la API DOM de Aspose.HTML para manipular HTML antes de renderizar. + +Siéntete libre de experimentar con diferentes CSS, lienzos más grandes o formatos de salida alternativos. ¡Feliz renderizado! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Cómo usar Aspose para renderizar HTML a PNG – Guía paso a paso](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Cómo renderizar HTML a PNG con Aspose – Guía completa](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Convertir HTML a PNG en .NET con Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/swedish/net/generate-jpg-and-png-images/_index.md b/html/swedish/net/generate-jpg-and-png-images/_index.md index 39785fb465..76f10b24c3 100644 --- a/html/swedish/net/generate-jpg-and-png-images/_index.md +++ b/html/swedish/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,7 @@ Lär dig att använda Aspose.HTML för .NET för att manipulera HTML-dokument, k Lär dig hur du aktiverar kantutjämning för att förbättra bildkvaliteten när du konverterar DOCX-dokument till PNG eller JPG med Aspose.HTML. ### [Konvertera DOCX till PNG – skapa zip‑arkiv C#‑handledning](./convert-docx-to-png-create-zip-archive-c-tutorial/) Lär dig hur du konverterar DOCX-filer till PNG-bilder och packar dem i ett zip‑arkiv med C# och Aspose.HTML. +### [Rendera html till png i C# – komplett guide](./render-html-to-png-in-c-complete-guide/) ## Slutsats diff --git a/html/swedish/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/swedish/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..b658f18fc3 --- /dev/null +++ b/html/swedish/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,340 @@ +--- +category: general +date: 2026-08-06 +description: Rendera HTML till PNG med Aspose.HTML i C#. Lär dig hur du konverterar + HTML till en bild, tillämpar teckensnittsstilar, kantutjämning och texthintning + i ett enda körbart exempel. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: sv +lastmod: 2026-08-06 +og_description: Rendera HTML till PNG med Aspose.HTML för .NET. Denna handledning + visar hur du konverterar HTML till bild, tillämpar fet‑kursiv formatering, kantutjämning + och texthintning. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Rendera HTML till PNG i C# – steg för steg med Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: Rendera HTML till PNG i C# – komplett guide +url: /sv/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-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 guide + +Om du snabbt och pålitligt behöver **rendera html till png**, visar den här guiden exakt hur du gör det med Aspose.HTML för .NET. Du får också se hur du **konverterar html till bild** samtidigt som du styr teckensnittsstil, kantutjämning och texthintning, så att den slutliga PNG-filen ser skarp ut på alla skärmar. + +Vi går igenom varje nödvändigt steg—från att installera NuGet‑paketet till att producera en produktionsklar PNG‑fil. I slutet av handledningen har du ett självständigt, körbart program som du kan lägga in i vilket C#‑projekt som helst. + +## Vad du kommer att lära dig + +* Hur du konfigurerar Aspose.HTML i ett .NET‑projekt. +* Hur du skapar ett HTML‑dokument i minnet och tillämpar `WebFontStyle.BoldItalic`‑enumet. +* Hur du aktiverar antialiasing och texthintning för mjukare rendering. +* Hur du renderar dokumentet till en PNG‑fil med `ImageRenderer`. +* Vanliga variationer såsom rendering till andra bildformat eller skalning av utskriften. + +Inga externa verktyg eller manuella bildkonverteringssteg krävs—allt sker programatiskt. + +## Förutsättningar + +* .NET 6.0 SDK eller senare (koden fungerar även med .NET Framework 4.7+). +* Visual Studio 2022 (eller någon IDE som stödjer C#). +* En aktiv Aspose.HTML för .NET‑licens (eller en gratis utvärderingsnyckel). +* Grundläggande kunskap om C#‑syntax. + +> **Proffstips:** Om du använder den kostnadsfria utvärderingen kommer den genererade PNG‑filen att innehålla ett vattenmärke. En köpt licens tar bort det automatiskt. + +--- + +## Konvertera html till bild – konfigurera miljön + +1. **Skapa ett nytt konsolprojekt** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Lägg till Aspose.HTML NuGet‑paketet** + + ```bash + dotnet add package Aspose.HTML + ``` + + Detta kommando hämtar alla de assembly du behöver för att rendera HTML till bilder. + +3. **(Valfritt) Lägg till en licensfil** + + Placera din `Aspose.Total.lic`‑fil i projektets rot och lägg till följande rad i början av `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + Licenssteget krävs inte för den kostnadsfria provversionen, men det förhindrar vattenmärket. + +## Rendera html till png med Aspose.HTML + +Kärnan i handledningen är en femstegsprocess som speglar den kod du har. Varje steg förklaras i detalj så att du förstår **varför** anropet är nödvändigt, inte bara **vad** det gör. + +### Steg 1: Skapa HTML‑dokumentet + +Vi börjar med en minimal HTML‑sträng som innehåller ett stycke formaterat med Arial‑teckensnittet. Genom att använda `HTMLDocument` kan vi arbeta helt i minnet—inga temporära filer skapas. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Varför detta är viktigt:* `HTMLDocument` parsar markupen och bygger ett DOM som renderaren kan traversera. Eftersom dokumentet lever i minnet är operationen snabb och trådsäker. + +### Steg 2: Tillämpa fet‑kursiv stil med `WebFontStyle` + +Aspose.HTML exponerar `WebFontStyle`‑enumerationen för att kombinera vanliga CSS‑värden för font‑weight och font‑style. Att sätta den till `BoldItalic` får texten att visas både fet och kursiv utan att skriva extra CSS. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Varför använda `WebFontStyle`?** +> Det eliminerar behovet av att bädda in ett stilblock eller en extern stylesheet, vilket minskar mängden HTML du måste hantera när du renderar bilder på servern. + +### Steg 3: Aktivera antialiasing för mjukare kanter + +Antialiasing jämnar ut kanterna på former och text, vilket minskar hackiga pixlar, särskilt på hög‑DPI‑skärmar. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Effekt:* När `UseAntialiasing` är `true` använder renderaren en sub‑pixel‑algoritm som ger en renare PNG, särskilt för diagonala linjer eller små teckensnittsstorlekar. + +### Steg 4: Aktivera texthintning + +Texthintning justerar glyfer till pixelrutnätet, vilket gör tecken skarpare vid låg upplösning. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*När du ska inaktivera:* Om du senare renderar vektorbaserade PDF:er kan du hoppa över hintning för att bevara den ursprungliga konturen. För raster‑PNG‑utdata är hintning nästan alltid fördelaktigt. + +### Steg 5: Rendera dokumentet till en PNG‑fil + +Slutligen skapar vi en `ImageRenderer`, skickar dokumentet och de två alternativobjekten, och skriver utdata till disk. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +Anropet blockerar tills filen är helt skriven, vilket garanterar att `output.png` finns när programmet avslutas. + +#### Förväntad utdata + +När programmet körs skapas **output.png** i projektmappen. Bilden visar ordet **Hello** i Arial, fet‑kursiv, centrerat på en vit bakgrund, med mjuka kanter tack vare antialiasing och hintning. + +{.img-fluid alt="Render html to png example output"} + +> **Obs:** Bilden ovan är en platshållare. I ditt eget projekt kommer PNG‑filen att återspegla exakt den HTML du har angett. + +--- + +## Fullständig, körbar källkod + +Nedan är den kompletta `Program.cs`‑filen. Kopiera den till konsolprojektet du skapade tidigare, återställ NuGet‑paketen och kör `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Running the program prints: + +``` +HTML has been rendered to PNG successfully. +``` + +och skapar `output.png` bredvid den körbara filen. + +--- + +## Variationer och kantfall + +### Rendering till andra bildformat + +`ImageRenderer` stödjer BMP, GIF, JPEG och TIFF. Ändra filändelsen i `RenderToFile` och justera eventuellt `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Skalning av utskriften + +Om du behöver en högre upplösning PNG (t.ex. för Retina‑skärmar), sätt `ImageWidth` och `ImageHeight`‑egenskaperna: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +Renderaren rasteriserar HTML vid den angivna storleken samtidigt som den bevarar vektor‑kvaliteten. + +### Hantera komplex CSS + +Aspose.HTML stödjer fullt ut externa stilmallar, media queries och SVG. Ladda bara HTML från en fil eller URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +Samma renderingspipeline gäller, så du kan **konvertera html till bild** för vilken webbsida som helst, inte bara enkla strängar. + +### Trådsäkerhetsaspekter + +`HTMLDocument` och `ImageRenderer` är inte trådsäkra. Om du behöver rendera många sidor parallellt, skapa en separat `HTMLDocument`‑instans per tråd eller använd ett trådpools‑mönster. + +--- + +## Vanliga fallgropar och hur du undviker dem + +| Problem | Varför det händer | Lösning | +|---------|-------------------|---------| +| PNG är tom eller saknar text | Teckensnittet hittades inte på servern | Installera det erforderliga teckensnittet på maskinen eller bädda in det via CSS `@font-face`. | +| Vattenmärke visas | Utvärderingslicens används | Använd en giltig licensfil (`Aspose.Total.lic`). | +| Utdata är suddig | Antialiasing inaktiverad | Sätt `imageOptions.UseAntialiasing = true`. | +| Texten ser tunn ut | Hintning inaktiverad | Sätt `textOptions.UseHinting = true`. | + +--- + +## Slutsats + +Du har nu en solid, helhetslösning för att **rendera html till png** i C#. Handledningen täckte installation av Aspose.HTML, skapande av ett HTML‑dokument, tillämpning av fet‑kursiv stil, aktivering av antialiasing och texthintning, och slutligen skrivning av en PNG‑fil till disk. + +Härifrån kan du utforska: + +* **Konvertera html till bild** för batch‑bearbetning av e‑postmallar. +* Rendering till PDF genom att byta ut `ImageRenderer` mot `PdfRenderer`. +* Använda Aspose.HTML:s DOM‑API för att manipulera HTML före rendering. + +Känn dig fri att experimentera med olika CSS, större canvas‑storlekar eller alternativa utdataformat. Lycka till med rendering! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstrerats i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Hur man använder Aspose för att rendera HTML till PNG – steg‑för‑steg‑guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Hur man renderar HTML till PNG med Aspose – komplett guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Konvertera HTML till PNG i .NET med Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/thai/net/generate-jpg-and-png-images/_index.md b/html/thai/net/generate-jpg-and-png-images/_index.md index bb3254275c..c5a3ff5457 100644 --- a/html/thai/net/generate-jpg-and-png-images/_index.md +++ b/html/thai/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,7 @@ Aspose.HTML สำหรับ .NET นำเสนอวิธีการง เรียนรู้วิธีเปิดใช้งาน Antialiasing เพื่อให้ภาพ PNG/JPG ที่แปลงจาก DOCX มีความคมชัดและลื่นไหล ### [แปลง DOCX เป็น PNG – สร้างไฟล์ ZIP ด้วย C#](./convert-docx-to-png-create-zip-archive-c-tutorial/) เรียนรู้วิธีแปลงไฟล์ DOCX เป็น PNG แล้วบีบอัดเป็นไฟล์ ZIP ด้วย C# โดยใช้ Aspose.HTML +### [เรนเดอร์ HTML เป็น PNG ใน C# – คู่มือฉบับสมบูรณ์](./render-html-to-png-in-c-complete-guide/) ## บทสรุป diff --git a/html/thai/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/thai/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..f105173b05 --- /dev/null +++ b/html/thai/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,338 @@ +--- +category: general +date: 2026-08-06 +description: เรนเดอร์ HTML เป็น PNG ด้วย Aspose.HTML ใน C# เรียนรู้วิธีแปลง HTML เป็นภาพ, + ใช้สไตล์ฟอนต์, แอนตี้เอไลซิง, และการให้คำแนะนำข้อความในตัวอย่างเดียวที่สามารถรันได้ +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: th +lastmod: 2026-08-06 +og_description: เรนเดอร์ HTML เป็น PNG ด้วย Aspose.HTML สำหรับ .NET บทเรียนนี้แสดงวิธีแปลง + HTML เป็นภาพ, ใช้สไตล์ตัวหนา‑ตัวเอียง, การทำแอนตี้เอเลียส, และการให้คำแนะนำข้อความ. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: แปลง HTML เป็น PNG ใน C# – ขั้นตอนโดยละเอียดด้วย Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: เรนเดอร์ HTML เป็น PNG ใน C# – คู่มือฉบับสมบูรณ์ +url: /th/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# เรนเดอร์ html เป็น png ใน C# – คู่มือฉบับสมบูรณ์ + +หากคุณต้องการ **render html to png** อย่างรวดเร็วและเชื่อถือได้ คู่มือนี้จะแสดงให้คุณเห็นขั้นตอนที่ทำได้ด้วย Aspose.HTML สำหรับ .NET คุณยังจะได้เห็นวิธี **convert html to image** พร้อมการควบคุมสไตล์ฟอนต์, การทำ antialiasing, และการทำ text hinting เพื่อให้ PNG สุดท้ายคมชัดบนหน้าจอใดก็ได้ + +เราจะเดินผ่านทุกขั้นตอนที่จำเป็น—from การติดตั้งแพ็กเกจ NuGet ไปจนถึงการสร้างไฟล์ PNG ที่พร้อมใช้งานในสภาพการผลิต เมื่อจบบทเรียนคุณจะมีโปรแกรมที่ทำงานได้เองและสามารถนำไปใส่ในโปรเจกต์ C# ใดก็ได้ + +## สิ่งที่คุณจะได้เรียน + +* วิธีตั้งค่า Aspose.HTML ในโปรเจกต์ .NET +* วิธีสร้างเอกสาร HTML ในหน่วยความจำและใช้ enum `WebFontStyle.BoldItalic` +* วิธีเปิดใช้งาน antialiasing และ text hinting เพื่อการเรนเดอร์ที่ราบรื่น +* วิธีเรนเดอร์เอกสารเป็นไฟล์ PNG ด้วย `ImageRenderer` +* ตัวแปรทั่วไป เช่น การเรนเดอร์เป็นรูปแบบภาพอื่นหรือการปรับขนาดผลลัพธ์ + +ไม่มีเครื่องมือภายนอกหรือขั้นตอนการแปลงภาพด้วยมือที่จำเป็น—ทุกอย่างทำโดยโปรแกรม + +## ข้อกำหนดเบื้องต้น + +* .NET 6.0 SDK หรือใหม่กว่า (โค้ดนี้ยังทำงานกับ .NET Framework 4.7+) +* Visual Studio 2022 (หรือ IDE ใดก็ได้ที่รองรับ C#) +* ไลเซนส์ Aspose.HTML for .NET ที่ใช้งานได้ (หรือคีย์ประเมินผลฟรี) +* ความคุ้นเคยพื้นฐานกับไวยากรณ์ C# + +> **เคล็ดลับ:** หากคุณใช้รุ่นประเมินผลฟรี PNG ที่สร้างขึ้นจะมีลายน้ำ ไลเซนส์ที่ซื้อจะลบลายน้ำโดยอัตโนมัติ + +--- + +## Convert html to image – ตั้งค่าสภาพแวดล้อม + +1. **สร้างโปรเจกต์คอนโซลใหม่** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **เพิ่มแพ็กเกจ NuGet ของ Aspose.HTML** + + ```bash + dotnet add package Aspose.HTML + ``` + + คำสั่งนี้จะดึงแอสเซมบลีทั้งหมดที่คุณต้องการสำหรับการเรนเดอร์ HTML เป็นภาพ + +3. **(Optional) เพิ่มไฟล์ไลเซนส์** + + วางไฟล์ `Aspose.Total.lic` ของคุณในโฟลเดอร์รากของโปรเจกต์และเพิ่มบรรทัดต่อไปนี้ที่จุดเริ่มต้นของ `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + ขั้นตอนการใส่ไลเซนส์ไม่จำเป็นสำหรับการทดลองใช้ฟรี แต่จะป้องกันลายน้ำ + +## เรนเดอร์ html เป็น png ด้วย Aspose.HTML + +หัวใจของบทเรียนคือกระบวนการห้าขั้นตอนที่สอดคล้องกับโค้ดที่คุณให้ไว้ แต่ละขั้นตอนจะอธิบายอย่างละเอียดเพื่อให้คุณเข้าใจ **ทำไม** ต้องเรียกใช้ และ **ทำอะไร** บ้าง + +### ขั้นตอนที่ 1: สร้างเอกสาร HTML + +เราเริ่มด้วยสตริง HTML ขั้นพื้นฐานที่มีพารากราฟสไตล์ฟอนต์ Arial การใช้ `HTMLDocument` ทำให้เราทำงานทั้งหมดในหน่วยความจำ—ไม่มีไฟล์ชั่วคราวถูกสร้างขึ้น + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*ทำไมเรื่องนี้สำคัญ:* `HTMLDocument` จะทำการพาร์สมาร์กอัปและสร้าง DOM ที่เรนเดอร์สามารถเดินทางได้ เนื่องจากเอกสารอยู่ในหน่วยความจำ การทำงานจึงเร็วและปลอดภัยต่อเธรด + +### ขั้นตอนที่ 2: ใช้สไตล์ bold‑italic ด้วย `WebFontStyle` + +Aspose.HTML เปิดเผย enumeration `WebFontStyle` เพื่อรวมค่าที่พบบ่อยของ CSS `font-weight` และ `font-style` การตั้งค่าเป็น `BoldItalic` ทำให้ข้อความแสดงเป็นตัวหนาและเอียงโดยไม่ต้องเขียน CSS เพิ่มเติม + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **ทำไมต้องใช้ `WebFontStyle`?** +> มันช่วยขจัดความจำเป็นในการฝังบล็อกสไตล์หรือสไตล์ชีตภายนอก ลดปริมาณ HTML ที่ต้องจัดการเมื่อเรนเดอร์ภาพฝั่งเซิร์ฟเวอร์ + +### ขั้นตอนที่ 3: เปิดใช้งาน antialiasing เพื่อขอบที่ราบรื่น + +Antialiasing ทำให้ขอบของรูปทรงและข้อความเรียบเนียน ลดพิกเซลหยักโดยเฉพาะบนหน้าจอ DPI สูง + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*ผลกระทบ:* เมื่อ `UseAntialiasing` เป็น `true` เรนเดอร์จะใช้ алгоритм sub‑pixel ที่ให้ PNG สะอาดยิ่งขึ้น โดยเฉพาะสำหรับเส้นทแยงมุมหรือขนาดฟอนต์เล็ก + +### ขั้นตอนที่ 4: เปิดใช้งาน text hinting + +Text hinting จัดตำแหน่ง glyphs ให้ตรงกับกริดพิกเซล ทำให้ตัวอักษรดูคมชัดที่ความละเอียดต่ำ + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*เมื่อใดควรปิด:* หากคุณกำลังเรนเดอร์ PDF แบบเวกเตอร์ในภายหลัง คุณอาจข้ามการ hinting เพื่อรักษาโครงร่างเดิม สำหรับการส่งออกเป็น PNG แบบแรสเตอร์ การ hinting มักเป็นประโยชน์เสมอ + +### ขั้นตอนที่ 5: เรนเดอร์เอกสารเป็นไฟล์ PNG + +สุดท้าย เราสร้าง `ImageRenderer` ส่งเอกสารและอ็อบเจกต์ตัวเลือกสองตัว แล้วเขียนผลลัพธ์ลงดิสก์ + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +การเรียกนี้จะบล็อกจนกว่าไฟล์จะถูกเขียนเต็มที่ รับประกันว่า `output.png` จะมีอยู่เมื่อโปรแกรมจบ + +#### ผลลัพธ์ที่คาดหวัง + +การรันโปรแกรมจะสร้าง **output.png** ในโฟลเดอร์โปรเจกต์ ภาพจะแสดงคำ **Hello** ด้วยฟอนต์ Arial, bold‑italic, อยู่กึ่งกลางบนพื้นหลังสีขาว พร้อมขอบที่เรียบเนียนจาก antialiasing และ hinting + +{.img-fluid alt="ตัวอย่างผลลัพธ์การเรนเดอร์ html เป็น png"} + +> **หมายเหตุ:** ภาพด้านบนเป็นเพียงตัวอย่าง ในโปรเจกต์ของคุณ PNG จะสะท้อน HTML ที่คุณให้ไว้จริง ๆ + +--- + +## โค้ดต้นฉบับเต็มที่สามารถรันได้ + +ด้านล่างเป็นไฟล์ `Program.cs` ฉบับสมบูรณ์ คัดลอกไปยังโปรเจกต์คอนโซลที่คุณสร้างไว้ก่อนหน้านี้, ทำการ restore NuGet packages, แล้วรัน `dotnet run` + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +การรันโปรแกรมจะแสดงผล: + +``` +HTML has been rendered to PNG successfully. +``` + +และสร้างไฟล์ `output.png` ข้างไฟล์ executable + +--- + +## ความแปรผันและกรณีขอบ + +### การเรนเดอร์เป็นรูปแบบภาพอื่น + +`ImageRenderer` รองรับ BMP, GIF, JPEG, และ TIFF เปลี่ยนส่วนขยายไฟล์ใน `RenderToFile` และปรับ `ImageRenderingOptions` ตามต้องการ: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### การปรับขนาดผลลัพธ์ + +หากต้องการ PNG ความละเอียดสูงกว่า (เช่น สำหรับหน้าจอ retina) ให้ตั้งค่าคุณสมบัติ `ImageWidth` และ `ImageHeight`: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +เรนเดอร์จะทำการแรสเตอร์ HTML ตามขนาดที่ระบุโดยยังคงรักษาคุณภาพเวกเตอร์ไว้ + +### การจัดการ CSS ที่ซับซ้อน + +Aspose.HTML รองรับสไตล์ชีตภายนอก, media queries, และ SVG เพียงโหลด HTML จากไฟล์หรือ URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +กระบวนการเรนเดอร์เดียวกันจะใช้ได้ ดังนั้นคุณสามารถ **convert html to image** สำหรับหน้าเว็บใดก็ได้ ไม่ใช่แค่สตริงง่าย ๆ + +### พิจารณาความปลอดภัยของเธรด + +`HTMLDocument` และ `ImageRenderer` ไม่ปลอดภัยต่อเธรด หากต้องเรนเดอร์หลายหน้าแบบขนาน ให้สร้างอินสแตนซ์ `HTMLDocument` แยกสำหรับแต่ละเธรดหรือใช้แพทเทิร์น thread‑pool + +--- + +## ข้อผิดพลาดทั่วไปและวิธีหลีกเลี่ยง + +| ปัญหา | สาเหตุ | วิธีแก้ | +|-------|--------|----------| +| PNG ว่างหรือไม่มีข้อความ | ไม่พบฟอนต์บนเซิร์ฟเวอร์ | ติดตั้งฟอนต์ที่ต้องการบนเครื่องหรือฝังฟอนต์ผ่าน CSS `@font-face`. | +| มีลายน้ำ | ใช้ไลเซนส์รุ่นทดลอง | ใช้ไฟล์ไลเซนส์ที่ถูกต้อง (`Aspose.Total.lic`). | +| ผลลัพธ์เบลอ | ปิดการทำ antialiasing | ตั้งค่า `imageOptions.UseAntialiasing = true`. | +| ข้อความดูบาง | ปิดการทำ hinting | ตั้งค่า `textOptions.UseHinting = true`. | + +--- + +## สรุป + +คุณมีวิธีแก้ปัญหาแบบครบวงจรเพื่อ **render html to png** ใน C# แล้ว บทเรียนนี้ครอบคลุมการติดตั้ง Aspose.HTML, การสร้างเอกสาร HTML, การใช้สไตล์ bold‑italic, การเปิดใช้งาน antialiasing และ text hinting, และสุดท้ายการบันทึกไฟล์ PNG ลงดิสก์ + +ต่อจากนี้คุณสามารถสำรวจต่อได้: + +* **convert html to image** สำหรับการประมวลผลอีเมลเทมเพลตเป็นชุด +* เรนเดอร์เป็น PDF โดยสลับ `ImageRenderer` กับ `PdfRenderer` +* ใช้ DOM API ของ Aspose.HTML เพื่อปรับแต่ง HTML ก่อนการเรนเดอร์ + +อย่ากลัวทดลองกับ CSS ที่แตกต่าง, แคนวาสที่ใหญ่ขึ้น, หรือรูปแบบเอาต์พุตอื่น ๆ ขอให้สนุกกับการเรนเดอร์! + +## สิ่งที่คุณควรเรียนต่อ + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคในคู่มือนี้ แต่ละแหล่งข้อมูลมีโค้ดตัวอย่างทำงานครบถ้วนพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโปรเจกต์ของคุณ + +- [วิธีใช้ Aspose เพื่อเรนเดอร์ HTML เป็น PNG – คู่มือขั้นตอน](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [วิธีเรนเดอร์ HTML เป็น PNG ด้วย Aspose – คู่มือฉบับสมบูรณ์](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Convert HTML to PNG ใน .NET ด้วย Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/turkish/net/generate-jpg-and-png-images/_index.md b/html/turkish/net/generate-jpg-and-png-images/_index.md index a918363c42..a036c9e485 100644 --- a/html/turkish/net/generate-jpg-and-png-images/_index.md +++ b/html/turkish/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ HTML belgelerini düzenlemek, HTML'yi resimlere dönüştürmek ve daha fazlası DOCX belgelerini PNG veya JPG formatına dönüştürürken antialiasing'i etkinleştirerek daha net ve pürüzsüz görüntüler elde edin. ### [docx'i png'ye dönüştür – zip arşivi oluşturma C# eğitimi](./convert-docx-to-png-create-zip-archive-c-tutorial/) C# kullanarak docx dosyalarını png formatına dönüştürüp, sonuçları zip arşivi içinde paketlemeyi öğrenin. +### [C# ile HTML'yi PNG'ye Render Et – Tam Kılavuz](./render-html-to-png-in-c-complete-guide/) +C# kullanarak HTML içeriğini PNG formatına dönüştürmenin adım adım rehberi. ## Çözüm diff --git a/html/turkish/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/turkish/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..4673be6618 --- /dev/null +++ b/html/turkish/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,332 @@ +--- +category: general +date: 2026-08-06 +description: Aspose.HTML ile C#'ta HTML'yi PNG'ye render edin. Tek bir çalıştırılabilir + örnekte HTML'yi görüntüye dönüştürmeyi, yazı tipi stillerini uygulamayı, kenar yumuşatmayı + ve metin ipucu eklemeyi öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: tr +lastmod: 2026-08-06 +og_description: Aspose.HTML for .NET kullanarak html'yi png'ye render edin. Bu öğretici, + html'yi görüntüye dönüştürmeyi, kalın‑eğik stil uygulamayı, kenar yumuşatmayı ve + metin ipucu (text hinting) uygulamayı gösterir. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: C#'ta HTML'yi PNG'ye dönüştür – Aspose.HTML ile adım adım +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: C# ile HTML'yi PNG'ye dönüştürme – tam rehber +url: /tr/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#’ta HTML'yi PNG'ye Render Etme – Tam Kılavuz + +If you need to **render html to png** quickly and reliably, this guide shows you exactly how to do it with Aspose.HTML for .NET. You’ll also see how to **convert html to image** while controlling font style, antialiasing, and text hinting, so the final PNG looks sharp on any screen. + +We’ll walk through every required step—from installing the NuGet package to producing a production‑ready PNG file. By the end of the tutorial you’ll have a self‑contained, runnable program that you can drop into any C# project. + +## Öğrenecekleriniz + +* Aspose.HTML'i bir .NET projesinde nasıl kuracağınızı. +* `WebFontStyle.BoldItalic` enum'ını uygulayarak bellek içi bir HTML belgesi nasıl oluşturacağınızı. +* Daha pürüzsüz render için antialiasing ve metin ipuçlamasını nasıl etkinleştireceğinizi. +* `ImageRenderer` kullanarak belgeyi PNG dosyasına nasıl render edeceğinizi. +* Diğer görüntü formatlarına render etme veya çıktıyı ölçeklendirme gibi yaygın varyasyonlar. + +No external tools or manual image conversion steps are required—everything happens programmatically. + +## Önkoşullar + +* .NET 6.0 SDK veya daha yenisi (kod .NET Framework 4.7+ ile de çalışır). +* Visual Studio 2022 (veya C# destekleyen herhangi bir IDE). +* Aktif bir Aspose.HTML for .NET lisansı (veya ücretsiz bir değerlendirme anahtarı). +* C# sözdizimi hakkında temel bilgi. + +> **Pro ipucu:** Ücretsiz değerlendirme sürümünü kullanıyorsanız, oluşturulan PNG bir filigran içerir. Satın alınan bir lisans otomatik olarak bunu kaldırır. + +--- + +## html'yi görüntüye dönüştür – ortamı kurma + +1. **Yeni bir konsol projesi oluşturun** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Aspose.HTML NuGet paketini ekleyin** + + ```bash + dotnet add package Aspose.HTML + ``` + + This command pulls in all the assemblies you need for rendering HTML to images. + +3. **(İsteğe bağlı) Lisans dosyası ekleyin** + + Place your `Aspose.Total.lic` file in the project root and add the following line at the start of `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + The license step is not required for the free trial, but it prevents the watermark. + +## Aspose.HTML ile html'yi png'ye render et + +The core of the tutorial is a five‑step process that mirrors the code you provided. Each step is explained in detail so you understand **why** the call is necessary, not just **what** it does. + +### Adım 1: HTML belgesi oluşturma + +We start with a minimal HTML string that contains a paragraph styled with the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary files are created. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Why this matters:* `HTMLDocument` parses the markup and builds a DOM that the renderer can traverse. Because the document lives in memory, the operation is fast and thread‑safe. + +### Adım 2: `WebFontStyle` ile kalın‑italik stil uygulama + +Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS font‑weight and font‑style values. Setting it to `BoldItalic` makes the text appear both bold and italic without writing additional CSS. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Why use `WebFontStyle`?** +> It eliminates the need to embed a style block or external stylesheet, reducing the amount of HTML you have to manage when rendering server‑side images. + +### Adım 3: Daha pürüzsüz kenarlar için antialiasing'i etkinleştirme + +Antialiasing smooths the borders of shapes and text, reducing jagged pixels especially on high‑DPI displays. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Impact:* When `UseAntialiasing` is `true`, the renderer applies a sub‑pixel algorithm that yields a cleaner PNG, particularly for diagonal lines or small font sizes. + +### Adım 4: Metin ipuçlamasını etkinleştirme + +Text hinting aligns glyphs to the pixel grid, making characters look sharper at low resolutions. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*When to disable:* If you are rendering vector‑based PDFs later, you might skip hinting to preserve the original outline. For raster PNG output, hinting is almost always beneficial. + +### Adım 5: Belgeyi PNG dosyasına renderleme + +Finally, we create an `ImageRenderer`, pass the document and the two option objects, and write the output to disk. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +The call blocks until the file is fully written, guaranteeing that `output.png` exists when the program exits. + +#### Beklenen çıktı + +Running the program creates **output.png** in the project folder. The image shows the word **Hello** in Arial, bold‑italic, centered on a white background, with smooth edges thanks to antialiasing and hinting. + +{.img-fluid alt="Render html to png örnek çıktısı"} + +> **Not:** Yukarıdaki görüntü bir yer tutucudur. Kendi projenizde PNG, sağladığınız tam HTML'yi yansıtacaktır. + +## Tam, çalıştırılabilir kaynak kodu + +Below is the complete `Program.cs` file. Copy it into the console project you created earlier, restore NuGet packages, and run `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Running the program prints: + +``` +HTML has been rendered to PNG successfully. +``` + +and creates `output.png` next to the executable. + +## Varyasyonlar ve kenar durumları + +### Diğer görüntü formatlarına renderleme + +`ImageRenderer` BMP, GIF, JPEG ve TIFF formatlarını destekler. `RenderToFile` içinde dosya uzantısını değiştirin ve isteğe bağlı olarak `ImageRenderingOptions` ayarını düzenleyin: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Çıktıyı ölçeklendirme + +If you need a higher‑resolution PNG (e.g., for retina displays), set the `ImageWidth` and `ImageHeight` properties: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +The renderer will rasterize the HTML at the specified size while preserving vector quality. + +### Karmaşık CSS ile başa çıkma + +Aspose.HTML fully supports external stylesheets, media queries, and SVG. Just load the HTML from a file or URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +The same rendering pipeline applies, so you can **convert html to image** for any web page, not only simple strings. + +### İş parçacığı‑güvenliği hususları + +`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to render many pages in parallel, create a separate `HTMLDocument` instance per thread or use a thread‑pool pattern. + +## Yaygın tuzaklar ve nasıl önlenir + +| Sorun | Neden oluşur | Çözüm | +|-------|----------------|-----| +| PNG boş veya metin eksik | Sunucuda yazı tipi bulunamadı | Gerekli yazı tipini makineye kurun veya CSS `@font-face` ile gömün. | +| Filigran görünüyor | Değerlendirme lisansı kullanılıyor | Geçerli bir lisans dosyası (`Aspose.Total.lic`) uygulayın. | +| Çıktı bulanık | Antialiasing devre dışı | `imageOptions.UseAntialiasing = true` olarak ayarlayın. | +| Metin ince görünüyor | Hinting devre dışı | `textOptions.UseHinting = true` olarak ayarlayın. | + +## Sonuç + +You now have a solid, end‑to‑end solution to **render html to png** in C#. The tutorial covered installing Aspose.HTML, creating an HTML document, applying bold‑italic styling, enabling antialiasing and text hinting, and finally writing a PNG file to disk. + +From here you can explore: + +* **Convert html to image** e‑posta şablonlarının toplu işlenmesi için. +* `ImageRenderer` yerine `PdfRenderer` kullanarak PDF'ye renderleme. +* Renderlemeden önce HTML'i manipüle etmek için Aspose.HTML’in DOM API'sını kullanma. + +Feel free to experiment with different CSS, larger canvases, or alternative output formats. Happy rendering! + +## Sonraki Öğrenmeniz Gerekenler? + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Aspose ile HTML'yi PNG'ye Render Etme – Adım‑Adım Kılavuz](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Aspose ile HTML'yi PNG'ye Render Etme – Tam Kılavuz](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Aspose.HTML ile .NET'te HTML'yi PNG'ye Dönüştürme](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/vietnamese/net/generate-jpg-and-png-images/_index.md b/html/vietnamese/net/generate-jpg-and-png-images/_index.md index 364f751610..e099e380c7 100644 --- a/html/vietnamese/net/generate-jpg-and-png-images/_index.md +++ b/html/vietnamese/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Học cách sử dụng Aspose.HTML cho .NET để thao tác với các tài li Hướng dẫn chi tiết cách bật khử răng cưa để cải thiện chất lượng hình ảnh khi chuyển đổi tài liệu DOCX sang PNG hoặc JPG bằng Aspose.HTML. ### [Chuyển đổi DOCX sang PNG – tạo tệp ZIP bằng C# – Hướng dẫn](./convert-docx-to-png-create-zip-archive-c-tutorial/) Hướng dẫn cách chuyển đổi tài liệu DOCX thành hình ảnh PNG và đóng gói chúng vào tệp ZIP bằng C#. +### [Kết xuất HTML sang PNG trong C# – hướng dẫn đầy đủ](./render-html-to-png-in-c-complete-guide/) +Hướng dẫn chi tiết cách kết xuất HTML thành hình ảnh PNG bằng C# sử dụng Aspose.HTML. ## Phần kết luận diff --git a/html/vietnamese/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md b/html/vietnamese/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md new file mode 100644 index 0000000000..a78e656b11 --- /dev/null +++ b/html/vietnamese/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/_index.md @@ -0,0 +1,338 @@ +--- +category: general +date: 2026-08-06 +description: Kết xuất HTML sang PNG với Aspose.HTML trong C#. Tìm hiểu cách chuyển + đổi HTML thành hình ảnh, áp dụng kiểu chữ, khử răng cưa và gợi ý văn bản trong một + ví dụ duy nhất, có thể chạy được. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- render html to png +- convert html to image +- Aspose.HTML rendering +- C# image rendering +- HTML to PNG conversion +language: vi +lastmod: 2026-08-06 +og_description: Kết xuất HTML sang PNG bằng Aspose.HTML cho .NET. Hướng dẫn này cho + thấy cách chuyển đổi HTML thành hình ảnh, áp dụng định dạng in đậm‑nghiêng, khử + răng cưa và gợi ý văn bản. +og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C# +og_title: Chuyển đổi HTML sang PNG trong C# – từng bước với Aspose.HTML +schemas: +- author: Aspose + dateModified: '2026-08-06' + description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + headline: Render html to png in C# – complete guide + type: TechArticle +- description: Render html to png with Aspose.HTML in C#. Learn how to convert html + to image, apply font styles, antialiasing, and text hinting in a single, runnable + example. + name: Render html to png in C# – complete guide + steps: + - name: Create the HTML document + text: We start with a minimal HTML string that contains a paragraph styled with + the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary + files are created. + - name: Apply bold‑italic styling with `WebFontStyle` + text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS + font‑weight and font‑style values. Setting it to `BoldItalic` makes the text + appear both bold and italic without writing additional CSS. + - name: Enable antialiasing for smoother edges + text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels + especially on high‑DPI displays. + - name: Activate text hinting + text: Text hinting aligns glyphs to the pixel grid, making characters look sharper + at low resolutions. + - name: Render the document to a PNG file + text: Finally, we create an `ImageRenderer`, pass the document and the two option + objects, and write the output to disk. + - name: Rendering to other image formats + text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension + in `RenderToFile` and optionally adjust `ImageRenderingOptions`:' + - name: Scaling the output + text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the + `ImageWidth` and `ImageHeight` properties:' + - name: Handling complex CSS + text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG. + Just load the HTML from a file or URL:' + - name: Thread‑safety considerations + text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to + render many pages in parallel, create a separate `HTMLDocument` instance per + thread or use a thread‑pool pattern.' + type: HowTo +tags: +- Aspose.HTML +- C# +- Image rendering +title: Kết xuất HTML sang PNG trong C# – hướng dẫn đầy đủ +url: /vi/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render html sang png trong C# – hướng dẫn đầy đủ + +Nếu bạn cần **render html to png** nhanh chóng và đáng tin cậy, hướng dẫn này sẽ chỉ cho bạn cách thực hiện với Aspose.HTML cho .NET. Bạn cũng sẽ thấy cách **convert html to image** đồng thời kiểm soát kiểu phông chữ, antialiasing và text hinting, để PNG cuối cùng trông sắc nét trên mọi màn hình. + +Chúng tôi sẽ hướng dẫn từng bước cần thiết — từ cài đặt gói NuGet đến việc tạo ra tệp PNG sẵn sàng cho sản xuất. Khi kết thúc tutorial, bạn sẽ có một chương trình tự chứa, có thể chạy được mà bạn có thể đưa vào bất kỳ dự án C# nào. + +## Những gì bạn sẽ học + +* Cách thiết lập Aspose.HTML trong dự án .NET. +* Cách tạo tài liệu HTML trong bộ nhớ và áp dụng enum `WebFontStyle.BoldItalic`. +* Cách bật antialiasing và text hinting để render mượt hơn. +* Cách render tài liệu thành tệp PNG bằng `ImageRenderer`. +* Các biến thể phổ biến như render sang các định dạng ảnh khác hoặc thay đổi kích thước đầu ra. + +Không cần công cụ bên ngoài hay các bước chuyển đổi ảnh thủ công — mọi thứ diễn ra bằng chương trình. + +## Yêu cầu trước + +* .NET 6.0 SDK hoặc phiên bản mới hơn (mã cũng hoạt động với .NET Framework 4.7+). +* Visual Studio 2022 (hoặc bất kỳ IDE nào hỗ trợ C#). +* Giấy phép Aspose.HTML cho .NET đang hoạt động (hoặc khóa đánh giá miễn phí). +* Kiến thức cơ bản về cú pháp C#. + +> **Mẹo:** Nếu bạn đang sử dụng bản đánh giá miễn phí, PNG được tạo sẽ chứa watermark. Giấy phép đã mua sẽ tự động loại bỏ nó. + +--- + +## Chuyển đổi html sang ảnh – thiết lập môi trường + +1. **Create a new console project** + + ```bash + dotnet new console -n HtmlToPngDemo + cd HtmlToPngDemo + ``` + +2. **Add the Aspose.HTML NuGet package** + + ```bash + dotnet add package Aspose.HTML + ``` + + Lệnh này sẽ tải về tất cả các assembly bạn cần để render HTML sang ảnh. + +3. **(Optional) Add a license file** + + Place your `Aspose.Total.lic` file in the project root and add the following line at the start of `Program.cs`: + + ```csharp + Aspose.Html.License license = new Aspose.Html.License(); + license.SetLicense("Aspose.Total.lic"); + ``` + + Bước thêm giấy phép không bắt buộc cho bản dùng thử miễn phí, nhưng nó sẽ ngăn watermark. + +## Render html sang png với Aspose.HTML + +Cốt lõi của tutorial là quy trình năm bước phản ánh mã bạn đã cung cấp. Mỗi bước được giải thích chi tiết để bạn hiểu **tại sao** lệnh này cần thiết, không chỉ **cái gì** nó làm. + +### Bước 1: Tạo tài liệu HTML + +Chúng ta bắt đầu với một chuỗi HTML tối thiểu chứa một đoạn văn được định dạng bằng phông Arial. Sử dụng `HTMLDocument` cho phép chúng ta làm việc hoàn toàn trong bộ nhớ — không tạo tệp tạm. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +// Step 1 – Build an in‑memory HTML document +HTMLDocument document = new HTMLDocument( + "Hello
" +); +``` + +*Tại sao điều này quan trọng:* `HTMLDocument` phân tích markup và xây dựng DOM mà renderer có thể duyệt. Vì tài liệu tồn tại trong bộ nhớ, thao tác nhanh và thread‑safe. + +### Bước 2: Áp dụng kiểu chữ đậm‑nghiêng với `WebFontStyle` + +Aspose.HTML cung cấp enumeration `WebFontStyle` để kết hợp các giá trị CSS font‑weight và font‑style thường dùng. Đặt nó thành `BoldItalic` làm cho văn bản hiển thị cả đậm và nghiêng mà không cần viết CSS bổ sung. + +```csharp +// Step 2 – Define font styling (bold and italic) +FontInfo fontInfo = new FontInfo(); +fontInfo.WebFontStyle = WebFontStyle.BoldItalic; +``` + +> **Tại sao dùng `WebFontStyle`?** +> Nó loại bỏ nhu cầu nhúng khối style hoặc stylesheet bên ngoài, giảm lượng HTML bạn phải quản lý khi render ảnh phía server. + +### Bước 3: Bật antialiasing để các cạnh mượt hơn + +Antialiasing làm mịn các viền của hình dạng và văn bản, giảm các pixel răng cưa, đặc biệt trên màn hình high‑DPI. + +```csharp +// Step 3 – Turn on antialiasing +ImageRenderingOptions imageOptions = new ImageRenderingOptions(); +imageOptions.UseAntialiasing = true; +``` + +*Ảnh hưởng:* Khi `UseAntialiasing` là `true`, renderer áp dụng thuật toán sub‑pixel tạo PNG sạch hơn, đặc biệt cho các đường chéo hoặc kích thước phông chữ nhỏ. + +### Bước 4: Kích hoạt text hinting + +Text hinting căn chỉnh glyphs vào lưới pixel, làm cho ký tự trông sắc nét hơn ở độ phân giải thấp. + +```csharp +// Step 4 – Enable text hinting +TextOptions textOptions = new TextOptions(); +textOptions.UseHinting = true; +``` + +*Khi nào nên tắt:* Nếu bạn sẽ render PDF dựa trên vector sau này, bạn có thể bỏ qua hinting để giữ nguyên outline gốc. Đối với đầu ra PNG raster, hinting hầu như luôn có lợi. + +### Bước 5: Render tài liệu thành tệp PNG + +Cuối cùng, chúng ta tạo một `ImageRenderer`, truyền tài liệu và hai đối tượng tùy chọn, và ghi đầu ra ra đĩa. + +```csharp +// Step 5 – Render to PNG +ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); +renderer.RenderToFile("output.png"); +``` + +Lệnh này sẽ chặn cho đến khi tệp được ghi hoàn toàn, đảm bảo `output.png` tồn tại khi chương trình kết thúc. + +#### Kết quả mong đợi + +Chạy chương trình sẽ tạo **output.png** trong thư mục dự án. Hình ảnh hiển thị từ **Hello** bằng Arial, đậm‑nghiêng, căn giữa trên nền trắng, với các cạnh mượt nhờ antialiasing và hinting. + +{.img-fluid alt="Ví dụ đầu ra render html sang png"} + +> **Lưu ý:** Hình ảnh trên chỉ là placeholder. Trong dự án của bạn, PNG sẽ phản ánh chính xác HTML bạn đã cung cấp. + +--- + +## Mã nguồn đầy đủ, có thể chạy + +Dưới đây là file `Program.cs` hoàn chỉnh. Sao chép nó vào dự án console bạn đã tạo trước đó, khôi phục các gói NuGet, và chạy `dotnet run`. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // Optional: load a license to remove evaluation watermark + // var license = new Aspose.Html.License(); + // license.SetLicense("Aspose.Total.lic"); + + // Step 1 – Build an in‑memory HTML document + HTMLDocument document = new HTMLDocument( + "Hello
" + ); + + // Step 2 – Apply bold‑italic styling + FontInfo fontInfo = new FontInfo(); + fontInfo.WebFontStyle = WebFontStyle.BoldItalic; + + // Step 3 – Enable antialiasing + ImageRenderingOptions imageOptions = new ImageRenderingOptions(); + imageOptions.UseAntialiasing = true; + + // Step 4 – Turn on text hinting + TextOptions textOptions = new TextOptions(); + textOptions.UseHinting = true; + + // Step 5 – Render to PNG file + ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions); + renderer.RenderToFile("output.png"); + + System.Console.WriteLine("HTML has been rendered to PNG successfully."); + } +} +``` + +Running the program prints: + +``` +HTML has been rendered to PNG successfully. +``` + +và tạo `output.png` bên cạnh tệp thực thi. + +--- + +## Các biến thể và trường hợp đặc biệt + +### Render sang các định dạng ảnh khác + +`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension in `RenderToFile` and optionally adjust `ImageRenderingOptions`: + +```csharp +imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg; +renderer.RenderToFile("output.jpeg"); +``` + +### Thay đổi kích thước đầu ra + +If you need a higher‑resolution PNG (e.g., for retina displays), set the `ImageWidth` and `ImageHeight` properties: + +```csharp +imageOptions.ImageWidth = 800; // pixels +imageOptions.ImageHeight = 600; // pixels +renderer.RenderToFile("large-output.png"); +``` + +Renderer sẽ rasterize HTML ở kích thước đã chỉ định trong khi giữ nguyên chất lượng vector. + +### Xử lý CSS phức tạp + +Aspose.HTML fully supports external stylesheets, media queries, and SVG. Just load the HTML from a file or URL: + +```csharp +HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html"); +``` + +Quy trình render giống nhau, vì vậy bạn có thể **convert html to image** cho bất kỳ trang web nào, không chỉ các chuỗi đơn giản. + +### Lưu ý về thread‑safety + +`HTMLDocument` và `ImageRenderer` không thread‑safe. Nếu bạn cần render nhiều trang đồng thời, tạo một instance `HTMLDocument` riêng cho mỗi thread hoặc sử dụng mẫu thread‑pool. + +--- + +## Những lỗi thường gặp và cách tránh + +| Vấn đề | Nguyên nhân | Cách khắc phục | +|-------|----------------|-----| +| PNG trống hoặc thiếu văn bản | Phông chữ không được tìm thấy trên máy chủ | Cài đặt phông chữ cần thiết trên máy hoặc nhúng nó qua CSS `@font-face`. | +| Watermark xuất hiện | Đang sử dụng giấy phép dùng thử | Áp dụng tệp giấy phép hợp lệ (`Aspose.Total.lic`). | +| Đầu ra mờ | Antialiasing bị tắt | Đặt `imageOptions.UseAntialiasing = true`. | +| Văn bản trông mỏng | Hinting bị tắt | Đặt `textOptions.UseHinting = true`. | + +## Kết luận + +Bây giờ bạn đã có một giải pháp toàn diện, đầu‑tới‑cuối để **render html to png** trong C#. Tutorial đã bao gồm cài đặt Aspose.HTML, tạo tài liệu HTML, áp dụng kiểu đậm‑nghiêng, bật antialiasing và text hinting, và cuối cùng ghi tệp PNG ra đĩa. + +Từ đây bạn có thể khám phá: + +* **Convert html to image** để xử lý hàng loạt mẫu email. +* Render sang PDF bằng cách thay `ImageRenderer` bằng `PdfRenderer`. +* Sử dụng DOM API của Aspose.HTML để thao tác HTML trước khi render. + +Hãy tự do thử nghiệm với CSS khác nhau, canvas lớn hơn, hoặc các định dạng đầu ra thay thế. Chúc render vui vẻ! + +## Bạn nên học gì tiếp theo? + +Các tutorial sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoạt động đầy đủ với giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Cách sử dụng Aspose để Render HTML sang PNG – Hướng dẫn từng bước](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Cách Render HTML sang PNG với Aspose – Hướng dẫn đầy đủ](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Chuyển đổi HTML sang PNG trong .NET với Aspose.HTML](/html/english/net/html-extensions-and-conversions/convert-html-to-png/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file