diff --git a/html/arabic/net/html-extensions-and-conversions/_index.md b/html/arabic/net/html-extensions-and-conversions/_index.md index 980eb7013..22e0fe1cf 100644 --- a/html/arabic/net/html-extensions-and-conversions/_index.md +++ b/html/arabic/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ url: /ar/net/html-extensions-and-conversions/ تعلم كيفية حفظ مستند HTML كملف ZIP باستخدام Aspose.HTML في C# خطوة بخطوة. ### [حفظ HTML إلى ZIP في C# – مثال كامل في الذاكرة](./save-html-to-zip-in-c-complete-in-memory-example/) تعلم كيفية حفظ مستند HTML كملف ZIP في الذاكرة باستخدام C# ومكتبة Aspose.HTML. +### [كيفية ضغط HTML في C# – دليل معالج الموارد المخصص](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +تعلم كيفية ضغط ملفات HTML باستخدام معالج موارد مخصص في C# مع Aspose.HTML. ## خاتمة diff --git a/html/arabic/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/arabic/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..e0ec2068e --- /dev/null +++ b/html/arabic/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-02-21 +description: تعلم كيفية ضغط HTML إلى ملف zip باستخدام معالج موارد مخصص في C#. يغطي + هذا الدليل أيضًا حفظ HTML كملف zip، تحويل HTML إلى zip، وحفظ HTML إلى zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: ar +og_description: كيفية ضغط HTML في C# باستخدام معالج موارد مخصص. كود خطوة بخطوة، شروحات، + ونصائح لحفظ HTML كملف zip. +og_title: كيفية ضغط ملفات HTML في C# – دليل كامل +tags: +- Aspose.HTML +- C# +- ZIP compression +title: كيفية ضغط HTML بصيغة Zip في C# – دليل معالج الموارد المخصص +url: /ar/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية ضغط HTML في C# – دليل معالج الموارد المخصص + +هل تساءلت يومًا **كيفية ضغط HTML** مباشرةً من تطبيق .NET الخاص بك دون لمس نظام الملفات؟ لست وحدك. يحتاج العديد من المطورين إلى تجميع مستند HTML مع موارده—الصور، CSS، السكريبتات—في ملف ZIP واحد لتسهيل النقل أو التخزين. + +في هذا الدرس سنظهر لك طريقة نظيفة لـ **حفظ HTML كملف zip** باستخدام `ResourceHandler` الخاص بـ Aspose.HTML. سنناقش أيضًا مواضيع ذات صلة مثل **تحويل HTML إلى zip** و **حفظ HTML إلى zip** باستخدام معالج قابل لإعادة الاستخدام يمكنك إدراجه في أي مشروع. لا أدوات خارجية، لا ملفات مؤقتة—فقط سحر كامل في الذاكرة. + +## ما ستتعلمه + +* كيفية إنشاء `HTMLDocument` في الذاكرة. +* كيفية تنفيذ **معالج موارد مخصص** يبث كل مورد إلى أرشيف ZIP واحد. +* الكود الدقيق اللازم لـ **حفظ HTML كملف zip** واسترجاع مصفوفة البايت. +* نصائح للتعامل مع الحالات الخاصة مثل الصور الكبيرة أو ملفات CSS المتعددة. +* مثال كامل قابل للتنفيذ يمكنك نسخه ولصقه في Visual Studio. + +> **المتطلبات المسبقة** – تحتاج إلى .NET 6+ (أو .NET Framework 4.6+) ومكتبة Aspose.HTML for .NET المثبتة عبر NuGet (`Install-Package Aspose.HTML`). لا توجد تبعيات أخرى. + +--- + +## الخطوة 1 – إنشاء مستند HTML (كيفية ضغط HTML) + +أول شيء نحتاجه هو نسخة من `HTMLDocument` التي تحتفظ بالعلامات التي نريد ضغطها. اعتبرها كالقماش لبقية العملية. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "
Sample text
"); +``` + +> **Why this matters:** باستخدام `HTMLDocument` نسمح لـ Aspose.HTML بمعالجة تحليل CSS، التخطيط، وحل الخطوط تمامًا كما يفعل المتصفح. هذا يضمن أن الـ PNG الذي تحصل عليه يبدو مطابقًا لما يراه المستخدم في Chrome أو Edge. + +## Convert HTML to Image – تكوين خيارات التصيير + +بعد ذلك نحدد كيف يجب على المحرك تحويل العلامات إلى صورة نقطية. هنا يمكنك **تحديد عرض الصورة وارتفاعها**، تمكين مضاد التعرج، واختيار لون الخلفية. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Pro tip:** إذا تركت `Width` و `Height`، سيستخدم Aspose.HTML الحجم الأصلي للصفحة، والذي قد يكون صغيرًا جدًا للصور المصغرة. ضبط هذه القيم يدويًا يمنحك السيطرة الكاملة على أبعاد PNG النهائية. + +## Generate PNG from HTML – تطبيق أنماط الخط (اختياري) + +أحيانًا تحتاج إلى نص غامق، مائل، أو مزيج من الأنماط. تسمح لك تعداد `WebFontStyle` بدمج العلامات باستخدام عامل OR البتّي (`|`). هذه الخطوة اختيارية لكنها توضح كيفية **generate PNG from HTML** مع تنسيق مخصص. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **What’s happening:** `combinedFontStyle.ToString()` تُعيد `"Bold, Italic"` التي يترجمها المحرك إلى قيمة CSS صالحة لـ `font-style`. النتيجة هي PNG يظهر النص فيه غامقًا ومائلًا معًا. + +## Save HTML as PNG – استدعاء التصيير النهائي + +الآن نجمع كل شيء معًا. يقوم مصدر `Image` بكتابة المحتوى المصور إلى ملف على القرص. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +تشغيل البرنامج ينشئ `output.png` في دليل العمل. افتحه وسترى نتيجة **render html to png** – نص واضح ومضاد للتعرج على خلفية بيضاء، بدقة 800 × 600 بكسل. + + + +> **Expected output:** ملف PNG يُظهر “Sample text” بحجم 24 px خط Arial، غامق ومائل، في وسط الصورة. إذا غيرت سلسلة HTML أو قيم `Width`/`Height`، سيتغير PNG وفقًا لذلك. + +## Convert HTML to Image – الاختلافات الشائعة وحالات الحافة + +### 1. تصيير صفحة ويب عن بُعد + +إذا كنت بحاجة إلى **convert HTML to image** من URL مباشر، ما عليك سوى تمرير الـ URL إلى `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +تأكد من أن الموقع المستهدف يسمح بالوصول البرمجي (CORS، المصادقة، إلخ). + +### 2. خلفيات شفافة + +عيّن `BackColor = Color.Transparent` واختر صيغة PNG تدعم قنوات ألفا. هذا مفيد لتراكب الصورة على عناصر واجهة أخرى. + +### 3. إخراج عالي الدقة + +لرسومات جاهزة للطباعة، زد من `Width` و `Height` مع ضبط `DPI` أيضًا: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. معالجة ملفات الأنماط الكبيرة + +Aspose.HTML يقوم تلقائيًا بتحميل ملفات CSS المرتبطة. إذا أردت تقليل طلبات الشبكة، أدمج CSS الضروري مباشرةً في سلسلة HTML أو استخدم `ResourceLoadingOptions` لتخزين الموارد مؤقتًا. + +## مثال كامل قابل للتنفيذ + +فيما يلي البرنامج الكامل الذي يمكنك نسخه ولصقه في تطبيق Console. يتضمن جميع الخطوات، التعليقات، والتعديلات الاختيارية التي نوقشت أعلاه. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +قم بتجميعه وتشغيله (`dotnet run` إذا كنت تستخدم .NET CLI). سيتأكد الطرفية من إنشاء الملف، وستجد `output.png` بجوار الملف التنفيذي. + +## الخلاصة + +لقد غطينا كل ما تحتاجه لتتمكن من **render HTML to PNG** باستخدام Aspose.HTML في C#. من إنشاء المستند، تعديل خيارات التصيير، تطبيق أنماط الخط المخصصة، إلى حفظ الصورة في النهاية—كل خطوة تم شرح **لماذا** هي مهمة، وليس فقط **كيف** تُكتب. + +إذا كنت تبحث عن **convert HTML to image** بصيغ أخرى، ما عليك سوى تغيير امتداد الملف في `renderer.Save` إلى `.jpeg` أو `.bmp` وضبط `ImageSaveOptions` وفقًا لذلك. هل تريد معالجة دفعات من الصفحات؟ ضع كتلة التصيير داخل حلقة `foreach` ومرّر كل سلسلة HTML أو URL. + +### ما التالي؟ + +- **استكشاف إنشاء PDF** – يمكن لـ Aspose.HTML أيضًا تصدير إلى PDF مع خيارات مماثلة. +- **دمج صفحات متعددة** – تصيير كل صفحة من مستند HTML متعدد الصفحات إلى PNG منفصل. +- **دمج مع ASP.NET Core** – إرجاع PNG مباشرةً كـ `FileResult` لالتقاط لقطات شاشة فورية. + +لا تتردد في تجربة الإعدادات، استبدال محتوى HTML، أو دمج هذا الكود في خدمة ويب. السماء هي الحد عندما يمكنك **generate PNG from HTML** في الوقت الحقيقي. + +هل لديك أسئلة أو حالة استخدام معقدة؟ اترك تعليقًا أدناه، ونتمنى لك برمجة سعيدة! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/chinese/net/html-extensions-and-conversions/_index.md b/html/chinese/net/html-extensions-and-conversions/_index.md index a6c24babf..4253f51f9 100644 --- a/html/chinese/net/html-extensions-and-conversions/_index.md +++ b/html/chinese/net/html-extensions-and-conversions/_index.md @@ -65,6 +65,8 @@ Aspose.HTML for .NET 不仅仅是一个库;它是 Web 开发领域的变革者 探索 Aspose.HTML for .NET 的强大功能:轻松将 HTML 转换为 XPS。包含先决条件、分步指南和常见问题解答。 ### [如何在 C# 中压缩 HTML – 将 HTML 保存为 Zip](./how-to-zip-html-in-c-save-html-to-zip/) 使用 Aspose.HTML for .NET 在 C# 中将 HTML 打包并保存为 Zip 文件的分步教程。 +### [在 C# 中将 HTML 打包为 ZIP – 自定义资源处理程序教程](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +使用 Aspose.HTML for .NET 在 C# 中通过自定义资源处理程序将 HTML 打包为 ZIP 的完整指南。 ### [使用 Aspose.HTML 在 .NET 中创建带样式文本的 HTML 文档并导出为 PDF – 完整指南](./create-html-document-with-styled-text-and-export-to-pdf-full/) 本完整指南展示如何使用 Aspose.HTML for .NET 创建带样式的 HTML 文档并将其导出为 PDF,包含详细步骤和代码示例。 ### [使用 Aspose.HTML 在 C# 中将 HTML 创建为 PDF – 完整指南](./create-pdf-from-html-c-step-by-step-guide/) diff --git a/html/chinese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/chinese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..8baa694e0 --- /dev/null +++ b/html/chinese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-02-21 +description: 学习如何在 C# 中使用自定义资源处理程序将 HTML 打包为 zip。本指南还涵盖将 HTML 保存为 zip、将 HTML 转换为 zip,以及将 + HTML 保存到 zip。 +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: zh +og_description: 如何在 C# 中使用自定义资源处理程序压缩 HTML 为 zip。逐步代码、解释以及保存 HTML 为 zip 的技巧。 +og_title: 如何在 C# 中压缩 HTML – 完整指南 +tags: +- Aspose.HTML +- C# +- ZIP compression +title: 如何在 C# 中压缩 HTML – 自定义资源处理程序教程 +url: /zh/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 C# 中压缩 HTML – 自定义资源处理程序教程 + +是否曾想过直接在 .NET 应用中 **压缩 HTML** 而不触及文件系统?你并不孤单。许多开发者需要将 HTML 文档及其资源——图片、CSS、脚本——打包成一个 ZIP 文件,以便轻松传输或存储。 + +在本教程中,我们将展示一种使用 Aspose.HTML 的 `ResourceHandler` **将 HTML 保存为 zip** 的简洁方法。我们还会涉及诸如 **convert HTML to zip** 和 **save HTML to zip** 等相关主题,提供一个可在任何项目中直接使用的可复用处理程序。无需外部工具,无需临时文件——纯粹的内存操作。 + +## 您将学习到 + +* 如何创建一个内存中的 `HTMLDocument`。 +* 如何实现一个 **custom resource handler**,将每个资源流式写入同一个 ZIP 包。 +* 完整的代码示例,用于 **save HTML as zip** 并获取字节数组。 +* 处理大型图片或多个 CSS 文件等边缘情况的技巧。 +* 一个完整、可直接复制粘贴到 Visual Studio 的可运行示例。 + +> **Prerequisites** – 需要 .NET 6+(或 .NET Framework 4.6+)并通过 NuGet 安装 Aspose.HTML for .NET 库 (`Install-Package Aspose.HTML`)。无其他依赖。 + +--- + +## 第一步 – 创建 HTML 文档(How to Zip HTML) + +我们首先需要一个 `HTMLDocument` 实例来保存要压缩的标记。可以把它看作后续所有操作的画布。 + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **为什么重要:** 通过使用 `HTMLDocument`,我们让 Aspose.HTML 像浏览器一样处理 CSS 解析、布局和字体解析。这样生成的 PNG 与用户在 Chrome 或 Edge 中看到的页面完全一致。 + +## Convert HTML to Image – 配置渲染选项 + +接下来定义引擎如何光栅化标记。在这里**设置图像宽高**、启用抗锯齿,并选择背景颜色。 + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **小技巧:** 如果省略 `Width` 和 `Height`,Aspose.HTML 将使用页面的固有尺寸,这可能对缩略图来说太小。显式设置这些值即可完全控制最终 PNG 的尺寸。 + +## Generate PNG from HTML – 应用字体样式(可选) + +有时你需要加粗、斜体或两者兼有。`WebFontStyle` 枚举允许使用位或运算符 (`|`) 合并标志。此步骤为可选,但演示了如何**使用自定义样式将 HTML 生成 PNG**。 + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **正在发生什么:** `combinedFontStyle.ToString()` 返回 `"Bold, Italic"`,引擎会将其转换为有效的 CSS `font-style` 值。结果是文本既加粗又倾斜的 PNG。 + +## Save HTML as PNG – 最终渲染调用 + +现在把所有内容串联起来。`Image` 渲染器将光栅化后的内容写入磁盘文件。 + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +运行程序后,会在工作目录生成 `output.png`。打开它,你将看到**render html to png**的结果——文字在白色画布上清晰、抗锯齿,尺寸恰为 800 × 600 像素。 + + + +> **预期输出:** 一个 PNG 文件,显示 “Sample text” 使用 24 px Arial、加粗且斜体,居中显示在图像中。如果修改 HTML 字符串或 `Width`/`Height` 值,PNG 会相应更新。 + +## Convert HTML to Image – 常见变体与边缘情况 + +### 1. 渲染远程网页 + +如果需要**将 HTML 转换为图像**来自实时 URL,只需将 URL 传给 `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +确保目标站点允许程序化访问(CORS、身份验证等)。 + +### 2. 透明背景 + +将 `BackColor = Color.Transparent` 并选择支持 alpha 通道的 PNG 格式。这在将图像叠加到其他 UI 元素上时非常实用。 + +### 3. 高分辨率输出 + +针对印刷级图形,增大 `Width` 和 `Height`,同时设置 `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. 处理大型样式表 + +Aspose.HTML 会自动下载链接的 CSS 文件。如果想限制网络请求,可将关键 CSS 直接嵌入 HTML 字符串,或使用 `ResourceLoadingOptions` 对资源进行缓存。 + +## 完整可运行示例 + +下面是完整程序代码,可直接复制粘贴到控制台应用中。它包含了上述所有步骤、注释以及可选的微调。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +编译并运行(使用 .NET CLI 时执行 `dotnet run`)。控制台会确认文件已创建,`output.png` 将出现在可执行文件旁边。 + +## 总结 + +我们已经完整演示了如何使用 Aspose.HTML 在 C# 中**将 HTML 渲染为 PNG**。从创建文档、调整渲染选项、应用自定义字体样式,到最终保存图像——每一步都解释了**为什么**重要,而不仅仅是**如何**操作。 + +如果你想**将 HTML 转换为图像**的其他格式,只需在 `renderer.Save` 中将文件扩展名改为 `.jpeg` 或 `.bmp`,并相应调整 `ImageSaveOptions`。想要批量处理大量页面?将渲染块放入 `foreach` 循环,逐个传入 HTML 字符串或 URL 即可。 + +### 接下来可以做什么? + +- **探索 PDF 生成**——Aspose.HTML 也可以使用类似选项导出为 PDF。 +- **合并多页**——将多页 HTML 文档的每一页渲染为单独的 PNG。 +- **与 ASP.NET Core 集成**——直接返回 PNG 作为 `FileResult`,实现即时截图。 + +欢迎随意实验设置、替换 HTML 内容,或将此代码嵌入 Web 服务。只要能够**在运行时生成 PNG**,你的想象力就是唯一的限制。 + +有问题或特殊使用场景?在下方留言,祝编码愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/czech/net/html-extensions-and-conversions/_index.md b/html/czech/net/html-extensions-and-conversions/_index.md index dc8f6f072..7173e0dff 100644 --- a/html/czech/net/html-extensions-and-conversions/_index.md +++ b/html/czech/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Naučte se vytvořit HTML dokument se stylovaným textem a převést jej do PDF Naučte se, jak uložit HTML soubor jako ZIP archiv pomocí Aspose.HTML pro .NET v kompletním C# tutoriálu. ### [Uložte HTML do ZIP v C# – Kompletní příklad v paměti](./save-html-to-zip-in-c-complete-in-memory-example/) Naučte se, jak uložit HTML soubor do ZIP archivu v paměti pomocí Aspose.HTML pro .NET v C#. +### [Jak zkomprimovat HTML v C# – Vlastní handler zdrojů](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Naučte se pomocí Aspose.HTML pro .NET vytvořit vlastní handler zdrojů pro kompresi HTML do ZIP v C#. ## Závěr diff --git a/html/czech/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/czech/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..51d18d35a --- /dev/null +++ b/html/czech/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,244 @@ +--- +category: general +date: 2026-02-21 +description: Naučte se, jak zabalit HTML do zipu pomocí vlastního obslužníka zdrojů + v C#. Tento průvodce také pokrývá ukládání HTML jako zip, převod HTML do zipu a + ukládání HTML do zipu. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: cs +og_description: Jak zkomprimovat HTML v C# pomocí vlastního správce zdrojů. Krok za + krokem kód, vysvětlení a tipy pro ukládání HTML jako zip. +og_title: Jak zipovat HTML v C# – Kompletní průvodce +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Jak zipovat HTML v C# – Tutoriál o vlastním handleru zdrojů +url: /cs/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +. + +Proceed. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak zipovat HTML v C# – Návod na vlastní Resource Handler + +Už jste se někdy zamysleli, **jak zipovat HTML** přímo z vaší .NET aplikace, aniž byste se dotýkali souborového systému? Nejste v tom sami. Mnoho vývojářů potřebuje zabalit HTML dokument spolu s jeho zdroji — obrázky, CSS, skripty — do jediného ZIP souboru pro snadný přenos nebo ukládání. + +V tomto tutoriálu vám ukážeme čistý způsob, jak **uložit HTML jako zip** pomocí `ResourceHandler` z Aspose.HTML. Dotkneme se také souvisejících témat, jako je **convert HTML to zip** a **save HTML to zip**, s opakovaně použitelným handlerem, který můžete vložit do libovolného projektu. Žádné externí nástroje, žádné dočasné soubory — pouze čistá paměťová magie. + +## Co se naučíte + +* Jak vytvořit `HTMLDocument` v paměti. +* Jak implementovat **custom resource handler**, který streamuje každý zdroj do jednoho ZIP archivu. +* Přesný kód potřebný k **save HTML as zip** a získání pole bajtů. +* Tipy pro řešení okrajových případů, jako jsou velké obrázky nebo více CSS souborů. +* Kompletní, spustitelný příklad, který můžete zkopírovat a vložit do Visual Studia. + +> **Prerequisites** – Potřebujete .NET 6+ (nebo .NET Framework 4.6+) a knihovnu Aspose.HTML pro .NET nainstalovanou přes NuGet (`Install-Package Aspose.HTML`). Žádné další závislosti. + +--- + +## Krok 1 – Vytvořte HTML dokument (How to Zip HTML) + +Prvním, co potřebujeme, je instance `HTMLDocument`, která obsahuje značkování, které chceme komprimovat. Považujte ji za plátno pro zbytek procesu. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Proč je to důležité:** Použitím `HTMLDocument` necháme Aspose.HTML zpracovat parsování CSS, rozvržení a řešení fontů přesně tak, jako by to udělal prohlížeč. To zaručuje, že získaný PNG bude vypadat identicky s tím, co uživatel vidí v Chrome nebo Edge. + +## Convert HTML to Image – Nastavení možností renderování + +Dále definujeme, jak má engine rasterizovat značkování. Zde **set image width height**, povolíte antialiasing a vyberete barvu pozadí. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Tip:** Pokud vynecháte `Width` a `Height`, Aspose.HTML použije vnitřní velikost stránky, která může být pro náhledy příliš malá. Explicitní nastavení těchto hodnot vám dává plnou kontrolu nad konečnými rozměry PNG. + +## Generate PNG from HTML – Použití stylů fontů (volitelné) + +Někdy potřebujete tučný, kurzívní nebo kombinaci stylů. Výčtový typ `WebFontStyle` vám umožňuje sloučit příznaky pomocí bitového OR operátoru (`|`). Tento krok je volitelný, ale ukazuje, jak **generate PNG from HTML** s vlastním stylingem. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **Co se děje:** `combinedFontStyle.ToString()` vrací `"Bold, Italic"`, což engine přeloží na platnou CSS hodnotu `font-style`. Výsledkem je PNG, kde text je zároveň tučný i kurzívní. + +## Save HTML as PNG – Poslední volání renderování + +Nyní vše spojíme. Renderer `Image` zapíše rasterizovaný obsah do souboru na disku. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Spuštěním programu se vytvoří `output.png` v pracovním adresáři. Otevřete jej a uvidíte výsledek **render html to png** — ostrý, antialiasovaný text na bílém plátně, přesně 800 × 600 pixelů. + + + +> **Očekávaný výstup:** PNG soubor zobrazující „Sample text“ ve 24‑px Arial, tučně a kurzívně, vycentrovaný v obrázku. Pokud změníte HTML řetězec nebo hodnoty `Width`/`Height`, PNG se podle toho aktualizuje. + +## Convert HTML to Image – Běžné varianty a okrajové případy + +### 1. Renderování vzdálené webové stránky + +Pokud potřebujete **convert HTML to image** z živé URL, stačí předat URL do `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Ujistěte se, že cílový web povoluje programový přístup (CORS, autentizace atd.). + +### 2. Průhledná pozadí + +Nastavte `BackColor = Color.Transparent` a zvolte PNG formát, který podporuje alfa kanály. To je užitečné pro překrytí obrázku na jiné UI prvky. + +### 3. Vysoké rozlišení výstupu + +Pro grafiku připravenou k tisku zvýšte `Width` a `Height` a zároveň nastavte `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Práce s velkými styly + +Aspose.HTML automaticky stahuje propojené CSS soubory. Pokud chcete omezit síťová volání, vložte kritické CSS přímo do HTML řetězce nebo použijte `ResourceLoadingOptions` pro kešování zdrojů. + +## Kompletní, spustitelný příklad + +Níže je kompletní program, který můžete zkopírovat a vložit do konzolové aplikace. Obsahuje všechny kroky, komentáře a volitelné úpravy zmíněné výše. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Zkompilujte a spusťte (`dotnet run`, pokud používáte .NET CLI). Konzole potvrdí vytvoření souboru a `output.png` najdete vedle spustitelného souboru. + +## Závěr + +Právě jsme probrali vše, co potřebujete k **render HTML to PNG** pomocí Aspose.HTML v C#. Od vytvoření dokumentu, úpravy možností renderování, aplikace vlastních stylů fontů až po finální uložení obrázku — každý krok byl vysvětlen **proč** je důležitý, ne jen **jak** jej zadat. + +Pokud chcete **convert HTML to image** pro jiné formáty, stačí změnit příponu souboru v `renderer.Save` na `.jpeg` nebo `.bmp` a podle toho upravit `ImageSaveOptions`. Chcete zpracovat hromadně desítky stránek? Zabalte blok renderování do smyčky `foreach` a předávejte každý HTML řetězec nebo URL. + +### Co dál? + +- **Explore PDF generation** – Aspose.HTML může také exportovat do PDF s podobnými možnostmi. +- **Combine multiple pages** – Renderujte každou stránku vícestránkového HTML dokumentu do samostatných PNG. +- **Integrate with ASP.NET Core** – Vraťte PNG přímo jako `FileResult` pro okamžité snímky obrazovky. + +Neváhejte experimentovat s nastavením, vyměnit HTML obsah nebo tento kód zapojit do webové služby. Možnosti jsou neomezené, když můžete **generate PNG from HTML** za běhu. + +Máte otázky nebo složitý případ použití? Zanechte komentář níže a šťastné kódování! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/dutch/net/html-extensions-and-conversions/_index.md b/html/dutch/net/html-extensions-and-conversions/_index.md index fd924a78c..c39819089 100644 --- a/html/dutch/net/html-extensions-and-conversions/_index.md +++ b/html/dutch/net/html-extensions-and-conversions/_index.md @@ -48,7 +48,7 @@ Leer hoe u EPUB naar XPS converteert in .NET met Aspose.HTML voor .NET. Volg onz ### [Converteer HTML naar BMP in .NET met Aspose.HTML](./convert-html-to-bmp/) Leer hoe u HTML naar BMP converteert in .NET met Aspose.HTML voor .NET. Uitgebreide handleiding voor webontwikkelaars voor het benutten van Aspose.HTML voor .NET. ### [Converteer HTML naar DOC en DOCX in .NET met Aspose.HTML](./convert-html-to-doc-docx/) -Leer hoe u de kracht van Aspose.HTML voor .NET kunt benutten in deze stapsgewijze handleiding. Converteer moeiteloos HTML naar DOCX en breng uw .NET-projecten naar een hoger niveau. Ga vandaag nog aan de slag! +Leer de kracht van Aspose.HTML voor .NET kunt benutten in deze stapsgewijze handleiding. Converteer moeiteloos HTML naar DOCX en breng uw .NET-projecten naar een hoger niveau. Ga vandaag nog aan de slag! ### [Converteer HTML naar GIF in .NET met Aspose.HTML](./convert-html-to-gif/) Ontdek de kracht van Aspose.HTML voor .NET: een stapsgewijze handleiding voor het converteren van HTML naar GIF. Vereisten, codevoorbeelden, FAQ's en meer! Optimaliseer uw HTML-manipulatie met Aspose.HTML. ### [Converteer HTML naar JPEG in .NET met Aspose.HTML](./convert-html-to-jpeg/) @@ -65,6 +65,8 @@ Leer hoe u HTML naar TIFF converteert met Aspose.HTML voor .NET. Volg onze staps Ontdek de kracht van Aspose.HTML voor .NET: Converteer HTML moeiteloos naar XPS. Vereisten, stapsgewijze handleiding en veelgestelde vragen inbegrepen. ### [HTML zippen in C# – HTML opslaan in zip](./how-to-zip-html-in-c-save-html-to-zip/) Leer hoe u HTML-bestanden comprimeert naar een zip‑archief met C# en Aspose.HTML voor .NET. +### [HTML zippen in C# – Aangepaste resourcehandler-tutorial](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Leer hoe u HTML-bestanden zipt in C# met een aangepaste resourcehandler via Aspose.HTML voor .NET. ### [Maak HTML-document met opgemaakte tekst en exporteer naar PDF – Volledige gids](./create-html-document-with-styled-text-and-export-to-pdf-full/) Leer hoe u een HTML-document met opgemaakte tekst maakt en deze volledig naar PDF exporteert met Aspose.HTML voor .NET. ### [Maak PDF van HTML – C# Stapsgewijze handleiding](./create-pdf-from-html-c-step-by-step-guide/) diff --git a/html/dutch/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/dutch/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..4b6a6d6a9 --- /dev/null +++ b/html/dutch/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-02-21 +description: Leer hoe je HTML kunt zippen met een aangepaste resourcehandler in C#. + Deze gids behandelt ook het opslaan van HTML als zip, het converteren van HTML naar + zip en het opslaan van HTML naar zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: nl +og_description: Hoe HTML zippen in C# met een aangepaste resourcehandler. Stapsgewijze + code, uitleg en tips voor het opslaan van HTML als zip. +og_title: Hoe HTML te zippen in C# – Complete gids +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Hoe HTML te zippen in C# – Tutorial voor aangepaste resourcehandler +url: /nl/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +". "Step 1 – Create the HTML Document (How to Zip HTML)" -> "Stap 1 – Maak het HTML-document (Hoe HTML te zippen)". etc. + +Make sure to keep code block placeholders unchanged. + +Also blockquote > lines need translation. + +Let's craft. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe HTML te zippen in C# – Custom Resource Handler Tutorial + +Heb je je ooit afgevraagd **hoe je HTML kunt zippen** direct vanuit je .NET‑app zonder het bestandssysteem aan te raken? Je bent niet de enige. Veel ontwikkelaars moeten een HTML‑document samen met zijn bronnen—afbeeldingen, CSS, scripts—verpakken in één ZIP‑bestand voor gemakkelijke transport of opslag. + +In deze tutorial laten we je een nette manier zien om **HTML op te slaan als zip** met behulp van Aspose.HTML’s `ResourceHandler`. We behandelen ook gerelateerde onderwerpen zoals **convert HTML to zip** en **save HTML to zip** met een herbruikbare handler die je in elk project kunt gebruiken. Geen externe tools, geen tijdelijke bestanden—alleen pure in‑memory magie. + +## Wat je zult leren + +* Hoe je een in‑memory `HTMLDocument` maakt. +* Hoe je een **custom resource handler** implementeert die elke bron naar één ZIP‑archief streamt. +* De exacte code die nodig is om **HTML op te slaan als zip** en de byte‑array op te halen. +* Tips voor het afhandelen van randgevallen zoals grote afbeeldingen of meerdere CSS‑bestanden. +* Een compleet, uitvoerbaar voorbeeld dat je kunt copy‑pasten in Visual Studio. + +> **Voorvereisten** – Je hebt .NET 6+ (of .NET Framework 4.6+) en de Aspose.HTML for .NET‑bibliotheek geïnstalleerd via NuGet (`Install-Package Aspose.HTML`). Geen andere afhankelijkheden. + +--- + +## Stap 1 – Maak het HTML‑document (Hoe HTML te zippen) + +Het eerste wat we nodig hebben is een `HTMLDocument`‑instantie die de markup bevat die we willen comprimeren. Beschouw dit als het canvas voor de rest van het proces. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Waarom dit belangrijk is:** Door `HTMLDocument` te gebruiken laat je Aspose.HTML CSS‑parsing, layout en lettertype‑resolutie afhandelen precies zoals een browser dat zou doen. Dat garandeert dat de PNG die je krijgt er identiek uitziet aan wat een gebruiker zou zien in Chrome of Edge. + +## HTML naar afbeelding converteren – Renderopties configureren + +Vervolgens definiëren we hoe de engine de markup moet rasteren. Hier stel je **beeldbreedte en -hoogte in**, schakel je antialiasing in en kies je een achtergrondkleur. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Pro tip:** Als je `Width` en `Height` weglaten, zal Aspose.HTML de intrinsieke grootte van de pagina gebruiken, wat te klein kan zijn voor miniaturen. Door deze waarden expliciet in te stellen krijg je volledige controle over de uiteindelijke PNG‑afmetingen. + +## PNG uit HTML genereren – Lettertype‑stijlen toepassen (optioneel) + +Soms heb je vet, cursief of een combinatie van stijlen nodig. De `WebFontStyle`‑enum laat je vlaggen combineren met de bitwise OR‑operator (`|`). Deze stap is optioneel maar toont hoe je **PNG uit HTML kunt genereren** met aangepaste styling. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **Wat er gebeurt:** `combinedFontStyle.ToString()` retourneert `"Bold, Italic"` die de engine vertaalt naar een geldige CSS `font-style`‑waarde. Het resultaat is een PNG waarin de tekst zowel vet als cursief verschijnt. + +## HTML opslaan als PNG – De uiteindelijke renderaanroep + +Nu verbinden we alles. De `Image`‑renderer schrijft de gerasterde inhoud naar een bestand op schijf. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Het uitvoeren van het programma maakt `output.png` aan in de werkmap. Open het, en je ziet het **render html to png**‑resultaat – scherpe, antialiaste tekst op een wit canvas, precies 800 × 600 pixels. + + + +> **Verwachte output:** Een PNG‑bestand dat “Sample text” toont in 24‑px Arial, vet en cursief, gecentreerd in de afbeelding. Als je de HTML‑string of de `Width`/`Height`‑waarden wijzigt, wordt de PNG dienovereenkomstig bijgewerkt. + +## HTML naar afbeelding converteren – Veelvoorkomende variaties & randgevallen + +### 1. Een externe webpagina renderen + +Als je **HTML naar afbeelding moet converteren** vanaf een live URL, geef je simpelweg de URL door aan `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Zorg ervoor dat de doelsite programmatische toegang toestaat (CORS, authenticatie, enz.). + +### 2. Transparante achtergronden + +Stel `BackColor = Color.Transparent` in en kies een PNG‑formaat dat alfakanalen ondersteunt. Dit is handig om de afbeelding over andere UI‑elementen te leggen. + +### 3. Hoge‑resolutie output + +Voor print‑klare graphics, verhoog `Width` en `Height` en stel ook `DPI` in: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Grote stylesheets verwerken + +Aspose.HTML downloadt automatisch gekoppelde CSS‑bestanden. Als je netwerkverzoeken wilt beperken, embed je kritieke CSS direct in de HTML‑string of gebruik je `ResourceLoadingOptions` om bronnen te cachen. + +## Volledig, uitvoerbaar voorbeeld + +Hieronder staat het volledige programma dat je kunt kopiëren‑plakken in een console‑applicatie. Het bevat alle stappen, commentaren en optionele aanpassingen die hierboven zijn besproken. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Compileer en voer uit (`dotnet run` als je de .NET CLI gebruikt). De console bevestigt de bestandscreatie, en je vindt `output.png` naast het uitvoerbare bestand. + +## Samenvatting + +We hebben zojuist alles behandeld wat je nodig hebt om **HTML naar PNG te renderen** met Aspose.HTML in C#. Van het aanmaken van het document, het aanpassen van renderopties, het toepassen van aangepaste lettertype‑stijlen, tot het uiteindelijk opslaan van de afbeelding — elke stap is uitgelegd **waarom** het belangrijk is, niet alleen **hoe** je het moet typen. + +Als je **HTML naar afbeelding wilt converteren** voor andere formaten, wijzig dan simpelweg de bestandsextensie in `renderer.Save` naar `.jpeg` of `.bmp` en pas `ImageSaveOptions` dienovereenkomstig aan. Wil je tientallen pagina's in batch verwerken? Plaats het renderblok in een `foreach`‑lus en lever elke HTML‑string of URL. + +### Wat is het volgende? + +- **PDF‑generatie verkennen** – Aspose.HTML kan ook exporteren naar PDF met vergelijkbare opties. +- **Meerdere pagina's combineren** – Render elke pagina van een meer‑pagina HTML‑document naar afzonderlijke PNG‑s. +- **Integreren met ASP.NET Core** – Retourneer de PNG direct als een `FileResult` voor screenshots on‑the‑fly. + +Voel je vrij om te experimenteren met de instellingen, de HTML‑inhoud te vervangen, of deze code in een webservice te integreren. De mogelijkheden zijn eindeloos wanneer je **PNG uit HTML kunt genereren** on‑the‑fly. + +Heb je vragen of een lastig gebruiksgeval? Laat een reactie achter hieronder, en happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/english/net/html-extensions-and-conversions/_index.md b/html/english/net/html-extensions-and-conversions/_index.md index a50bc9ccb..53669676e 100644 --- a/html/english/net/html-extensions-and-conversions/_index.md +++ b/html/english/net/html-extensions-and-conversions/_index.md @@ -67,6 +67,8 @@ Learn how to convert HTML to TIFF with Aspose.HTML for .NET. Follow our step-by- Discover the power of Aspose.HTML for .NET: Convert HTML to XPS effortlessly. Prerequisites, step-by-step guide, and FAQs included. ### [How to Zip HTML in C# – Save HTML to Zip](./how-to-zip-html-in-c-save-html-to-zip/) Learn how to zip HTML files in C# using Aspose.HTML, saving HTML content to a ZIP archive with step-by-step guidance. +### [How to Zip HTML in C# – Custom Resource Handler Tutorial](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Learn how to zip HTML files using a custom resource handler in C# with Aspose.HTML for .NET. ### [Create HTML Document with Styled Text and Export to PDF – Full Guide](./create-html-document-with-styled-text-and-export-to-pdf-full/) Learn how to create an HTML document with styled text and export it to PDF using Aspose.HTML for .NET in this comprehensive guide. ### [Save HTML as ZIP – Complete C# Tutorial](./save-html-as-zip-complete-c-tutorial/) diff --git a/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..88816c993 --- /dev/null +++ b/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-02-21 +description: Learn how to zip HTML using a custom resource handler in C#. This guide + also covers save HTML as zip, convert HTML to zip, and save HTML to zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: en +og_description: How to zip HTML in C# using a custom resource handler. Step‑by‑step + code, explanations, and tips for saving HTML as zip. +og_title: How to Zip HTML in C# – Complete Guide +tags: +- Aspose.HTML +- C# +- ZIP compression +title: How to Zip HTML in C# – Custom Resource Handler Tutorial +url: /net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to Zip HTML in C# – Custom Resource Handler Tutorial + +Ever wondered **how to zip HTML** directly from your .NET app without touching the file system? You’re not alone. Many developers need to package an HTML document together with its resources—images, CSS, scripts—into a single ZIP file for easy transport or storage. + +In this tutorial we’ll show you a clean way to **save HTML as zip** using Aspose.HTML’s `ResourceHandler`. We’ll also touch on related topics like **convert HTML to zip** and **save HTML to zip** with a reusable handler that you can drop into any project. No external tools, no temporary files—just pure in‑memory magic. + +## What You’ll Learn + +* How to create an in‑memory `HTMLDocument`. +* How to implement a **custom resource handler** that streams every resource into one ZIP archive. +* The exact code needed to **save HTML as zip** and retrieve the byte array. +* Tips for handling edge cases such as large images or multiple CSS files. +* A complete, runnable example you can copy‑paste into Visual Studio. + +> **Prerequisites** – You need .NET 6+ (or .NET Framework 4.6+) and the Aspose.HTML for .NET library installed via NuGet (`Install-Package Aspose.HTML`). No other dependencies. + +--- + +## Step 1 – Create the HTML Document (How to Zip HTML) + +The first thing we need is an `HTMLDocument` instance that holds the markup we want to compress. Think of this as the canvas for the rest of the process. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Why this matters:** By using `HTMLDocument` we let Aspose.HTML handle CSS parsing, layout, and font resolution exactly as a browser would. That guarantees the PNG you get looks identical to what a user would see in Chrome or Edge. + +## Convert HTML to Image – Configure Rendering Options + +Next we define how the engine should rasterize the markup. This is where you **set image width height**, enable antialiasing, and pick a background colour. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Pro tip:** If you omit `Width` and `Height`, Aspose.HTML will use the intrinsic size of the page, which may be too small for thumbnails. Explicitly setting these values gives you full control over the final PNG dimensions. + +## Generate PNG from HTML – Apply Font Styles (Optional) + +Sometimes you need bold, italic, or a combination of styles. The `WebFontStyle` enum lets you merge flags using the bitwise OR operator (`|`). This step is optional but demonstrates how to **generate PNG from HTML** with custom styling. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **What’s happening:** `combinedFontStyle.ToString()` returns `"Bold, Italic"` which the engine translates into a valid CSS `font-style` value. The result is a PNG where the text appears both bold and italic. + +## Save HTML as PNG – The Final Rendering Call + +Now we tie everything together. The `Image` renderer writes the rasterized content to a file on disk. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Running the program creates `output.png` in the working directory. Open it, and you’ll see the **render html to png** result – crisp, antialiased text on a white canvas, exactly 800 × 600 pixels. + + + +> **Expected output:** A PNG file showing “Sample text” in 24‑px Arial, bold and italic, centered in the image. If you change the HTML string or the `Width`/`Height` values, the PNG updates accordingly. + +## Convert HTML to Image – Common Variations & Edge Cases + +### 1. Rendering a Remote Web Page + +If you need to **convert HTML to image** from a live URL, just pass the URL to `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Make sure the target site allows programmatic access (CORS, authentication, etc.). + +### 2. Transparent Backgrounds + +Set `BackColor = Color.Transparent` and choose a PNG format that supports alpha channels. This is handy for overlaying the image on other UI elements. + +### 3. High‑Resolution Output + +For print‑ready graphics, increase `Width` and `Height` while also setting `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Handling Large Stylesheets + +Aspose.HTML automatically downloads linked CSS files. If you want to limit network calls, embed critical CSS directly in the HTML string or use the `ResourceLoadingOptions` to cache resources. + +## Full, Runnable Example + +Below is the complete program you can copy‑paste into a console application. It includes all the steps, comments, and optional tweaks discussed above. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Compile and run (`dotnet run` if you’re using the .NET CLI). The console will confirm the file creation, and you’ll find `output.png` beside the executable. + +## Wrap‑Up + +We’ve just covered everything you need to **render HTML to PNG** using Aspose.HTML in C#. From creating the document, tweaking rendering options, applying custom font styles, to finally saving the image—each step was explained **why** it matters, not just **how** to type it. + +If you’re looking to **convert HTML to image** for other formats, simply change the file extension in `renderer.Save` to `.jpeg` or `.bmp` and adjust `ImageSaveOptions` accordingly. Want to batch‑process dozens of pages? Wrap the rendering block in a `foreach` loop and feed each HTML string or URL. + +### What’s Next? + +- **Explore PDF generation** – Aspose.HTML can also export to PDF with similar options. +- **Combine multiple pages** – Render each page of a multi‑page HTML document to separate PNGs. +- **Integrate with ASP.NET Core** – Return the PNG directly as a `FileResult` for on‑the‑fly screenshots. + +Feel free to experiment with the settings, swap out the HTML content, or plug this code into a web service. The sky’s the limit when you can **generate PNG from HTML** on the fly. + +Got questions or a tricky use‑case? Drop a comment below, and happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/french/net/html-extensions-and-conversions/_index.md b/html/french/net/html-extensions-and-conversions/_index.md index f4e02735c..838d0b283 100644 --- a/html/french/net/html-extensions-and-conversions/_index.md +++ b/html/french/net/html-extensions-and-conversions/_index.md @@ -74,6 +74,8 @@ Apprenez à compresser du HTML en un fichier zip avec C# grâce à notre guide d Apprenez à enregistrer un document HTML dans un fichier ZIP en C# avec Aspose.HTML pour .NET. Guide complet étape par étape. ### [Enregistrer HTML en ZIP en C# – Exemple complet en mémoire](./save-html-to-zip-in-c-complete-in-memory-example/) Enregistrez du HTML dans un fichier ZIP en mémoire avec Aspose.HTML pour .NET. +### [Comment zipper du HTML en C# – Tutoriel sur le gestionnaire de ressources personnalisé](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Apprenez à zipper du HTML en C# en utilisant un gestionnaire de ressources personnalisé avec Aspose.HTML pour .NET. ## Conclusion diff --git a/html/french/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/french/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..161f6ba08 --- /dev/null +++ b/html/french/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-02-21 +description: Apprenez à zipper du HTML à l'aide d'un gestionnaire de ressources personnalisé + en C#. Ce guide couvre également l'enregistrement du HTML en zip, la conversion + du HTML en zip et la sauvegarde du HTML en zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: fr +og_description: Comment compresser du HTML en C# à l'aide d'un gestionnaire de ressources + personnalisé. Code étape par étape, explications et conseils pour enregistrer le + HTML en zip. +og_title: Comment compresser du HTML en C# – Guide complet +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Comment compresser du HTML en C# – Tutoriel sur le gestionnaire de ressources + personnalisé +url: /fr/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment compresser du HTML en ZIP avec C# – Tutoriel sur le gestionnaire de ressources personnalisé + +Vous vous êtes déjà demandé **comment compresser du HTML en ZIP** directement depuis votre application .NET sans toucher au système de fichiers ? Vous n'êtes pas seul. De nombreux développeurs doivent empaqueter un document HTML avec ses ressources — images, CSS, scripts — dans un seul fichier ZIP pour faciliter le transport ou le stockage. + +Dans ce tutoriel, nous vous montrerons une méthode propre pour **enregistrer du HTML en zip** en utilisant le `ResourceHandler` d’Aspose.HTML. Nous aborderons également des sujets connexes comme **convertir du HTML en zip** et **enregistrer du HTML en zip** avec un gestionnaire réutilisable que vous pouvez intégrer à n’importe quel projet. Aucun outil externe, aucun fichier temporaire — juste de la magie pure en mémoire. + +## Ce que vous allez apprendre + +* Comment créer un `HTMLDocument` en mémoire. +* Comment implémenter un **gestionnaire de ressources personnalisé** qui diffuse chaque ressource dans une seule archive ZIP. +* Le code exact nécessaire pour **enregistrer du HTML en zip** et récupérer le tableau d’octets. +* Astuces pour gérer les cas limites tels que les images volumineuses ou plusieurs fichiers CSS. +* Un exemple complet et exécutable que vous pouvez copier‑coller dans Visual Studio. + +> **Prérequis** – Vous avez besoin de .NET 6+ (ou .NET Framework 4.6+) et de la bibliothèque Aspose.HTML pour .NET installée via NuGet (`Install-Package Aspose.HTML`). Aucune autre dépendance. + +--- + +## Étape 1 – Créer le document HTML (Comment compresser du HTML) + +La première chose dont nous avons besoin est une instance `HTMLDocument` qui contient le balisage que nous voulons compresser. Considérez-la comme la toile pour le reste du processus. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Pourquoi c’est important :** En utilisant `HTMLDocument`, nous laissons Aspose.HTML gérer l'analyse CSS, la mise en page et la résolution des polices exactement comme le ferait un navigateur. Cela garantit que le PNG obtenu est identique à ce qu'un utilisateur verrait dans Chrome ou Edge. + +## Convertir HTML en image – Configurer les options de rendu + +Ensuite, nous définissons comment le moteur doit rasteriser le balisage. C’est ici que vous **set image width height**, activez l'anticrénelage et choisissez une couleur d'arrière‑plan. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Astuce :** Si vous omettez `Width` et `Height`, Aspose.HTML utilisera la taille intrinsèque de la page, ce qui peut être trop petit pour les vignettes. Définir explicitement ces valeurs vous donne un contrôle total sur les dimensions finales du PNG. + +## Générer PNG à partir de HTML – Appliquer les styles de police (optionnel) + +Parfois, vous avez besoin de gras, d'italique ou d'une combinaison de styles. L'énumération `WebFontStyle` vous permet de fusionner des drapeaux à l'aide de l'opérateur OU bit à bit (`|`). Cette étape est optionnelle mais montre comment **generate PNG from HTML** avec un style personnalisé. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **Ce qui se passe :** `combinedFontStyle.ToString()` renvoie `"Bold, Italic"` que le moteur traduit en une valeur CSS `font-style` valide. Le résultat est un PNG où le texte apparaît à la fois en gras et en italique. + +## Enregistrer HTML en PNG – L’appel final de rendu + +Nous rassemblons maintenant le tout. Le rendu `Image` écrit le contenu rasterisé dans un fichier sur le disque. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +L'exécution du programme crée `output.png` dans le répertoire de travail. Ouvrez-le, et vous verrez le résultat **render html to png** – du texte net, antialiasé sur un canevas blanc, exactement 800 × 600 pixels. + + + +> **Sortie attendue :** Un fichier PNG affichant « Sample text » en Arial 24 px, gras et italique, centré dans l'image. Si vous modifiez la chaîne HTML ou les valeurs `Width`/`Height`, le PNG se met à jour en conséquence. + +## Convertir HTML en image – Variations courantes et cas limites + +### 1. Rendu d'une page web distante + +Si vous devez **convert HTML to image** depuis une URL en direct, passez simplement l'URL à `HTMLDocument` : + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Assurez‑vous que le site cible autorise l'accès programmatique (CORS, authentification, etc.). + +### 2. Fonds transparents + +Définissez `BackColor = Color.Transparent` et choisissez un format PNG qui prend en charge les canaux alpha. Cela est pratique pour superposer l'image sur d'autres éléments d'interface. + +### 3. Sortie haute résolution + +Pour des graphiques prêts à l'impression, augmentez `Width` et `Height` tout en définissant également `DPI` : + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Gestion des grandes feuilles de style + +Aspose.HTML télécharge automatiquement les fichiers CSS liés. Si vous souhaitez limiter les appels réseau, intégrez le CSS critique directement dans la chaîne HTML ou utilisez `ResourceLoadingOptions` pour mettre en cache les ressources. + +## Exemple complet, exécutable + +Ci-dessous se trouve le programme complet que vous pouvez copier‑coller dans une application console. Il inclut toutes les étapes, commentaires et ajustements optionnels abordés précédemment. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Compilez et exécutez (`dotnet run` si vous utilisez le CLI .NET). La console confirmera la création du fichier, et vous trouverez `output.png` à côté de l'exécutable. + +## Conclusion + +Nous venons de couvrir tout ce dont vous avez besoin pour **render HTML to PNG** avec Aspose.HTML en C#. De la création du document, à l'ajustement des options de rendu, en passant par l'application de styles de police personnalisés, jusqu'à l'enregistrement final de l'image — chaque étape a été expliquée **why** elle est importante, pas seulement **how** la saisir. + +Si vous cherchez à **convert HTML to image** pour d'autres formats, il suffit de changer l'extension du fichier dans `renderer.Save` en `.jpeg` ou `.bmp` et d'ajuster `ImageSaveOptions` en conséquence. Vous voulez traiter par lots des dizaines de pages ? Enveloppez le bloc de rendu dans une boucle `foreach` et fournissez chaque chaîne HTML ou URL. + +### Et après ? + +- **Explore PDF generation** – Aspose.HTML peut également exporter en PDF avec des options similaires. +- **Combine multiple pages** – Rendre chaque page d'un document HTML multi‑pages en PNG séparés. +- **Integrate with ASP.NET Core** – Retourner le PNG directement en tant que `FileResult` pour des captures d'écran à la volée. + +N'hésitez pas à expérimenter avec les paramètres, à remplacer le contenu HTML, ou à intégrer ce code dans un service web. Le ciel est la limite lorsque vous pouvez **generate PNG from HTML** à la volée. + +Des questions ou un cas d'utilisation difficile ? Laissez un commentaire ci‑dessous, et bon codage ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/german/net/html-extensions-and-conversions/_index.md b/html/german/net/html-extensions-and-conversions/_index.md index 607896d28..e5bc8162d 100644 --- a/html/german/net/html-extensions-and-conversions/_index.md +++ b/html/german/net/html-extensions-and-conversions/_index.md @@ -30,7 +30,7 @@ Bei der Webentwicklung müssen HTML-Dokumente häufig in verschiedene Formate ko ## Erste Schritte mit Aspose.HTML -Sind Sie bereit, loszulegen? Die Tutorials von Aspose.HTML für .NET richten sich sowohl an Anfänger als auch an erfahrene Entwickler. Egal, ob Sie neu bei HTML-Erweiterungen und -Konvertierungen sind oder fortgeschrittene Tipps suchen, unsere Schritt-für-Schritt-Anleitungen sind auf Ihre Bedürfnisse zugeschnitten. +Sind Sie bereit, loszulegen? Die Tutorials von Aspose.HTML für .NET richten sich sowohl an Anfänger als auch an erfahrene Entwickler. Egal, ob Sie neu bei HTML-Erweiterungen und -Konvertierungen sind oder fortgeschrittene Tipps suchen, unsere Schritt‑für‑Schritt‑Anleitungen sind auf Ihre Bedürfnisse zugeschnitten. ## Warum Aspose.HTML für .NET? @@ -38,41 +38,45 @@ Aspose.HTML für .NET ist nicht nur eine Bibliothek; es verändert die Welt der ## Tutorials zu HTML-Erweiterungen und -Konvertierungen ### [Konvertieren Sie HTML in .NET in PDF mit Aspose.HTML](./convert-html-to-pdf/) -Konvertieren Sie HTML mühelos in PDF mit Aspose.HTML für .NET. Folgen Sie unserer Schritt-für-Schritt-Anleitung und entfesseln Sie die Leistungsfähigkeit der HTML-zu-PDF-Konvertierung. +Konvertieren Sie HTML mühelos in PDF mit Aspose.HTML für .NET. Folgen Sie unserer Schritt‑für‑Schritt‑Anleitung und entfesseln Sie die Leistungsfähigkeit der HTML‑zu‑PDF‑Konvertierung. ### [Konvertieren Sie EPUB in .NET mit Aspose.HTML in ein Bild](./convert-epub-to-image/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in Bilder konvertieren. Schritt-für-Schritt-Anleitung mit Codebeispielen und anpassbaren Optionen. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in Bilder konvertieren. Schritt‑für‑Schritt‑Anleitung mit Codebeispielen und anpassbaren Optionen. ### [Konvertieren Sie EPUB in .NET mit Aspose.HTML in PDF](./convert-epub-to-pdf/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in PDF konvertieren. Diese Schritt-für-Schritt-Anleitung umfasst Anpassungsoptionen, FAQs und mehr für eine nahtlose Dokumentkonvertierung. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in PDF konvertieren. Diese Schritt‑für‑Schritt‑Anleitung umfasst Anpassungsoptionen, FAQs und mehr für eine nahtlose Dokumentkonvertierung. ### [Konvertieren Sie EPUB in XPS in .NET mit Aspose.HTML](./convert-epub-to-xps/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in XPS in .NET konvertieren. Folgen Sie unserer Schritt-für-Schritt-Anleitung für mühelose Konvertierungen. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in XPS in .NET konvertieren. Folgen Sie unserer Schritt‑für‑Schritt‑Anleitung für mühelose Konvertierungen. ### [Konvertieren Sie HTML in BMP in .NET mit Aspose.HTML](./convert-html-to-bmp/) Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in BMP in .NET konvertieren. Umfassender Leitfaden für Webentwickler zur Nutzung von Aspose.HTML für .NET. ### [Konvertieren Sie HTML in .NET in DOC und DOCX mit Aspose.HTML](./convert-html-to-doc-docx/) -Erfahren Sie in dieser Schritt-für-Schritt-Anleitung, wie Sie die Leistung von Aspose.HTML für .NET nutzen. Konvertieren Sie HTML mühelos in DOCX und verbessern Sie Ihre .NET-Projekte. Legen Sie noch heute los! +Erfahren Sie in dieser Schritt‑für‑Schritt‑Anleitung, wie Sie die Leistung von Aspose.HTML für .NET nutzen. Konvertieren Sie HTML mühelos in DOCX und verbessern Sie Ihre .NET‑Projekte. Legen Sie noch heute los! ### [Konvertieren Sie HTML in GIF in .NET mit Aspose.HTML](./convert-html-to-gif/) -Entdecken Sie die Leistungsfähigkeit von Aspose.HTML für .NET: Eine Schritt-für-Schritt-Anleitung zur Konvertierung von HTML in GIF. Voraussetzungen, Codebeispiele, FAQs und mehr! Optimieren Sie Ihre HTML-Manipulation mit Aspose.HTML. +Entdecken Sie die Leistungsfähigkeit von Aspose.HTML für .NET: Eine Schritt‑für‑Schritt‑Anleitung zur Konvertierung von HTML in GIF. Voraussetzungen, Codebeispiele, FAQs und mehr! Optimieren Sie Ihre HTML‑Manipulation mit Aspose.HTML. ### [Konvertieren Sie HTML in JPEG in .NET mit Aspose.HTML](./convert-html-to-jpeg/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in JPEG in .NET konvertieren. Eine Schritt-für-Schritt-Anleitung zur Nutzung der Leistungsfähigkeit von Aspose.HTML für .NET. Optimieren Sie Ihre Webentwicklungsaufgaben mühelos. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in JPEG in .NET konvertieren. Eine Schritt‑für‑Schritt‑Anleitung zur Nutzung der Leistungsfähigkeit von Aspose.HTML für .NET. Optimieren Sie Ihre Webentwicklungsaufgaben mühelos. ### [Konvertieren Sie HTML in .NET in Markdown mit Aspose.HTML](./convert-html-to-markdown/) -Erfahren Sie, wie Sie HTML in .NET mit Aspose.HTML in Markdown konvertieren, um Inhalte effizient zu bearbeiten. Erhalten Sie eine Schritt-für-Schritt-Anleitung für einen nahtlosen Konvertierungsprozess. +Erfahren Sie, wie Sie HTML in .NET mit Aspose.HTML in Markdown konvertieren, um Inhalte effizient zu bearbeiten. Erhalten Sie eine Schritt‑für‑Schritt‑Anleitung für einen nahtlosen Konvertierungsprozess. ### [Konvertieren Sie HTML in MHTML in .NET mit Aspose.HTML](./convert-html-to-mhtml/) -Konvertieren Sie HTML in .NET in MHTML mit Aspose.HTML – Eine Schritt-für-Schritt-Anleitung zum effizienten Archivieren von Webinhalten. Erfahren Sie, wie Sie mit Aspose.HTML für .NET MHTML-Archive erstellen. +Konvertieren Sie HTML in .NET in MHTML mit Aspose.HTML – Eine Schritt‑für‑Schritt‑Anleitung zum effizienten Archivieren von Webinhalten. Erfahren Sie, wie Sie mit Aspose.HTML für .NET MHTML-Archive erstellen. ### [Konvertieren Sie HTML in PNG in .NET mit Aspose.HTML](./convert-html-to-png/) -Entdecken Sie, wie Sie mit Aspose.HTML für .NET HTML-Dokumente bearbeiten und konvertieren. Schritt-für-Schritt-Anleitung für effektive .NET-Entwicklung. +Entdecken Sie, wie Sie mit Aspose.HTML für .NET HTML‑Dokumente bearbeiten und konvertieren. Schritt‑für‑Schritt‑Anleitung für effektive .NET‑Entwicklung. ### [Konvertieren Sie HTML in TIFF in .NET mit Aspose.HTML](./convert-html-to-tiff/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in TIFF konvertieren. Folgen Sie unserer Schritt-für-Schritt-Anleitung zur effizienten Optimierung von Webinhalten. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in TIFF konvertieren. Folgen Sie unserer Schritt‑für‑Schritt‑Anleitung zur effizienten Optimierung von Webinhalten. ### [Konvertieren Sie HTML in XPS in .NET mit Aspose.HTML](./convert-html-to-xps/) -Entdecken Sie die Leistungsfähigkeit von Aspose.HTML für .NET: Konvertieren Sie HTML mühelos in XPS. Voraussetzungen, Schritt-für-Schritt-Anleitung und FAQs inklusive. +Entdecken Sie die Leistungsfähigkeit von Aspose.HTML für .NET: Konvertieren Sie HTML mühelos in XPS. Voraussetzungen, Schritt‑für‑Schritt‑Anleitung und FAQs inklusive. ### [HTML in C# zippen – HTML in Zip speichern](./how-to-zip-html-in-c-save-html-to-zip/) -Erfahren Sie, wie Sie HTML-Inhalte mit Aspose.HTML für .NET in eine ZIP-Datei komprimieren und speichern. -### [HTML-Dokument mit formatiertem Text erstellen und in PDF exportieren – Vollständige Anleitung](./create-html-document-with-styled-text-and-export-to-pdf-full/) -Erfahren Sie, wie Sie ein HTML-Dokument mit formatiertem Text erstellen und es mit Aspose.HTML für .NET in ein PDF exportieren. +Erfahren Sie, wie Sie HTML‑Inhalte mit Aspose.HTML für .NET in eine ZIP‑Datei komprimieren und speichern. + +### [HTML in C# zippen – Tutorial zum benutzerdefinierten Ressourcen‑Handler](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML‑Inhalte mithilfe eines benutzerdefinierten Ressourcen‑Handlers in ein ZIP‑Archiv komprimieren. + +### [HTML‑Dokument mit formatiertem Text erstellen und in PDF exportieren – Vollständige Anleitung](./create-html-document-with-styled-text-and-export-to-pdf-full/) +Erfahren Sie, wie Sie ein HTML‑Dokument mit formatiertem Text erstellen und es mit Aspose.HTML für .NET in ein PDF exportieren. ### [PDF aus HTML erstellen – C# Schritt‑für‑Schritt‑Anleitung](./create-pdf-from-html-c-step-by-step-guide/) Erstellen Sie PDF aus HTML mit C# – eine detaillierte Schritt‑für‑Schritt‑Anleitung mit Aspose.HTML für .NET. ### [HTML als ZIP speichern – Komplettes C#‑Tutorial](./save-html-as-zip-complete-c-tutorial/) Erfahren Sie, wie Sie HTML‑Inhalte mit Aspose.HTML für .NET in ein ZIP‑Archiv speichern – vollständige Schritt‑für‑Schritt‑Anleitung in C#. ### [HTML in ZIP speichern in C# – Komplettes In‑Memory‑Beispiel](./save-html-to-zip-in-c-complete-in-memory-example/) -Speichern Sie HTML-Inhalte in ein ZIP-Archiv komplett im Speicher mit Aspose.HTML für .NET. Schritt‑für‑Schritt‑Anleitung. +Speichern Sie HTML‑Inhalte in ein ZIP‑Archiv komplett im Speicher mit Aspose.HTML für .NET. Schritt‑für‑Schritt‑Anleitung. ## Abschluss diff --git a/html/german/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/german/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..492f70f0a --- /dev/null +++ b/html/german/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-02-21 +description: Erfahren Sie, wie Sie HTML mit einem benutzerdefinierten Ressourcen‑Handler + in C# zippen. Dieser Leitfaden behandelt außerdem das Speichern von HTML als Zip, + das Konvertieren von HTML zu Zip und das Speichern von HTML in Zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: de +og_description: Wie man HTML in C# mit einem benutzerdefinierten Ressourcen‑Handler + zippt. Schritt‑für‑Schritt‑Code, Erklärungen und Tipps zum Speichern von HTML als + Zip. +og_title: HTML in C# zippen – Komplettanleitung +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Wie man HTML in C# zippt – Tutorial zum benutzerdefinierten Ressourcen‑Handler +url: /de/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +. + +Let's write. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man HTML in C# zippt – Tutorial zum benutzerdefinierten Resource Handler + +Haben Sie sich jemals gefragt, **wie man HTML** direkt aus Ihrer .NET‑App zippt, ohne das Dateisystem zu berühren? Sie sind nicht allein. Viele Entwickler müssen ein HTML‑Dokument zusammen mit seinen Ressourcen – Bilder, CSS, Skripte – in eine einzige ZIP‑Datei packen, um es einfach zu transportieren oder zu speichern. + +In diesem Tutorial zeigen wir Ihnen einen sauberen Weg, **HTML als ZIP zu speichern** mithilfe von Aspose.HTML’s `ResourceHandler`. Wir gehen auch auf verwandte Themen ein wie **HTML in ZIP konvertieren** und **HTML zu ZIP speichern** mit einem wiederverwendbaren Handler, den Sie in jedes Projekt einbinden können. Keine externen Tools, keine temporären Dateien – nur reiner In‑Memory‑Zauber. + +## Was Sie lernen werden + +* Wie man ein In‑Memory‑`HTMLDocument` erstellt. +* Wie man einen **benutzerdefinierten Resource Handler** implementiert, der jede Ressource in ein einziges ZIP‑Archiv streamt. +* Den genauen Code, der nötig ist, um **HTML als ZIP zu speichern** und das Byte‑Array zu erhalten. +* Tipps zum Umgang mit Sonderfällen wie großen Bildern oder mehreren CSS‑Dateien. +* Ein vollständiges, ausführbares Beispiel, das Sie in Visual Studio kopieren‑und‑einfügen können. + +> **Voraussetzungen** – Sie benötigen .NET 6+ (oder .NET Framework 4.6+) und die Aspose.HTML for .NET‑Bibliothek, installiert via NuGet (`Install-Package Aspose.HTML`). Keine weiteren Abhängigkeiten. + +--- + +## Schritt 1 – Das HTML‑Dokument erstellen (Wie man HTML zippt) + +Das Erste, das wir brauchen, ist eine `HTMLDocument`‑Instanz, die das Markup enthält, das wir komprimieren wollen. Betrachten Sie dies als die Leinwand für den Rest des Prozesses. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Warum das wichtig ist:** Durch die Verwendung von `HTMLDocument` lässt Aspose.HTML das CSS‑Parsing, Layout und die Schriftauflösung genau wie ein Browser erledigen. Das garantiert, dass das PNG, das Sie erhalten, identisch aussieht mit dem, was ein Benutzer in Chrome oder Edge sehen würde. + +## HTML zu Bild konvertieren – Rendering‑Optionen konfigurieren + +Als Nächstes definieren wir, wie die Engine das Markup rasterisieren soll. Hier legen Sie **Bildbreite und -höhe fest**, aktivieren Antialiasing und wählen eine Hintergrundfarbe. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Profi‑Tipp:** Wenn Sie `Width` und `Height` weglassen, verwendet Aspose.HTML die intrinsische Größe der Seite, die für Thumbnails zu klein sein kann. Durch das explizite Festlegen dieser Werte erhalten Sie die volle Kontrolle über die endgültigen PNG‑Abmessungen. + +## PNG aus HTML erzeugen – Schriftstile anwenden (optional) + +Manchmal benötigen Sie fett, kursiv oder eine Kombination von Stilen. Das `WebFontStyle`‑Enum ermöglicht das Zusammenführen von Flags mittels des bitweisen OR‑Operators (`|`). Dieser Schritt ist optional, zeigt aber, wie man **PNG aus HTML erzeugt** mit benutzerdefinierten Stilen. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **Was passiert:** `combinedFontStyle.ToString()` liefert `"Bold, Italic"`, was die Engine in einen gültigen CSS‑`font-style`‑Wert übersetzt. Das Ergebnis ist ein PNG, bei dem der Text sowohl fett als auch kursiv dargestellt wird. + +## HTML als PNG speichern – Der abschließende Rendering‑Aufruf + +Jetzt fügen wir alles zusammen. Der `Image`‑Renderer schreibt den rasterisierten Inhalt in eine Datei auf dem Datenträger. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Das Ausführen des Programms erzeugt `output.png` im Arbeitsverzeichnis. Öffnen Sie es, und Sie sehen das Ergebnis des **render html to png** – scharfer, antialiasierter Text auf einer weißen Leinwand, exakt 800 × 600 Pixel. + + + +> **Erwartete Ausgabe:** Eine PNG‑Datei, die „Sample text“ in 24‑px Arial, fett und kursiv, zentriert im Bild zeigt. Wenn Sie den HTML‑String oder die Werte `Width`/`Height` ändern, wird das PNG entsprechend aktualisiert. + +## HTML zu Bild konvertieren – Häufige Variationen & Sonderfälle + +### 1. Remote‑Webseite rendern + +Wenn Sie **HTML zu Bild konvertieren** von einer Live‑URL benötigen, übergeben Sie einfach die URL an `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Stellen Sie sicher, dass die Zielseite programmatischen Zugriff erlaubt (CORS, Authentifizierung usw.). + +### 2. Transparente Hintergründe + +Setzen Sie `BackColor = Color.Transparent` und wählen Sie ein PNG‑Format, das Alphakanäle unterstützt. Das ist praktisch, um das Bild über anderen UI‑Elementen zu überlagern. + +### 3. Hochauflösende Ausgabe + +Für druckfertige Grafiken erhöhen Sie `Width` und `Height` und setzen zusätzlich `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Umgang mit großen Stylesheets + +Aspose.HTML lädt verknüpfte CSS‑Dateien automatisch herunter. Wenn Sie Netzwerkaufrufe begrenzen möchten, betten Sie kritisches CSS direkt in den HTML‑String ein oder verwenden Sie `ResourceLoadingOptions`, um Ressourcen zu cachen. + +## Vollständiges, ausführbares Beispiel + +Unten finden Sie das komplette Programm, das Sie in eine Konsolenanwendung kopieren‑und‑einfügen können. Es enthält alle Schritte, Kommentare und optionalen Anpassungen, die oben besprochen wurden. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Kompilieren und ausführen (`dotnet run`, wenn Sie die .NET‑CLI verwenden). Die Konsole bestätigt die Dateierstellung, und Sie finden `output.png` neben der ausführbaren Datei. + +## Fazit + +Wir haben gerade alles behandelt, was Sie benötigen, um **HTML zu PNG zu rendern** mit Aspose.HTML in C#. Vom Erstellen des Dokuments, Anpassen der Rendering‑Optionen, Anwenden benutzerdefinierter Schriftstile bis zum endgültigen Speichern des Bildes – jeder Schritt wurde erklärt **warum** er wichtig ist, nicht nur **wie** man ihn tippt. + +Wenn Sie **HTML zu Bild** für andere Formate konvertieren möchten, ändern Sie einfach die Dateierweiterung in `renderer.Save` zu `.jpeg` oder `.bmp` und passen `ImageSaveOptions` entsprechend an. Möchten Sie Dutzende von Seiten stapelweise verarbeiten? Wickeln Sie den Rendering‑Block in eine `foreach`‑Schleife und übergeben Sie jeden HTML‑String oder jede URL. + +### Was kommt als Nächstes? + +- **PDF‑Erstellung erkunden** – Aspose.HTML kann ebenfalls mit ähnlichen Optionen nach PDF exportieren. +- **Mehrere Seiten kombinieren** – Rendern Sie jede Seite eines mehrseitigen HTML‑Dokuments in separate PNGs. +- **Integration mit ASP.NET Core** – Geben Sie das PNG direkt als `FileResult` für Sofort‑Screenshots zurück. + +Fühlen Sie sich frei, mit den Einstellungen zu experimentieren, den HTML‑Inhalt auszutauschen oder diesen Code in einen Web‑Service einzubinden. Der Himmel ist die Grenze, wenn Sie **PNG aus HTML** on‑the‑fly erzeugen können. + +Haben Sie Fragen oder einen kniffligen Anwendungsfall? Hinterlassen Sie unten einen Kommentar, und viel Spaß beim Coden! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/greek/net/html-extensions-and-conversions/_index.md b/html/greek/net/html-extensions-and-conversions/_index.md index 013b0ec4b..c816ff6c5 100644 --- a/html/greek/net/html-extensions-and-conversions/_index.md +++ b/html/greek/net/html-extensions-and-conversions/_index.md @@ -67,6 +67,8 @@ url: /el/net/html-extensions-and-conversions/ Ανακαλύψτε τη δύναμη του Aspose.HTML για .NET: Μετατρέψτε HTML σε XPS χωρίς κόπο. Περιλαμβάνονται προαπαιτούμενα, οδηγός βήμα προς βήμα και συχνές ερωτήσεις. ### [Πώς να συμπιέσετε HTML σε C# – Αποθήκευση HTML σε Zip](./how-to-zip-html-in-c-save-html-to-zip/) Μάθετε πώς να συμπιέσετε αρχεία HTML σε αρχείο ZIP χρησιμοποιώντας το Aspose.HTML για .NET σε C#. +### [Πώς να συμπιέσετε HTML σε C# – Tutorial προσαρμοσμένου διαχειριστή πόρων](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Μάθετε πώς να συμπιέσετε αρχεία HTML σε ZIP χρησιμοποιώντας προσαρμοσμένο διαχειριστή πόρων στο C# με Aspose.HTML. ### [Δημιουργία εγγράφου HTML με μορφοποιημένο κείμενο και εξαγωγή σε PDF – Πλήρης οδηγός](./create-html-document-with-styled-text-and-export-to-pdf-full/) Μάθετε πώς να δημιουργήσετε ένα έγγραφο HTML με μορφοποιημένο κείμενο και να το εξάγετε σε PDF χρησιμοποιώντας το Aspose.HTML για .NET. ### [Αποθήκευση HTML ως ZIP – Πλήρης Εκπαιδευτικό C#](./save-html-as-zip-complete-c-tutorial/) diff --git a/html/greek/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/greek/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..58400e6b3 --- /dev/null +++ b/html/greek/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-02-21 +description: Μάθετε πώς να συμπιέζετε HTML σε zip χρησιμοποιώντας έναν προσαρμοσμένο + διαχειριστή πόρων σε C#. Αυτός ο οδηγός καλύπτει επίσης την αποθήκευση HTML ως zip, + τη μετατροπή HTML σε zip και την αποθήκευση HTML σε zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: el +og_description: Πώς να συμπιέσετε HTML σε C# χρησιμοποιώντας έναν προσαρμοσμένο διαχειριστή + πόρων. Κώδικας βήμα‑βήμα, εξηγήσεις και συμβουλές για την αποθήκευση του HTML ως + zip. +og_title: Πώς να συμπιέσετε HTML σε C# – Πλήρης οδηγός +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Πώς να συμπιέσετε HTML σε C# – Εκπαιδευτικό για προσαρμοσμένο διαχειριστή πόρων +url: /el/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να Συμπιέσετε HTML σε ZIP με C# – Tutorial Προσαρμοσμένου Διαχειριστή Πόρων + +Έχετε σκεφτεί ποτέ **πώς να συμπιέσετε HTML** απευθείας από την εφαρμογή .NET χωρίς να αγγίξετε το σύστημα αρχείων; Δεν είστε μόνοι. Πολλοί προγραμματιστές χρειάζονται να συσκευάσουν ένα έγγραφο HTML μαζί με τους πόρους του — εικόνες, CSS, scripts — σε ένα ενιαίο αρχείο ZIP για εύκολη μεταφορά ή αποθήκευση. + +Σε αυτό το tutorial θα σας δείξουμε έναν καθαρό τρόπο για **αποθήκευση HTML ως zip** χρησιμοποιώντας το `ResourceHandler` του Aspose.HTML. Θα αγγίξουμε επίσης σχετικές θεματικές όπως **convert HTML to zip** και **save HTML to zip** με έναν επαναχρησιμοποιήσιμο διαχειριστή που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο. Χωρίς εξωτερικά εργαλεία, χωρίς προσωρινά αρχεία — μόνο καθαρή μνήμη. + +## Τι Θα Μάθετε + +* Πώς να δημιουργήσετε ένα `HTMLDocument` στη μνήμη. +* Πώς να υλοποιήσετε έναν **προσαρμοσμένο διαχειριστή πόρων** που ρέει κάθε πόρο σε ένα ενιαίο αρχείο ZIP. +* Τον ακριβή κώδικα που απαιτείται για **αποθήκευση HTML ως zip** και ανάκτηση του byte array. +* Συμβουλές για τη διαχείριση ειδικών περιπτώσεων όπως μεγάλες εικόνες ή πολλαπλά αρχεία CSS. +* Ένα πλήρες, εκτελέσιμο παράδειγμα που μπορείτε να αντιγράψετε‑επικολλήσετε στο Visual Studio. + +> **Προαπαιτούμενα** – Χρειάζεστε .NET 6+ (ή .NET Framework 4.6+) και τη βιβλιοθήκη Aspose.HTML for .NET εγκατεστημένη μέσω NuGet (`Install-Package Aspose.HTML`). Δεν υπάρχουν άλλες εξαρτήσεις. + +--- + +## Βήμα 1 – Δημιουργία του HTML Εγγράφου (How to Zip HTML) + +Το πρώτο που χρειάζεται είναι μια παρουσία `HTMLDocument` που να περιέχει το markup που θέλουμε να συμπιέσουμε. Σκεφτείτε το ως το καμβά για το υπόλοιπο της διαδικασίας. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Why this matters:** By using `HTMLDocument` we let Aspose.HTML handle CSS parsing, layout, and font resolution exactly as a browser would. That guarantees the PNG you get looks identical to what a user would see in Chrome or Edge. + +## Convert HTML to Image – Configure Rendering Options + +Στη συνέχεια ορίζουμε πώς η μηχανή πρέπει να rasterize το markup. Εδώ **ορίζετε το πλάτος και το ύψος της εικόνας**, ενεργοποιείτε antialiasing και επιλέγετε χρώμα φόντου. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Pro tip:** If you omit `Width` and `Height`, Aspose.HTML will use the intrinsic size of the page, which may be too small for thumbnails. Explicitly setting these values gives you full control over the final PNG dimensions. + +## Generate PNG from HTML – Apply Font Styles (Optional) + +Μερικές φορές χρειάζεστε έντονη, πλάγια ή συνδυασμό στυλ. Το enum `WebFontStyle` σας επιτρέπει να συγχωνεύετε flags χρησιμοποιώντας τον bitwise OR operator (`|`). Αυτό το βήμα είναι προαιρετικό αλλά δείχνει πώς να **generate PNG from HTML** με προσαρμοσμένο στυλ. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **What’s happening:** `combinedFontStyle.ToString()` returns `"Bold, Italic"` which the engine translates into a valid CSS `font-style` value. The result is a PNG where the text appears both bold and italic. + +## Save HTML as PNG – The Final Rendering Call + +Τώρα ενώνουμε όλα. Ο renderer `Image` γράφει το rasterized περιεχόμενο σε αρχείο στο δίσκο. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Η εκτέλεση του προγράμματος δημιουργεί το `output.png` στον τρέχοντα φάκελο εργασίας. Ανοίξτε το και θα δείτε το **render html to png** αποτέλεσμα — καθαρό, antialiased κείμενο σε λευκό καμβά, ακριβώς 800 × 600 pixel. + + + +> **Expected output:** A PNG file showing “Sample text” in 24‑px Arial, bold and italic, centered in the image. If you change the HTML string or the `Width`/`Height` values, the PNG updates accordingly. + +## Convert HTML to Image – Common Variations & Edge Cases + +### 1. Rendering a Remote Web Page + +Αν χρειάζεται να **convert HTML to image** από ζωντανό URL, απλώς περάστε το URL στο `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Βεβαιωθείτε ότι ο στόχος επιτρέπει προγραμματιστική πρόσβαση (CORS, authentication, κλπ.). + +### 2. Transparent Backgrounds + +Ορίστε `BackColor = Color.Transparent` και επιλέξτε μορφή PNG που υποστηρίζει κανάλια άλφα. Αυτό είναι χρήσιμο για επικάλυψη της εικόνας σε άλλα UI στοιχεία. + +### 3. High‑Resolution Output + +Για γραφικά έτοιμα για εκτύπωση, αυξήστε τα `Width` και `Height` ενώ ταυτόχρονα ορίζετε `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Handling Large Stylesheets + +Το Aspose.HTML κατεβάζει αυτόματα τα συνδεδεμένα CSS αρχεία. Αν θέλετε να περιορίσετε τα network calls, ενσωματώστε κρίσιμο CSS απευθείας στο HTML string ή χρησιμοποιήστε το `ResourceLoadingOptions` για caching πόρων. + +## Full, Runnable Example + +Παρακάτω είναι το πλήρες πρόγραμμα που μπορείτε να αντιγράψετε‑και‑επικολλήσετε σε μια εφαρμογή console. Περιλαμβάνει όλα τα βήματα, σχόλια και προαιρετικές ρυθμίσεις που συζητήθηκαν παραπάνω. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Συγκεντρώστε και τρέξτε (`dotnet run` αν χρησιμοποιείτε το .NET CLI). Η κονσόλα θα επιβεβαιώσει τη δημιουργία του αρχείου και θα βρείτε το `output.png` δίπλα στο εκτελέσιμο. + +## Wrap‑Up + +Καλύψαμε όλα όσα χρειάζεστε για να **render HTML to PNG** χρησιμοποιώντας το Aspose.HTML σε C#. Από τη δημιουργία του εγγράφου, τη ρύθμιση επιλογών απόδοσης, την εφαρμογή προσαρμοσμένων στυλ γραμματοσειράς, μέχρι την τελική αποθήκευση της εικόνας — κάθε βήμα εξηγήθηκε **γιατί** είναι σημαντικό, όχι μόνο **πώς** να το πληκτρολογήσετε. + +Αν θέλετε να **convert HTML to image** σε άλλες μορφές, απλώς αλλάξτε την επέκταση αρχείου στο `renderer.Save` σε `.jpeg` ή `.bmp` και προσαρμόστε το `ImageSaveOptions` αναλόγως. Θέλετε να επεξεργαστείτε δεκάδες σελίδες; Τυλίξτε το μπλοκ rendering μέσα σε έναν `foreach` βρόχο και δώστε κάθε HTML string ή URL. + +### What’s Next? + +- **Explore PDF generation** – Aspose.HTML can also export to PDF with similar options. +- **Combine multiple pages** – Render each page of a multi‑page HTML document to separate PNGs. +- **Integrate with ASP.NET Core** – Return the PNG directly as a `FileResult` for on‑the‑fly screenshots. + +Feel free to experiment with the settings, swap out the HTML content, or plug this code into a web service. The sky’s the limit when you can **generate PNG from HTML** on the fly. + +Got questions or a tricky use‑case? Drop a comment below, and happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hindi/net/html-extensions-and-conversions/_index.md b/html/hindi/net/html-extensions-and-conversions/_index.md index 45408d5a1..de51855a0 100644 --- a/html/hindi/net/html-extensions-and-conversions/_index.md +++ b/html/hindi/net/html-extensions-and-conversions/_index.md @@ -30,7 +30,7 @@ HTML एक्सटेंशन डेवलपर्स के लिए ए ## Aspose.HTML के साथ आरंभ करें -क्या आप शुरू करने के लिए तैयार हैं? .NET के लिए Aspose.HTML ट्यूटोरियल शुरुआती और अनुभवी डेवलपर्स दोनों के लिए हैं। चाहे आप HTML एक्सटेंशन और रूपांतरणों के लिए नए हों या उन्नत युक्तियों की तलाश कर रहे हों, हमारे चरण-दर-चरण मार्गदर्शिकाएँ आपकी आवश्यकताओं के अनुरूप डिज़ाइन की गई हैं। +क्या आप शुरू करने के लिए तैयार हैं? .NET के लिए Aspose.HTML ट्यूटोरियल शुरुआती और अनुभवी डेवलपर्स दोनों के लिए हैं। चाहे आप HTML एक्सटेंशन और रूपांतरणों के लिए नए हों या उन्नत युक्तियों की तलाश कर रहे हों, हमारे चरण-दर-स्टेप मार्गदर्शिकाएँ आपकी आवश्यकताओं के अनुरूप डिज़ाइन की गई हैं। ## .NET के लिए Aspose.HTML क्यों? @@ -62,34 +62,38 @@ C# में Aspose.HTML का उपयोग करके HTML को PDF म .NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को GIF में बदलने के लिए चरण-दर-चरण मार्गदर्शिका। पूर्वापेक्षाएँ, कोड उदाहरण, FAQ, और बहुत कुछ! Aspose.HTML के साथ अपने HTML हेरफेर को अनुकूलित करें। ### [Aspose.HTML के साथ .NET में HTML को JPEG में बदलें](./convert-html-to-jpeg/) -.NET के लिए Aspose.HTML के साथ .NET में HTML को JPEG में बदलने का तरीका जानें। .NET के लिए Aspose.HTML की शक्ति का उपयोग करने के लिए चरण-दर-चरण मार्गदर्शिका। अपने वेब डेवलपमेंट कार्यों को आसानी से अनुकूलित करें। +.NET के लिए Aspose.HTML के साथ .NET में HTML को JPEG में बदलने का तरीका जानें। .NET के लिए Aspose.HTML की शक्ति का उपयोग करने के लिए चरण-दर-स्टेप मार्गदर्शिका। अपने वेब डेवलपमेंट कार्यों को आसानी से अनुकूलित करें। ### [Aspose.HTML के साथ .NET में HTML को Markdown में बदलें](./convert-html-to-markdown/) -कुशल सामग्री हेरफेर के लिए Aspose.HTML का उपयोग करके .NET में HTML को Markdown में परिवर्तित करना सीखें। सहज रूपांतरण प्रक्रिया के लिए चरण-दर-चरण मार्गदर्शन प्राप्त करें। +कुशल सामग्री हेरफेर के लिए Aspose.HTML का उपयोग करके .NET में HTML को Markdown में परिवर्तित करना सीखें। सहज रूपांतरण प्रक्रिया के लिए चरण-दर-स्टेप मार्गदर्शन प्राप्त करें। ### [Aspose.HTML के साथ .NET में HTML को MHTML में बदलें](./convert-html-to-mhtml/) -Aspose.HTML के साथ .NET में HTML को MHTML में बदलें - कुशल वेब सामग्री संग्रह के लिए चरण-दर-चरण मार्गदर्शिका। MHTML संग्रह बनाने के लिए .NET के लिए Aspose.HTML का उपयोग करना सीखें। +Aspose.HTML के साथ .NET में HTML को MHTML में बदलें - कुशल वेब सामग्री संग्रह के लिए चरण-दर-स्टेप मार्गदर्शिका। MHTML संग्रह बनाने के लिए .NET के लिए Aspose.HTML का उपयोग करना सीखें। ### [Aspose.HTML के साथ .NET में HTML को PNG में बदलें](./convert-html-to-png/) -जानें कि HTML दस्तावेज़ों में हेरफेर करने और उन्हें परिवर्तित करने के लिए .NET के लिए Aspose.HTML का उपयोग कैसे करें। प्रभावी .NET विकास के लिए चरण-दर-चरण मार्गदर्शिका। +जानें कि HTML दस्तावेज़ों में हेरफेर करने और उन्हें परिवर्तित करने के लिए .NET के लिए Aspose.HTML का उपयोग कैसे करें। प्रभावी .NET विकास के लिए चरण-दर-स्टेप मार्गदर्शिका। ### [Aspose.HTML के साथ .NET में HTML को TIFF में बदलें](./convert-html-to-tiff/) -.NET के लिए Aspose.HTML के साथ HTML को TIFF में कैसे बदलें, यह जानें। कुशल वेब सामग्री अनुकूलन के लिए हमारे चरण-दर-चरण मार्गदर्शिका का पालन करें। +.NET के लिए Aspose.HTML के साथ HTML को TIFF में कैसे बदलें, यह जानें। कुशल वेब सामग्री अनुकूलन के लिए हमारे चरण-दर-स्टेप मार्गदर्शिका का पालन करें। ### [Aspose.HTML के साथ .NET में HTML को XPS में बदलें](./convert-html-to-xps/) -.NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को XPS में आसानी से बदलें। पूर्वापेक्षाएँ, चरण-दर-चरण मार्गदर्शिका और FAQ शामिल हैं। +.NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को XPS में आसानी से बदलें। पूर्वापेक्षाएँ, चरण-दर-स्टेप मार्गदर्शिका और FAQ शामिल हैं। + ### [HTML को ZIP के रूप में सहेजें – पूर्ण C# ट्यूटोरियल](./save-html-as-zip-complete-c-tutorial/) -HTML को ZIP फ़ाइल में सहेजने के चरण-दर-चरण मार्गदर्शन, C# कोड उदाहरण और अनुकूलन विकल्प। +HTML को ZIP फ़ाइल में सहेजने के चरण-दर-स्टेप मार्गदर्शन, C# कोड उदाहरण और अनुकूलन विकल्प। ### [C# में HTML को ज़िप कैसे करें – HTML को ज़िप में सहेजें](./how-to-zip-html-in-c-save-html-to-zip/) .NET के लिए Aspose.HTML का उपयोग करके C# में HTML को ज़िप फ़ाइल में सहेजने का तरीका सीखें। ### [स्टाइल्ड टेक्स्ट के साथ HTML दस्तावेज़ बनाएं और PDF में निर्यात करें – पूर्ण गाइड](./create-html-document-with-styled-text-and-export-to-pdf-full/) Aspose.HTML for .NET का उपयोग करके स्टाइल्ड टेक्ट वाले HTML दस्तावेज़ को बनाएं और उसे PDF में निर्यात करने की पूरी गाइड। -.NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को XPS में आसानी से बदलें। पूर्वापेक्षाएँ, चरण-दर-स्टेप मार्गदर्शिका और FAQ शामिल हैं। + ### [C# में HTML को ZIP में सहेजें – पूर्ण इन‑मेमोरी उदाहरण](./save-html-to-zip-in-c-complete-in-memory-example/) C# में इन‑मेमोरी में HTML को ZIP फ़ाइल में सहेजने का पूरा उदाहरण देखें। +### [C# में HTML को ज़िप कैसे करें – कस्टम रिसोर्स हैंडलर ट्यूटोरियल](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +C# में Aspose.HTML का उपयोग करके कस्टम रिसोर्स हैंडलर के साथ HTML को ZIP फ़ाइल में सहेजने का चरण‑दर‑चरण मार्गदर्शन। + ## निष्कर्ष निष्कर्ष में, HTML एक्सटेंशन और रूपांतरण आधुनिक वेब विकास के आवश्यक तत्व हैं। .NET के लिए Aspose.HTML प्रक्रिया को सरल बनाता है और इसे सभी स्तरों के डेवलपर्स के लिए सुलभ बनाता है। हमारे ट्यूटोरियल का पालन करके, आप एक व्यापक कौशल सेट के साथ एक कुशल वेब डेवलपर बनने के अपने रास्ते पर अच्छी तरह से आगे बढ़ेंगे। diff --git a/html/hindi/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/hindi/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..9efb82e71 --- /dev/null +++ b/html/hindi/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-02-21 +description: C# में एक कस्टम रिसोर्स हैंडलर का उपयोग करके HTML को ज़िप करना सीखें। + यह गाइड HTML को ज़िप के रूप में सहेजना, HTML को ज़िप में बदलना, और HTML को ज़िप + में सहेजना भी कवर करता है। +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: hi +og_description: कैसे कस्टम रिसोर्स हैंडलर का उपयोग करके C# में HTML को ज़िप करें। + चरण‑दर‑चरण कोड, व्याख्याएँ, और HTML को ज़िप के रूप में सहेजने के टिप्स। +og_title: C# में HTML को ज़िप कैसे करें – पूर्ण गाइड +tags: +- Aspose.HTML +- C# +- ZIP compression +title: C# में HTML को ज़िप कैसे करें – कस्टम रिसोर्स हैंडलर ट्यूटोरियल +url: /hi/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में HTML को ज़िप कैसे करें – कस्टम रिसोर्स हैंडलर ट्यूटोरियल + +क्या आपने कभी **HTML को सीधे .NET एप्लिकेशन से ज़िप** करने के बारे में सोचा है बिना फ़ाइल सिस्टम को छुए? आप अकेले नहीं हैं। कई डेवलपर्स को HTML दस्तावेज़ को उसकी सभी रिसोर्सेज—इमेजेज, CSS, स्क्रिप्ट्स—के साथ एक ही ZIP फ़ाइल में पैकेज करने की जरूरत पड़ती है, ताकि उसे आसानी से ट्रांसपोर्ट या स्टोर किया जा सके। + +इस ट्यूटोरियल में हम दिखाएंगे कि **Aspose.HTML के `ResourceHandler`** का उपयोग करके **HTML को ज़िप के रूप में सेव** कैसे किया जाए। हम **HTML को ज़िप में कनवर्ट** और **HTML को ज़िप में सेव** जैसे संबंधित विषयों को भी छुएँगे, एक रियूज़ेबल हैंडलर के साथ जिसे आप किसी भी प्रोजेक्ट में डाल सकते हैं। कोई बाहरी टूल नहीं, कोई टेम्पररी फ़ाइल नहीं—सिर्फ शुद्ध इन‑मेमोरी मैजिक। + +## आप क्या सीखेंगे + +* इन‑मेमोरी `HTMLDocument` कैसे बनाएं। +* **कस्टम रिसोर्स हैंडलर** को कैसे इम्प्लीमेंट करें जो हर रिसोर्स को एक ही ZIP आर्काइव में स्ट्रीम करे। +* **HTML को ज़िप के रूप में सेव** करने और बाइट एरे प्राप्त करने के लिए आवश्यक सटीक कोड। +* बड़े इमेजेज या कई CSS फ़ाइलों जैसे एज केस को हैंडल करने के टिप्स। +* एक पूरा, रन करने योग्य उदाहरण जिसे आप Visual Studio में कॉपी‑पेस्ट कर सकते हैं। + +> **Prerequisites** – आपको .NET 6+ (या .NET Framework 4.6+) और Aspose.HTML for .NET लाइब्रेरी चाहिए, जिसे NuGet (`Install-Package Aspose.HTML`) से इंस्टॉल किया जा सकता है। अन्य कोई डिपेंडेंसी नहीं। + +--- + +## Step 1 – Create the HTML Document (How to Zip HTML) + +सबसे पहले हमें एक `HTMLDocument` इंस्टेंस चाहिए जो उस मार्कअप को रखेगा जिसे हम कंप्रेस करना चाहते हैं। इसे बाकी प्रोसेस के लिए कैनवास समझें। + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Why this matters:** `HTMLDocument` का उपयोग करके हम Aspose.HTML को CSS पार्सिंग, लेआउट, और फ़ॉन्ट रिज़ॉल्यूशन को ठीक उसी तरह संभालने देते हैं जैसा एक ब्राउज़र करता है। इससे यह सुनिश्चित होता है कि प्राप्त PNG Chrome या Edge में उपयोगकर्ता को दिखने वाले परिणाम के समान दिखे। + +## HTML को इमेज में बदलें – रेंडरिंग विकल्प कॉन्फ़िगर करें + +अब हम परिभाषित करते हैं कि इंजन को मार्कअप को कैसे रास्टराइज़ करना चाहिए। यहाँ आप **image width height सेट** करते हैं, एंटीएलियासिंग सक्षम करते हैं, और बैकग्राउंड कलर चुनते हैं। + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Pro tip:** यदि आप `Width` और `Height` को छोड़ देते हैं, तो Aspose.HTML पेज का अंतर्निहित आकार उपयोग करेगा, जो थंबनेल के लिए बहुत छोटा हो सकता है। इन मानों को स्पष्ट रूप से सेट करने से आपको अंतिम PNG आयामों पर पूर्ण नियंत्रण मिलता है। + +## HTML से PNG जेनरेट करें – फ़ॉन्ट स्टाइल लागू करें (वैकल्पिक) + +कभी‑कभी आपको बोल्ड, इटैलिक, या स्टाइल्स का संयोजन चाहिए होता है। `WebFontStyle` एन्नुम आपको बिटवाइज़ OR ऑपरेटर (`|`) का उपयोग करके फ़्लैग्स को मर्ज करने देता है। यह चरण वैकल्पिक है लेकिन यह दर्शाता है कि कैसे **generate PNG from HTML** को कस्टम स्टाइलिंग के साथ किया जाता है। + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **What’s happening:** `combinedFontStyle.ToString()` `"Bold, Italic"` लौटाता है जिसे इंजन वैध CSS `font-style` वैल्यू में बदल देता है। परिणामस्वरूप एक PNG मिलता है जहाँ टेक्स्ट दोनों ही बोल्ड और इटैलिक दिखता है। + +## HTML को PNG के रूप में सेव करें – अंतिम रेंडरिंग कॉल + +अब हम सब कुछ एक साथ जोड़ते हैं। `Image` रेंडरर रास्टराइज़्ड कंटेंट को डिस्क पर फ़ाइल में लिखता है। + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +प्रोग्राम चलाने से `output.png` वर्किंग डायरेक्टरी में बनता है। इसे खोलें, और आप **render html to png** परिणाम देखेंगे – सफ़ेद कैनवास पर स्पष्ट, एंटीएलियास्ड टेक्स्ट, बिल्कुल 800 × 600 पिक्सेल। + + + +> **Expected output:** एक PNG फ़ाइल जो “Sample text” को 24‑px Arial, बोल्ड और इटैलिक में, इमेज के केंद्र में दिखाती है। यदि आप HTML स्ट्रिंग या `Width`/`Height` मान बदलते हैं, तो PNG उसी अनुसार अपडेट हो जाता है। + +## HTML को इमेज में बदलें – सामान्य विविधताएँ और किनारे के मामले + +### 1. रिमोट वेब पेज रेंडर करना + +यदि आपको लाइव URL से **convert HTML to image** करना है, तो बस URL को `HTMLDocument` में पास करें: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +सुनिश्चित करें कि लक्ष्य साइट प्रोग्रामेटिक एक्सेस की अनुमति देती है (CORS, ऑथेंटिकेशन, आदि)। + +### 2. ट्रांसपेरेंट बैकग्राउंड + +`BackColor = Color.Transparent` सेट करें और ऐसा PNG फ़ॉर्मेट चुनें जो अल्फा चैनल को सपोर्ट करता हो। यह इमेज को अन्य UI एलिमेंट्स पर ओवरले करने के लिए उपयोगी है। + +### 3. हाई‑रेज़ोल्यूशन आउटपुट + +प्रिंट‑रेडी ग्राफ़िक्स के लिए, `Width` और `Height` बढ़ाएँ और साथ ही `DPI` सेट करें: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. बड़े स्टाइलशीट्स को संभालना + +Aspose.HTML स्वचालित रूप से लिंक्ड CSS फ़ाइलें डाउनलोड करता है। यदि आप नेटवर्क कॉल्स को सीमित करना चाहते हैं, तो क्रिटिकल CSS को सीधे HTML स्ट्रिंग में एम्बेड करें या `ResourceLoadingOptions` का उपयोग करके रिसोर्सेज़ को कैश करें। + +## पूर्ण, चलाने योग्य उदाहरण + +नीचे पूरा प्रोग्राम दिया गया है जिसे आप कॉपी‑पेस्ट करके एक कंसोल एप्लिकेशन में उपयोग कर सकते हैं। इसमें ऊपर चर्चा किए गए सभी चरण, कमेंट्स, और वैकल्पिक ट्यूनिंग शामिल हैं। + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +कम्पाइल और रन करें (`dotnet run` यदि आप .NET CLI का उपयोग कर रहे हैं)। कंसोल फ़ाइल निर्माण की पुष्टि करेगा, और आप `output.png` को एक्सीक्यूटेबल के बगल में पाएँगे। + +## समापन + +हमने अभी-अभी वह सब कवर किया है जो आपको C# में Aspose.HTML का उपयोग करके **render HTML to PNG** करने के लिए चाहिए। दस्तावेज़ बनाना, रेंडरिंग विकल्प ट्यून करना, कस्टम फ़ॉन्ट स्टाइल लागू करना, और अंत में इमेज सेव करना—हर चरण को **why** समझाते हुए बताया गया, न कि सिर्फ **how** टाइप करना। + +यदि आप अन्य फ़ॉर्मेट्स के लिए **convert HTML to image** करना चाहते हैं, तो बस `renderer.Save` में फ़ाइल एक्सटेंशन को `.jpeg` या `.bmp` में बदलें और `ImageSaveOptions` को उसी अनुसार समायोजित करें। दर्जनों पेज़ को बैच‑प्रोसेस करना चाहते हैं? रेंडरिंग ब्लॉक को `foreach` लूप में रैप करें और प्रत्येक HTML स्ट्रिंग या URL को फीड करें। + +### आगे क्या? + +- **Explore PDF generation** – Aspose.HTML समान विकल्पों के साथ PDF में भी एक्सपोर्ट कर सकता है। +- **Combine multiple pages** – मल्टी‑पेज HTML डॉक्यूमेंट के प्रत्येक पेज को अलग‑अलग PNG में रेंडर करें। +- **Integrate with ASP.NET Core** – PNG को सीधे `FileResult` के रूप में रिटर्न करें ताकि ऑन‑द‑फ़्लाई स्क्रीनशॉट मिल सके। + +सेटिंग्स के साथ प्रयोग करने, HTML कंटेंट बदलने, या इस कोड को वेब सर्विस में प्लग करने में संकोच न करें। जब आप ऑन‑द‑फ़्लाई **generate PNG from HTML** कर सकते हैं तो संभावनाएँ असीमित हैं। + +कोई प्रश्न या जटिल उपयोग‑केस है? नीचे कमेंट करें, और हैप्पी कोडिंग! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hongkong/net/html-extensions-and-conversions/_index.md b/html/hongkong/net/html-extensions-and-conversions/_index.md index 3d146ada2..31a2ec280 100644 --- a/html/hongkong/net/html-extensions-and-conversions/_index.md +++ b/html/hongkong/net/html-extensions-and-conversions/_index.md @@ -67,6 +67,12 @@ Aspose.HTML for .NET 不只是一個函式庫;它還是一個函式庫。它 探索 Aspose.HTML for .NET 的強大功能:輕鬆將 HTML 轉換為 XPS。包括先決條件、逐步指南和常見問題。 ### [如何在 C# 中壓縮 HTML – 將 HTML 保存為 Zip](./how-to-zip-html-in-c-save-html-to-zip/) 了解如何使用 Aspose.HTML for .NET 在 C# 中將 HTML 壓縮為 Zip 檔案,並保存以便分發。 +### [使用 Aspose.HTML 將 HTML 儲存為 ZIP – 完整 C# 教學](./save-html-as-zip-complete-c-tutorial/) +使用 Aspose.HTML for .NET 將 HTML 文件壓縮為 ZIP 檔案,提供完整的 C# 範例與步驟說明。 +### [在 C# 中將 HTML 儲存為 ZIP – 完整的記憶體內示例](./save-html-to-zip-in-c-complete-in-memory-example/) +示範如何在 C# 中使用 Aspose.HTML 將 HTML 內容直接壓縮成 ZIP 檔案,全部在記憶體中完成。 +### [在 C# 中使用自訂資源處理程式將 HTML 壓縮為 ZIP – 完整教學](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +示範如何在 C# 中使用自訂資源處理程式將 HTML 壓縮為 ZIP,提供完整步驟與範例。 ### [建立具樣式文字的 HTML 文件並匯出為 PDF – 完整指南](./create-html-document-with-styled-text-and-export-to-pdf-full/) 使用 Aspose.HTML for .NET 建立帶樣式文字的 HTML 文件,並將其匯出為 PDF 的完整步驟指南。 ### [使用 Aspose.HTML 將 HTML 儲存為 ZIP – 完整 C# 教學](./save-html-as-zip-complete-c-tutorial/) diff --git a/html/hongkong/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/hongkong/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..5e2ff5884 --- /dev/null +++ b/html/hongkong/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-02-21 +description: 學習如何在 C# 中使用自訂資源處理程式將 HTML 壓縮為 zip。本指南亦涵蓋將 HTML 儲存為 zip、將 HTML 轉換為 zip,以及將 + HTML 儲存為 zip。 +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: zh-hant +og_description: 如何在 C# 中使用自訂資源處理程式將 HTML 壓縮為 zip。一步一步的程式碼、說明與保存 HTML 為 zip 的技巧。 +og_title: 如何在 C# 中壓縮 HTML – 完整指南 +tags: +- Aspose.HTML +- C# +- ZIP compression +title: 如何在 C# 中壓縮 HTML – 自訂資源處理程式教學 +url: /zh-hant/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 C# 中壓縮 HTML 為 ZIP – 自訂資源處理程式教學 + +有沒有想過 **如何直接在 .NET 應用程式中壓縮 HTML** 而不觸碰檔案系統?你並不孤單。許多開發者需要將 HTML 文件與其資源——圖片、CSS、腳本——打包成單一 ZIP 檔,以便輕鬆傳輸或儲存。 + +在本教學中,我們將示範使用 Aspose.HTML 的 `ResourceHandler` 以 **save HTML as zip** 的乾淨方式。亦會提及 **convert HTML to zip** 與 **save HTML to zip** 等相關主題,提供一個可重用的處理程式,讓你可直接放入任何專案。無需外部工具、無需暫存檔——全程在記憶體中完成。 + +## 你將學會 + +* 如何建立一個在記憶體中的 `HTMLDocument`。 +* 如何實作 **custom resource handler**,將每個資源串流至同一個 ZIP 壓縮檔。 +* 完整的程式碼,說明 **save HTML as zip** 並取得位元組陣列的方法。 +* 處理大型圖片或多個 CSS 檔等邊緣情況的技巧。 +* 一個可直接複製貼上至 Visual Studio 的完整可執行範例。 + +> **Prerequisites** – 需要 .NET 6+(或 .NET Framework 4.6+)以及透過 NuGet 安裝的 Aspose.HTML for .NET 套件 (`Install-Package Aspose.HTML`)。除此之外無其他相依性。 + +--- + +## Step 1 – Create the HTML Document (How to Zip HTML) + +首先,我們需要一個 `HTMLDocument` 實例來保存欲壓縮的標記。把它想像成後續流程的畫布。 + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **為什麼這很重要:** 使用 `HTMLDocument` 後,Aspose.HTML 會像瀏覽器一樣處理 CSS 解析、版面配置與字型解析。這保證了產出的 PNG 與使用 Chrome 或 Edge 時看到的畫面完全相同。 + +## Convert HTML to Image – 設定渲染選項 + +接著,我們定義引擎如何 rasterize 標記。這裡可以 **設定影像寬度與高度**、啟用抗鋸齒,並選擇背景顏色。 + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **小技巧:** 若省略 `Width` 與 `Height`,Aspose.HTML 會使用頁面的內在尺寸,可能會太小而不適合作為縮圖。明確設定這兩個值即可完整掌控最終 PNG 的尺寸。 + +## Generate PNG from HTML – 套用字型樣式(可選) + +有時你需要粗體、斜體或兩者同時使用。`WebFontStyle` 列舉允許使用位元 OR 運算子 (`|`) 合併旗標。此步驟為可選,但可示範如何 **從 HTML 產生 PNG** 並自訂樣式。 + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **發生了什麼事:** `combinedFontStyle.ToString()` 會回傳 `"Bold, Italic"`,引擎會將其轉換為有效的 CSS `font-style` 值。最終產出的 PNG 文字同時呈現粗體與斜體。 + +## Save HTML as PNG – 最終渲染呼叫 + +現在把所有步驟串起來。`Image` 渲染器會把 rasterized 內容寫入磁碟檔案。 + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +執行程式後,會在工作目錄產生 `output.png`。開啟它,你會看到 **render html to png** 的結果——文字清晰、抗鋸齒,白色畫布,尺寸正好為 800 × 600 像素。 + + + +> **預期輸出:** 一個 PNG 檔案,顯示「Sample text」字樣,使用 24 px Arial、粗體與斜體,置中於影像內。若更改 HTML 字串或 `Width`/`Height`,PNG 會相應更新。 + +## Convert HTML to Image – 常見變形與例外情況 + +### 1. 渲染遠端網頁 + +若要 **將 HTML 轉換為影像**,來源是線上 URL,只需把 URL 傳給 `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +請確保目標網站允許程式化存取(CORS、驗證等)。 + +### 2. 透明背景 + +將 `BackColor = Color.Transparent`,並選擇支援 alpha 通道的 PNG 格式。這在要把影像疊加到其他 UI 元素上時非常實用。 + +### 3. 高解析度輸出 + +若需列印品質的圖形,可同時提升 `Width`、`Height`,並設定 `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. 處理大型樣式表 + +Aspose.HTML 會自動下載連結的 CSS 檔案。若想減少網路請求,可直接在 HTML 字串中嵌入關鍵 CSS,或使用 `ResourceLoadingOptions` 進行資源快取。 + +## 完整可執行範例 + +以下程式碼可直接貼到 Console 應用程式中。它包含前述所有步驟、註解與可選調整。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +編譯並執行(若使用 .NET CLI,執行 `dotnet run`)。主控台會顯示檔案建立成功訊息,`output.png` 會出現在執行檔旁邊。 + +## 總結 + +我們已完整說明如何使用 Aspose.HTML 在 C# 中 **將 HTML 渲染為 PNG**。從建立文件、調整渲染選項、套用自訂字型樣式,到最終儲存影像——每一步都說明了 **為什麼** 這麼做,而不只是 **怎麼寫**。 + +若想 **將 HTML 轉換為其他影像格式**,只需把 `renderer.Save` 的副檔名改成 `.jpeg` 或 `.bmp`,並相應調整 `ImageSaveOptions`。需要批次處理多頁?將渲染區塊包在 `foreach` 迴圈中,逐一傳入 HTML 字串或 URL 即可。 + +### 接下來可以做什麼? + +- **探索 PDF 產生** – Aspose.HTML 也能以類似方式匯出 PDF。 +- **合併多頁** – 把多頁 HTML 文件的每一頁分別渲染成 PNG。 +- **整合至 ASP.NET Core** – 直接以 `FileResult` 回傳 PNG,實現即時截圖。 + +歡迎自行嘗試不同設定、替換 HTML 內容,或將此程式碼嵌入 Web 服務。只要能 **即時從 HTML 產生 PNG**,創意無限。 + +有任何問題或特殊需求嗎?在下方留言,我們一起討論,祝開發順利! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hungarian/net/html-extensions-and-conversions/_index.md b/html/hungarian/net/html-extensions-and-conversions/_index.md index 53dd8b575..1bf87ae4b 100644 --- a/html/hungarian/net/html-extensions-and-conversions/_index.md +++ b/html/hungarian/net/html-extensions-and-conversions/_index.md @@ -60,6 +60,8 @@ Ismerje meg, hogyan hozhat létre PDF-et HTML-ből C#‑ban az Aspose.HTML for . ### [HTML mentése ZIP-ként – Teljes C# oktatóanyag](./save-html-as-zip-complete-c-tutorial/) ### [HTML mentése ZIP-be C#‑ban – Teljes memória‑beli példa](./save-html-to-zip-in-c-complete-in-memory-example/) Mentse a HTML-t közvetlenül memóriában ZIP-archívumba az Aspose.HTML for .NET C#‑ban. +### [HTML zip-elése C#-ban – Egyéni erőforráskezelő oktatóanyag](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Ismerje meg, hogyan használhat egyéni erőforráskezelőt a HTML zip-eléséhez C#-ban az Aspose.HTML for .NET segítségével. ## Következtetés diff --git a/html/hungarian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/hungarian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..49598805c --- /dev/null +++ b/html/hungarian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-02-21 +description: Tanulja meg, hogyan lehet HTML-t zip-elt formátumba csomagolni egy egyedi + erőforráskezelő segítségével C#-ban. Ez az útmutató a HTML zip-fájlba mentését, + a HTML zip-re konvertálását és a HTML zip-be mentését is lefedi. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: hu +og_description: Hogyan csomagoljuk ZIP-be a HTML-t C#-ban egy egyedi erőforráskezelő + használatával. Lépésről‑lépésre kód, magyarázatok és tippek a HTML ZIP-be mentéséhez. +og_title: HTML ZIP-elése C#-ban – Teljes útmutató +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Hogyan tömörítsük a HTML-t C#‑ban – Egyedi erőforráskezelő útmutató +url: /hu/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan csomagoljuk ZIP-be a HTML-t C#‑ban – Egyedi erőforráskezelő oktatóanyag + +Gondolkodtál már azon, **hogyan zip‑eljük a HTML‑t** közvetlenül a .NET alkalmazásodból anélkül, hogy a fájlrendszert érintenénk? Nem vagy egyedül. Sok fejlesztőnek kell egy HTML‑dokumentumot a hozzá tartozó erőforrásokkal – képek, CSS, szkriptek – egyetlen ZIP‑fájlba csomagolnia, hogy könnyen szállítható vagy tárolható legyen. + +Ebben az oktatóanyagban bemutatjuk, hogyan **menthetünk HTML‑t ZIP‑ként** az Aspose.HTML `ResourceHandler` segítségével. Rámutatunk a kapcsolódó témákra is, mint a **convert HTML to zip** és a **save HTML to zip**, egy újrahasználható kezelővel, amelyet bármelyik projektbe be lehet illeszteni. Nincs külső eszköz, nincs ideiglenes fájl – csak tiszta memória‑varázslat. + +## Amit megtanulsz + +* Hogyan hozzunk létre egy memória‑alapú `HTMLDocument`‑ot. +* Hogyan valósítsunk meg egy **egyedi erőforráskezelőt**, amely minden erőforrást egy ZIP‑archívumba stream‑el. +* A pontos kód, amely **HTML‑t ZIP‑ként ment**, és visszaadja a byte‑tömböt. +* Tippek a szélsőséges esetek kezeléséhez, például nagy képek vagy több CSS‑fájl esetén. +* Egy teljes, futtatható példa, amelyet egyszerűen beilleszthetsz a Visual Studio‑ba. + +> **Előfeltételek** – Szükséged van .NET 6+ (vagy .NET Framework 4.6+) környezetre, valamint az Aspose.HTML for .NET könyvtárra, amelyet a NuGet‑en keresztül telepíthetsz (`Install-Package Aspose.HTML`). Egyéb függőség nincs. + +--- + +## 1. lépés – HTML dokumentum létrehozása (How to Zip HTML) + +Az első dolog, amire szükségünk van, egy `HTMLDocument` példány, amely a tömöríteni kívánt markup‑ot tartalmazza. Tekintsd ezt a folyamat vásznának. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Why this matters:** By using `HTMLDocument` we let Aspose.HTML handle CSS parsing, layout, and font resolution exactly as a browser would. That guarantees the PNG you get looks identical to what a user would see in Chrome or Edge. + +## Convert HTML to Image – Configure Rendering Options + +Ezután definiáljuk, hogyan rasterizálja a motor a markup‑ot. Itt **állítod be a kép szélességét és magasságát**, engedélyezed az antialiasing‑et, és kiválasztod a háttérszínt. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Pro tip:** If you omit `Width` and `Height`, Aspose.HTML will use the intrinsic size of the page, which may be too small for thumbnails. Explicitly setting these values gives you full control over the final PNG dimensions. + +## Generate PNG from HTML – Apply Font Styles (Optional) + +Néha szükség van félkövér, dőlt vagy kombinált stílusokra. A `WebFontStyle` enum lehetővé teszi, hogy a bitwise OR operátorral (`|`) egyesítsd a flag‑eket. Ez a lépés opcionális, de bemutatja, hogyan **generate PNG from HTML** egyedi stílusokkal. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **What’s happening:** `combinedFontStyle.ToString()` returns `"Bold, Italic"` which the engine translates into a valid CSS `font-style` value. The result is a PNG where the text appears both bold and italic. + +## Save HTML as PNG – The Final Rendering Call + +Most összekötjük a részeket. Az `Image` renderer a rasterizált tartalmat egy fájlba írja a lemezen. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +A program futtatása létrehozza az `output.png` fájlt a munkakönyvtárban. Nyisd meg, és láthatod a **render html to png** eredményt – éles, antialiaselt szöveg fehér vásznon, pontosan 800 × 600 pixel méretben. + + + +> **Expected output:** A PNG file showing “Sample text” in 24‑px Arial, bold and italic, centered in the image. If you change the HTML string or the `Width`/`Height` values, the PNG updates accordingly. + +## Convert HTML to Image – Common Variations & Edge Cases + +### 1. Rendering a Remote Web Page + +Ha **convert HTML to image**-t szeretnél egy élő URL‑ről, egyszerűen add át az URL‑t az `HTMLDocument`‑nek: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Győződj meg róla, hogy a céloldal engedélyezi a programozott hozzáférést (CORS, hitelesítés, stb.). + +### 2. Transparent Backgrounds + +Állítsd be a `BackColor = Color.Transparent` értéket, és válassz olyan PNG formátumot, amely támogatja az alfa csatornát. Ez hasznos, ha a képet más UI elemekre szeretnéd átfedni. + +### 3. High‑Resolution Output + +Nyomtatásra kész grafikához növeld a `Width` és `Height` értékeket, valamint állítsd be a `DPI`‑t: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Handling Large Stylesheets + +Az Aspose.HTML automatikusan letölti a hivatkozott CSS fájlokat. Ha korlátozni szeretnéd a hálózati hívásokat, ágyazd be a kritikus CSS‑t közvetlenül a HTML string‑be, vagy használd a `ResourceLoadingOptions`‑t az erőforrások gyorsítótárazásához. + +## Full, Runnable Example + +Az alábbiakban a teljes programot találod, amelyet egyszerűen másolj be egy konzolalkalmazásba. Tartalmazza az összes lépést, megjegyzést és a fent tárgyalt opcionális finomításokat. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Fordítsd le és futtasd (`dotnet run`, ha a .NET CLI‑t használod). A konzol megerősíti a fájl létrehozását, és az `output.png` a futtatható fájl mellett fog megjelenni. + +## Wrap‑Up + +Most már mindent tudsz, hogyan **render HTML to PNG** Aspose.HTML‑el C#‑ban. A dokumentum létrehozásától, a renderelési beállítások finomításán, az egyedi betűstílusok alkalmazásán át a kép mentéséig – minden lépést elmagyaráztunk, **miért** fontos, nem csak **hogyan** kell beírni. + +Ha más formátumokra is **convert HTML to image**-t szeretnél, egyszerűen változtasd meg a `renderer.Save` fájlkiterjesztését `.jpeg` vagy `.bmp`‑re, és állítsd be az `ImageSaveOptions`‑t ennek megfelelően. Több tucat oldalt szeretnél kötegelt feldolgozni? Csomagold a renderelési blokkot egy `foreach` ciklusba, és add át minden HTML string‑et vagy URL‑t. + +### What’s Next? + +- **Explore PDF generation** – Aspose.HTML can also export to PDF with similar options. +- **Combine multiple pages** – Render each page of a multi‑page HTML document to separate PNGs. +- **Integrate with ASP.NET Core** – Return the PNG directly as a `FileResult` for on‑the‑fly screenshots. + +Nyugodtan kísérletezz a beállításokkal, cseréld le az HTML tartalmat, vagy illeszd be a kódot egy webszolgáltatásba. A lehetőségek határtalanok, ha **generate PNG from HTML**‑t tudsz futás közben előállítani. + +Van kérdésed vagy bonyolult felhasználási eseted? Írj egy megjegyzést alább, és jó kódolást! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/indonesian/net/html-extensions-and-conversions/_index.md b/html/indonesian/net/html-extensions-and-conversions/_index.md index 6ac5368ff..1a910543b 100644 --- a/html/indonesian/net/html-extensions-and-conversions/_index.md +++ b/html/indonesian/net/html-extensions-and-conversions/_index.md @@ -67,6 +67,8 @@ Pelajari cara mengonversi HTML ke TIFF dengan Aspose.HTML untuk .NET. Ikuti pand Temukan kekuatan Aspose.HTML untuk .NET: Ubah HTML menjadi XPS dengan mudah. Prasyarat, panduan langkah demi langkah, dan Tanya Jawab Umum disertakan. ### [Cara Mengompres HTML menjadi Zip di C# – Simpan HTML ke Zip](./how-to-zip-html-in-c-save-html-to-zip/) Pelajari cara mengompres file HTML menjadi arsip ZIP menggunakan C# dan Aspose.HTML. +### [Cara Mengompres HTML menjadi Zip di C# – Tutorial Penangan Sumber Daya Kustom](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Pelajari cara mengompres HTML menjadi ZIP dengan menggunakan Custom Resource Handler di C#. ### [Buat Dokumen HTML dengan Teks Bergaya dan Ekspor ke PDF – Panduan Lengkap](./create-html-document-with-styled-text-and-export-to-pdf-full/) Pelajari cara membuat dokumen HTML dengan teks berformat dan mengekspornya ke PDF menggunakan Aspose.HTML untuk .NET. ### [Simpan HTML sebagai ZIP – Tutorial Lengkap C#](./save-html-as-zip-complete-c-tutorial/) diff --git a/html/indonesian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/indonesian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..e139186d2 --- /dev/null +++ b/html/indonesian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,250 @@ +--- +category: general +date: 2026-02-21 +description: Pelajari cara mengompres HTML menjadi zip menggunakan penangan sumber + daya khusus di C#. Panduan ini juga mencakup menyimpan HTML sebagai zip, mengonversi + HTML ke zip, dan menyimpan HTML ke zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: id +og_description: Cara meng‑zip HTML di C# menggunakan handler sumber daya khusus. Kode + langkah demi langkah, penjelasan, dan tips untuk menyimpan HTML sebagai zip. +og_title: Cara Mengezip HTML di C# – Panduan Lengkap +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Cara Meng-zip HTML di C# – Tutorial Penangan Sumber Daya Kustom +url: /id/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +. + +Make sure not to translate code inside code blocks (they are placeholders). So only translate surrounding text. + +Also keep markdown links unchanged (none present except maybe none). There is a link? No. + +Now produce final translation. + +Let's craft. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara Mengompres HTML menjadi ZIP di C# – Tutorial Penangan Sumber Daya Kustom + +Pernah bertanya-tanya **bagaimana cara mengompres HTML** langsung dari aplikasi .NET Anda tanpa menyentuh sistem file? Anda tidak sendirian. Banyak pengembang perlu mengemas dokumen HTML bersama dengan sumber dayanya—gambar, CSS, skrip—ke dalam satu file ZIP untuk transportasi atau penyimpanan yang mudah. + +Dalam tutorial ini kami akan menunjukkan cara bersih untuk **menyimpan HTML sebagai zip** menggunakan `ResourceHandler` dari Aspose.HTML. Kami juga akan menyentuh topik terkait seperti **convert HTML to zip** dan **save HTML to zip** dengan penangan yang dapat digunakan kembali dan dapat Anda sisipkan ke proyek mana pun. Tanpa alat eksternal, tanpa file sementara—hanya sihir murni dalam memori. + +## Apa yang Akan Anda Pelajari + +* Cara membuat `HTMLDocument` dalam memori. +* Cara mengimplementasikan **custom resource handler** yang menyalurkan setiap sumber daya ke dalam satu arsip ZIP. +* Kode tepat yang diperlukan untuk **save HTML as zip** dan mengambil array byte. +* Tips menangani kasus tepi seperti gambar besar atau banyak file CSS. +* Contoh lengkap yang dapat dijalankan dan Anda dapat menyalin‑tempel ke Visual Studio. + +> **Prasyarat** – Anda memerlukan .NET 6+ (atau .NET Framework 4.6+) dan perpustakaan Aspose.HTML untuk .NET yang diinstal melalui NuGet (`Install-Package Aspose.HTML`). Tidak ada dependensi lain. + +--- + +## Langkah 1 – Buat Dokumen HTML (How to Zip HTML) + +Hal pertama yang kita butuhkan adalah instance `HTMLDocument` yang memuat markup yang ingin kita kompres. Anggap ini sebagai kanvas untuk seluruh proses selanjutnya. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Mengapa ini penting:** Dengan menggunakan `HTMLDocument` kita membiarkan Aspose.HTML menangani parsing CSS, layout, dan resolusi font persis seperti browser. Itu menjamin PNG yang dihasilkan terlihat identik dengan apa yang dilihat pengguna di Chrome atau Edge. + +## Konversi HTML ke Gambar – Atur Opsi Rendering + +Selanjutnya kita menentukan bagaimana mesin harus meraster markup. Di sinilah Anda **mengatur lebar tinggi gambar**, mengaktifkan antialiasing, dan memilih warna latar belakang. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Tips pro:** Jika Anda tidak menyertakan `Width` dan `Height`, Aspose.HTML akan menggunakan ukuran intrinsik halaman, yang mungkin terlalu kecil untuk thumbnail. Menetapkan nilai ini secara eksplisit memberi Anda kontrol penuh atas dimensi PNG akhir. + +## Buat PNG dari HTML – Terapkan Gaya Font (Opsional) + +Kadang‑kadang Anda memerlukan teks tebal, miring, atau kombinasi keduanya. Enum `WebFontStyle` memungkinkan Anda menggabungkan flag menggunakan operator bitwise OR (`|`). Langkah ini opsional tetapi memperlihatkan cara **menghasilkan PNG dari HTML** dengan gaya khusus. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **Apa yang terjadi:** `combinedFontStyle.ToString()` mengembalikan `"Bold, Italic"` yang kemudian diterjemahkan mesin menjadi nilai CSS `font-style` yang valid. Hasilnya adalah PNG di mana teks muncul sekaligus tebal dan miring. + +## Simpan HTML sebagai PNG – Panggilan Rendering Akhir + +Sekarang kita menggabungkan semuanya. Renderer `Image` menulis konten yang telah diraster ke file di disk. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Menjalankan program akan membuat `output.png` di direktori kerja. Buka file tersebut, dan Anda akan melihat hasil **render html ke png** – teks tajam, antialias, pada kanvas putih, berukuran tepat 800 × 600 piksel. + + + +> **Output yang diharapkan:** File PNG yang menampilkan “Sample text” dengan Arial 24 px, tebal dan miring, terpusat di dalam gambar. Jika Anda mengubah string HTML atau nilai `Width`/`Height`, PNG akan diperbarui sesuai. + +## Konversi HTML ke Gambar – Variasi Umum & Kasus Tepi + +### 1. Merender Halaman Web Jarak Jauh + +Jika Anda perlu **mengonversi HTML ke gambar** dari URL yang aktif, cukup berikan URL tersebut ke `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Pastikan situs target mengizinkan akses programatik (CORS, autentikasi, dll.). + +### 2. Latar Belakang Transparan + +Setel `BackColor = Color.Transparent` dan pilih format PNG yang mendukung kanal alfa. Ini berguna untuk menumpangkan gambar di atas elemen UI lain. + +### 3. Output Resolusi Tinggi + +Untuk grafis siap cetak, tingkatkan `Width` dan `Height` sekaligus mengatur `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Menangani Stylesheet Besar + +Aspose.HTML secara otomatis mengunduh file CSS yang terhubung. Jika Anda ingin membatasi panggilan jaringan, sematkan CSS kritis langsung di string HTML atau gunakan `ResourceLoadingOptions` untuk menyimpan cache sumber daya. + +## Contoh Lengkap yang Dapat Dijalankan + +Berikut adalah program lengkap yang dapat Anda salin‑tempel ke aplikasi konsol. Program ini mencakup semua langkah, komentar, dan penyesuaian opsional yang dibahas di atas. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Kompilasi dan jalankan (`dotnet run` jika Anda menggunakan .NET CLI). Konsol akan mengonfirmasi pembuatan file, dan Anda akan menemukan `output.png` di samping executable. + +## Penutup + +Kami baru saja membahas semua yang Anda perlukan untuk **render HTML ke PNG** menggunakan Aspose.HTML di C#. Dari membuat dokumen, menyesuaikan opsi rendering, menerapkan gaya font khusus, hingga akhirnya menyimpan gambar—setiap langkah dijelaskan **mengapa** penting, bukan sekadar **bagaimana** menuliskannya. + +Jika Anda ingin **mengonversi HTML ke gambar** ke format lain, cukup ubah ekstensi file di `renderer.Save` menjadi `.jpeg` atau `.bmp` dan sesuaikan `ImageSaveOptions` yang bersangkutan. Ingin memproses puluhan halaman sekaligus? Bungkus blok rendering dalam loop `foreach` dan berikan setiap string HTML atau URL. + +### Apa Selanjutnya? + +- **Jelajahi pembuatan PDF** – Aspose.HTML juga dapat mengekspor ke PDF dengan opsi serupa. +- **Gabungkan beberapa halaman** – Render tiap halaman dokumen HTML multi‑halaman ke PNG terpisah. +- **Integrasikan dengan ASP.NET Core** – Kembalikan PNG langsung sebagai `FileResult` untuk screenshot secara real‑time. + +Silakan bereksperimen dengan pengaturan, ganti konten HTML, atau sambungkan kode ini ke layanan web. Langit adalah batasnya ketika Anda dapat **menghasilkan PNG dari HTML** secara dinamis. + +Punya pertanyaan atau kasus penggunaan yang menantang? Tinggalkan komentar di bawah, dan selamat coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/italian/net/html-extensions-and-conversions/_index.md b/html/italian/net/html-extensions-and-conversions/_index.md index fcf4daa30..777136312 100644 --- a/html/italian/net/html-extensions-and-conversions/_index.md +++ b/html/italian/net/html-extensions-and-conversions/_index.md @@ -67,6 +67,8 @@ Scopri come convertire HTML in TIFF con Aspose.HTML per .NET. Segui la nostra gu Scopri la potenza di Aspose.HTML per .NET: converti HTML in XPS senza sforzo. Prerequisiti, guida passo passo e FAQ incluse. ### [Come comprimere HTML in C# – Salva HTML in Zip](./how-to-zip-html-in-c-save-html-to-zip/) Scopri come comprimere un documento HTML in un file ZIP usando Aspose.HTML per .NET in C#. +### [Come comprimere HTML in C# – Tutorial Gestore di Risorse Personalizzato](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Impara a comprimere HTML in un archivio ZIP usando un gestore di risorse personalizzato con Aspose.HTML per .NET in C#. ### [Creare PDF da HTML – Guida passo‑a‑passo C#](./create-pdf-from-html-c-step-by-step-guide/) Crea un PDF da HTML in C# con Aspose.HTML per .NET. Segui la nostra guida passo passo per una conversione semplice ed efficace. ### [Salva HTML come ZIP – Tutorial completo C#](./save-html-as-zip-complete-c-tutorial/) diff --git a/html/italian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/italian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..54454c121 --- /dev/null +++ b/html/italian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,252 @@ +--- +category: general +date: 2026-02-21 +description: Scopri come comprimere HTML in zip utilizzando un gestore di risorse + personalizzato in C#. Questa guida copre anche come salvare HTML come zip, convertire + HTML in zip e salvare HTML in zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: it +og_description: Come comprimere HTML in C# usando un gestore di risorse personalizzato. + Codice passo‑passo, spiegazioni e consigli per salvare HTML come zip. +og_title: Come comprimere HTML in C# – Guida completa +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Come comprimere HTML in C# – Tutorial sul gestore di risorse personalizzato +url: /it/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +the shortcodes at top and bottom unchanged. Also keep code block placeholders unchanged. + +We need to translate headings, paragraphs, list items, blockquotes, etc. + +Let's produce the translated version. + +Be careful with markdown links: there are none except maybe in the text? There's no markdown link. There's a code block placeholder, not actual code. Keep them. + +Also note "⚠️" etc not needed. + +Proceed. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come comprimere HTML in ZIP con C# – Tutorial sul gestore di risorse personalizzato + +Ti sei mai chiesto **come comprimere HTML** direttamente dalla tua app .NET senza toccare il file system? Non sei l'unico. Molti sviluppatori devono impacchettare un documento HTML insieme alle sue risorse—immagini, CSS, script—in un unico file ZIP per facilitarne il trasporto o l'archiviazione. + +In questo tutorial ti mostreremo un modo pulito per **salvare HTML come zip** usando `ResourceHandler` di Aspose.HTML. Tratteremo anche argomenti correlati come **convert HTML to zip** e **save HTML to zip** con un gestore riutilizzabile che puoi inserire in qualsiasi progetto. Nessun tool esterno, nessun file temporaneo—solo pura magia in‑memory. + +## Cosa imparerai + +* Come creare un `HTMLDocument` in memoria. +* Come implementare un **custom resource handler** che trasmette ogni risorsa in un unico archivio ZIP. +* Il codice esatto necessario per **save HTML as zip** e recuperare l'array di byte. +* Suggerimenti per gestire casi particolari come immagini di grandi dimensioni o più file CSS. +* Un esempio completo, eseguibile, da copiare‑incollare in Visual Studio. + +> **Prerequisiti** – Hai bisogno di .NET 6+ (o .NET Framework 4.6+) e della libreria Aspose.HTML per .NET installata via NuGet (`Install-Package Aspose.HTML`). Nessun'altra dipendenza. + +--- + +## Passo 1 – Creare il documento HTML (How to Zip HTML) + +La prima cosa di cui abbiamo bisogno è un'istanza `HTMLDocument` che contenga il markup che vogliamo comprimere. Considerala come la tela per il resto del processo. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Perché è importante:** Usando `HTMLDocument` lasciamo che Aspose.HTML gestisca il parsing CSS, il layout e la risoluzione dei font esattamente come farebbe un browser. Questo garantisce che il PNG ottenuto sia identico a quello che un utente vedrebbe in Chrome o Edge. + +## Convert HTML to Image – Configure Rendering Options + +Successivamente definiamo come il motore deve rasterizzare il markup. Qui è dove **set image width height**, abiliti l'antialiasing e scegli un colore di sfondo. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Consiglio professionale:** Se ometti `Width` e `Height`, Aspose.HTML utilizzerà la dimensione intrinseca della pagina, che potrebbe essere troppo piccola per le miniature. Impostare esplicitamente questi valori ti dà il pieno controllo sulle dimensioni finali del PNG. + +## Generate PNG from HTML – Apply Font Styles (Optional) + +A volte hai bisogno di grassetto, corsivo o una combinazione di stili. L'enum `WebFontStyle` ti permette di unire flag usando l'operatore OR bitwise (`|`). Questo passaggio è opzionale ma dimostra come **generate PNG from HTML** con stile personalizzato. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **Cosa sta succedendo:** `combinedFontStyle.ToString()` restituisce `"Bold, Italic"` che il motore traduce in un valore CSS `font-style` valido. Il risultato è un PNG in cui il testo appare sia in grassetto che in corsivo. + +## Save HTML as PNG – The Final Rendering Call + +Ora uniamo tutto. Il renderer `Image` scrive il contenuto rasterizzato su file disco. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Eseguendo il programma viene creato `output.png` nella directory di lavoro. Aprilo e vedrai il risultato **render html to png**—testo nitido, antialiasato su una tela bianca, esattamente 800 × 600 pixel. + + + +> **Output previsto:** Un file PNG che mostra “Sample text” in Arial 24 px, grassetto e corsivo, centrato nell'immagine. Se cambi la stringa HTML o i valori `Width`/`Height`, il PNG si aggiorna di conseguenza. + +## Convert HTML to Image – Common Variations & Edge Cases + +### 1. Rendering a Remote Web Page + +Se devi **convert HTML to image** da un URL live, passa semplicemente l'URL a `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Assicurati che il sito di destinazione consenta l'accesso programmatico (CORS, autenticazione, ecc.). + +### 2. Transparent Backgrounds + +Imposta `BackColor = Color.Transparent` e scegli un formato PNG che supporti canali alfa. È utile per sovrapporre l'immagine ad altri elementi UI. + +### 3. High‑Resolution Output + +Per grafiche pronte per la stampa, aumenta `Width` e `Height` impostando anche `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Handling Large Stylesheets + +Aspose.HTML scarica automaticamente i file CSS collegati. Se vuoi limitare le chiamate di rete, incorpora il CSS critico direttamente nella stringa HTML o usa `ResourceLoadingOptions` per mettere in cache le risorse. + +## Full, Runnable Example + +Di seguito trovi il programma completo che puoi copiare‑incollare in un'applicazione console. Include tutti i passaggi, i commenti e le personalizzazioni opzionali discusse sopra. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Compila ed esegui (`dotnet run` se usi la .NET CLI). La console confermerà la creazione del file e troverai `output.png` accanto all'eseguibile. + +## Wrap‑Up + +Abbiamo appena coperto tutto ciò che ti serve per **render HTML to PNG** usando Aspose.HTML in C#. Dalla creazione del documento, alla regolazione delle opzioni di rendering, all'applicazione di stili di font personalizzati, fino al salvataggio finale dell'immagine—ogni passaggio è stato spiegato **perché** è importante, non solo **come** digitare il codice. + +Se vuoi **convert HTML to image** in altri formati, basta cambiare l'estensione del file in `renderer.Save` in `.jpeg` o `.bmp` e adeguare `ImageSaveOptions` di conseguenza. Vuoi elaborare in batch decine di pagine? Avvolgi il blocco di rendering in un ciclo `foreach` e fornisci ogni stringa HTML o URL. + +### What’s Next? + +- **Esplora la generazione PDF** – Aspose.HTML può anche esportare in PDF con opzioni simili. +- **Combina più pagine** – Renderizza ogni pagina di un documento HTML multi‑page in PNG separati. +- **Integra con ASP.NET Core** – Restituisci il PNG direttamente come `FileResult` per screenshot on‑the‑fly. + +Sentiti libero di sperimentare con le impostazioni, sostituire il contenuto HTML o inserire questo codice in un servizio web. Il cielo è il limite quando puoi **generate PNG from HTML** al volo. + +Hai domande o un caso d'uso complesso? Lascia un commento qui sotto, e buona programmazione! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/japanese/net/html-extensions-and-conversions/_index.md b/html/japanese/net/html-extensions-and-conversions/_index.md index 4110fd8e8..76e12f853 100644 --- a/html/japanese/net/html-extensions-and-conversions/_index.md +++ b/html/japanese/net/html-extensions-and-conversions/_index.md @@ -78,6 +78,8 @@ C# と Aspose.HTML を使用して、HTML コンテンツを Zip アーカイブ ### [C# で HTML を ZIP に保存 – 完全インメモリ例](./save-html-to-zip-in-c-complete-in-memory-example/) Aspose.HTML for .NET を使用して、HTML をメモリ内で ZIP アーカイブに保存する手順をステップバイステップで解説します。 +### [C# で HTML を Zip に圧縮する方法 – カスタムリソースハンドラ チュートリアル](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) + ## 結論 結論として、HTML の拡張と変換は、現代の Web 開発に不可欠な要素です。Aspose.HTML for .NET はプロセスを簡素化し、あらゆるレベルの開発者が利用できるようにします。当社のチュートリアルに従うことで、幅広いスキルを備えた熟練した Web 開発者になるための道を順調に進むことができます。 diff --git a/html/japanese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/japanese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..0c7d9d223 --- /dev/null +++ b/html/japanese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-02-21 +description: C# のカスタム リソース ハンドラを使用して HTML を zip に圧縮する方法を学びましょう。このガイドでは、HTML を zip + として保存する方法、HTML を zip に変換する方法、そして HTML を zip に保存する方法も取り上げています。 +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: ja +og_description: カスタムリソースハンドラを使用して C# で HTML を zip に圧縮する方法。ステップバイステップのコード、解説、HTML を + zip として保存するためのヒント。 +og_title: C#でHTMLをZIPする方法 – 完全ガイド +tags: +- Aspose.HTML +- C# +- ZIP compression +title: C#でHTMLをZIPする方法 – カスタムリソースハンドラチュートリアル +url: /ja/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +. + +Make sure code block placeholders remain unchanged. + +Also preserve blockquotes >. + +Let's craft translation. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#でHTMLをZIPにする方法 – カスタムリソースハンドラーチュートリアル + +.NET アプリからファイルシステムに触れずに **HTML を ZIP にする** 方法を考えたことはありませんか? あなただけではありません。多くの開発者が、HTML ドキュメントとそのリソース(画像、CSS、スクリプト)を 1 つの ZIP ファイルにまとめて、簡単に転送や保存できるようにしたいと考えています。 + +このチュートリアルでは、Aspose.HTML の `ResourceHandler` を使って **HTML を ZIP として保存** するクリーンな方法を紹介します。また、**HTML を ZIP に変換** や **HTML を ZIP に保存** といった関連トピックにも触れ、どのプロジェクトにも組み込める再利用可能なハンドラを提供します。外部ツール不要、テンポラリファイル不要、純粋にインメモリで実現します。 + +## 学べること + +* インメモリの `HTMLDocument` の作成方法 +* すべてのリソースを 1 つの ZIP アーカイブにストリームする **カスタムリソースハンドラ** の実装方法 +* **HTML を ZIP として保存** し、バイト配列を取得するための正確なコード +* 大きな画像や複数の CSS ファイルなど、エッジケースの取り扱いに関するヒント +* Visual Studio にコピペできる、完全に実行可能なサンプル + +> **前提条件** – .NET 6+(または .NET Framework 4.6+)と、NuGet でインストールした Aspose.HTML for .NET ライブラリ(`Install-Package Aspose.HTML`)が必要です。その他の依存関係はありません。 + +--- + +## Step 1 – Create the HTML Document (How to Zip HTML) + +最初に必要なのは、圧縮したいマークアップを保持する `HTMLDocument` インスタンスです。これは以降の処理全体のキャンバスと考えてください。 + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **ポイント:** `HTMLDocument` を使用することで、Aspose.HTML が CSS の解析、レイアウト、フォント解決をブラウザーと同様に行います。これにより、生成される PNG は Chrome や Edge でユーザーが見るものと同一になります。 + +## Convert HTML to Image – レンダリングオプションの設定 + +次に、エンジンがマークアップをどのようにラスタライズするかを定義します。ここで **画像の幅と高さ** を設定し、アンチエイリアスを有効にし、背景色を指定します。 + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **プロのコツ:** `Width` と `Height` を省略すると、Aspose.HTML はページの固有サイズを使用しますが、サムネイルとしては小さすぎることがあります。明示的にサイズを指定すれば、最終 PNG の寸法を完全にコントロールできます。 + +## Generate PNG from HTML – フォントスタイルの適用(任意) + +太字や斜体、あるいはその組み合わせが必要な場合があります。`WebFontStyle` 列挙体はビット単位の OR 演算子(`|`)でフラグを結合できます。この手順は任意ですが、**HTML から PNG を生成** する際にカスタムスタイリングを行う方法を示しています。 + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **何が起きているか:** `combinedFontStyle.ToString()` は `"Bold, Italic"` を返し、エンジンはこれを有効な CSS の `font-style` 値に変換します。その結果、テキストが太字かつ斜体の PNG が生成されます。 + +## Save HTML as PNG – 最終的なレンダリング呼び出し + +すべてをまとめます。`Image` レンダラがラスタライズされたコンテンツをディスク上のファイルに書き出します。 + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +プログラムを実行すると、作業ディレクトリに `output.png` が作成されます。開いてみると、**render html to png** の結果が確認できます。白いキャンバス上に 800 × 600 ピクセルの鮮明でアンチエイリアス処理されたテキストが表示されます。 + + + +> **期待される出力:** 「Sample text」という文字列が 24 px Arial、太字・斜体で画像の中央に描かれた PNG。HTML 文字列や `Width`/`Height` の値を変更すれば、PNG も自動的に更新されます。 + +## Convert HTML to Image – よくあるバリエーションとエッジケース + +### 1. リモート Web ページのレンダリング + +ライブ URL から **HTML を画像に変換** したい場合は、`HTMLDocument` に URL を渡すだけです。 + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +対象サイトがプログラムからのアクセスを許可しているか(CORS、認証など)を確認してください。 + +### 2. 透過背景 + +`BackColor = Color.Transparent` を設定し、アルファチャンネルをサポートする PNG 形式を選択します。これにより、他の UI 要素上に画像を重ね合わせることが容易になります。 + +### 3. 高解像度出力 + +印刷向けのグラフィックが必要な場合は、`Width` と `Height` を大きくし、さらに `DPI` を設定します。 + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. 大規模スタイルシートの取り扱い + +Aspose.HTML はリンクされた CSS ファイルを自動でダウンロードします。ネットワーク呼び出しを抑えたい場合は、重要な CSS を HTML 文字列に埋め込むか、`ResourceLoadingOptions` を使ってリソースをキャッシュしてください。 + +## 完全な実行可能サンプル + +以下はコンソールアプリケーションにコピペできる、全手順・コメント・オプションを網羅したプログラムです。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +`dotnet run`(.NET CLI 使用時)でコンパイル・実行してください。コンソールにファイル作成が確認され、実行ファイルと同じディレクトリに `output.png` が生成されます。 + +## まとめ + +Aspose.HTML を使って C# で **HTML を PNG にレンダリング** するために必要な手順をすべて解説しました。ドキュメント作成、レンダリングオプションの調整、カスタムフォントスタイルの適用、最終的な画像保存まで、**なぜ**それが重要か、**どうやって**書くかを丁寧に説明しています。 + +他のフォーマットに **HTML を画像に変換** したい場合は、`renderer.Save` のファイル拡張子を `.jpeg` や `.bmp` に変更し、`ImageSaveOptions` を適宜調整すれば OK です。多数のページをバッチ処理したい場合は、レンダリングブロックを `foreach` ループで囲み、各 HTML 文字列または URL を順に処理してください。 + +### 次にやること + +- **PDF 生成を試す** – Aspose.HTML は同様のオプションで PDF へのエクスポートも可能です。 +- **複数ページの結合** – マルチページ HTML ドキュメントの各ページを別々の PNG にレンダリングします。 +- **ASP.NET Core への統合** – PNG を `FileResult` として直接返し、オンザフライでスクリーンショットを提供します。 + +設定をいろいろ試したり、HTML コンテンツを差し替えたり、コードを Web サービスに組み込んだりしてみてください。**HTML から PNG を動的に生成**できれば、可能性は無限大です。 + +質問や難しいユースケースがあれば、下のコメント欄にどうぞ。ハッピーコーディング! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/korean/net/html-extensions-and-conversions/_index.md b/html/korean/net/html-extensions-and-conversions/_index.md index 38fc3bd7e..7e925f496 100644 --- a/html/korean/net/html-extensions-and-conversions/_index.md +++ b/html/korean/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Aspose.HTML for .NET을 사용하여 스타일이 적용된 텍스트가 포함 Aspose.HTML for .NET을 사용해 HTML을 ZIP 파일로 저장하는 전체 C# 단계별 튜토리얼. ### [C#에서 HTML을 ZIP으로 저장 – 완전 인메모리 예제](./save-html-to-zip-in-c-complete-in-memory-example/) Aspose.HTML for .NET을 사용하여 메모리 내에서 HTML을 ZIP 파일로 저장하는 방법을 단계별로 안내합니다. +### [C#에서 HTML을 Zip으로 압축하는 방법 – 사용자 정의 리소스 핸들러 튜토리얼](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +C#와 Aspose.HTML을 사용해 사용자 정의 리소스 핸들러로 HTML을 ZIP 파일로 압축하는 단계별 가이드. ## 결론 diff --git a/html/korean/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/korean/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..85ecb111c --- /dev/null +++ b/html/korean/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-02-21 +description: C#에서 사용자 정의 리소스 핸들러를 사용해 HTML을 zip으로 압축하는 방법을 배웁니다. 이 가이드는 HTML을 zip으로 + 저장하고, HTML을 zip으로 변환하며, HTML을 zip으로 저장하는 방법도 다룹니다. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: ko +og_description: 맞춤 리소스 핸들러를 사용해 C#에서 HTML을 zip으로 압축하는 방법. 단계별 코드, 설명 및 HTML을 zip으로 + 저장하는 팁. +og_title: C#에서 HTML 압축하는 방법 – 완전 가이드 +tags: +- Aspose.HTML +- C# +- ZIP compression +title: C#로 HTML을 압축하는 방법 – 커스텀 리소스 핸들러 튜토리얼 +url: /ko/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 HTML을 ZIP으로 압축하는 방법 – 커스텀 리소스 핸들러 튜토리얼 + +.NET 애플리케이션에서 파일 시스템을 건드리지 않고 **HTML을 직접 ZIP으로 압축**하는 방법이 궁금하신가요? 혼자가 아닙니다. 많은 개발자들이 HTML 문서와 그 리소스(이미지, CSS, 스크립트)를 하나의 ZIP 파일로 패키징해 손쉽게 전송하거나 저장하려고 합니다. + +이 튜토리얼에서는 Aspose.HTML의 `ResourceHandler`를 사용해 **HTML을 ZIP으로 저장**하는 깔끔한 방법을 보여드립니다. 또한 **HTML을 ZIP으로 변환**하고 **HTML을 ZIP에 저장**하는 재사용 가능한 핸들러를 소개합니다. 외부 도구 없이, 임시 파일 없이—전부 메모리 내에서 이루어집니다. + +## 배울 내용 + +* 메모리 내 `HTMLDocument`를 만드는 방법 +* 모든 리소스를 하나의 ZIP 아카이브로 스트리밍하는 **커스텀 리소스 핸들러** 구현 방법 +* **HTML을 ZIP으로 저장**하고 바이트 배열을 얻는 정확한 코드 +* 큰 이미지나 다수의 CSS 파일 같은 엣지 케이스 처리 팁 +* Visual Studio에 복사‑붙여넣기만 하면 바로 실행 가능한 완전한 예제 + +> **전제 조건** – .NET 6+ (또는 .NET Framework 4.6+)와 NuGet(`Install-Package Aspose.HTML`)을 통해 설치된 Aspose.HTML for .NET 라이브러리가 필요합니다. 다른 의존성은 없습니다. + +--- + +## Step 1 – HTML 문서 만들기 (How to Zip HTML) + +먼저 압축하려는 마크업을 담을 `HTMLDocument` 인스턴스를 생성합니다. 이는 이후 과정의 캔버스 역할을 합니다. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **왜 중요한가:** `HTMLDocument`를 사용하면 Aspose.HTML가 CSS 파싱, 레이아웃 계산, 폰트 해석을 브라우저와 동일하게 처리합니다. 따라서 얻어지는 PNG는 Chrome이나 Edge에서 사용자가 보는 화면과 동일합니다. + +## Convert HTML to Image – Configure Rendering Options + +다음으로 엔진이 마크업을 어떻게 래스터화할지 정의합니다. 여기서 **이미지 너비와 높이**를 설정하고, 안티앨리어싱을 활성화하며, 배경 색을 지정합니다. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **프로 팁:** `Width`와 `Height`를 생략하면 Aspose.HTML가 페이지의 고유 크기를 사용합니다. 이는 썸네일용으로는 너무 작을 수 있으니, 명시적으로 값을 지정해 최종 PNG 크기를 완전히 제어하세요. + +## Generate PNG from HTML – Apply Font Styles (Optional) + +때때로 굵게, 기울임꼴 또는 두 스타일을 동시에 적용해야 할 때가 있습니다. `WebFontStyle` 열거형은 비트 OR 연산자(`|`)를 사용해 플래그를 병합할 수 있습니다. 이 단계는 선택 사항이지만 **HTML에서 PNG 생성** 시 사용자 정의 스타일링을 적용하는 방법을 보여줍니다. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **무슨 일이 일어나나요:** `combinedFontStyle.ToString()`은 `"Bold, Italic"`을 반환하고, 엔진은 이를 유효한 CSS `font-style` 값으로 변환합니다. 결과는 텍스트가 굵게와 기울임꼴 모두 적용된 PNG가 됩니다. + +## Save HTML as PNG – The Final Rendering Call + +이제 모든 것을 연결합니다. `Image` 렌더러가 래스터화된 내용을 디스크의 파일에 기록합니다. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +프로그램을 실행하면 작업 디렉터리에 `output.png`가 생성됩니다. 파일을 열어 보면 **render html to png** 결과—흰색 캔버스 위에 선명하고 안티앨리어싱된 텍스트가 800 × 600 픽셀 크기로 표시됩니다. + + + +> **예상 출력:** 24‑px Arial, 굵게와 기울임꼴이 적용된 “Sample text”가 이미지 중앙에 표시된 PNG 파일입니다. HTML 문자열이나 `Width`/`Height` 값을 변경하면 PNG도 그에 맞게 업데이트됩니다. + +## Convert HTML to Image – Common Variations & Edge Cases + +### 1. Rendering a Remote Web Page + +실제 URL에서 **HTML을 이미지로 변환**해야 한다면 `HTMLDocument`에 URL을 전달하면 됩니다: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +대상 사이트가 프로그램matic 접근을 허용하는지(CORS, 인증 등) 확인하세요. + +### 2. Transparent Backgrounds + +`BackColor = Color.Transparent`로 설정하고 알파 채널을 지원하는 PNG 포맷을 선택하면 투명 배경을 만들 수 있습니다. 이는 다른 UI 요소 위에 이미지를 오버레이할 때 유용합니다. + +### 3. High‑Resolution Output + +인쇄용 그래픽이 필요하다면 `Width`와 `Height`를 늘리고 `DPI`도 설정하세요: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Handling Large Stylesheets + +Aspose.HTML는 연결된 CSS 파일을 자동으로 다운로드합니다. 네트워크 호출을 제한하고 싶다면 중요한 CSS를 HTML 문자열에 직접 삽입하거나 `ResourceLoadingOptions`를 사용해 리소스를 캐시하세요. + +## Full, Runnable Example + +아래는 콘솔 애플리케이션에 복사·붙여넣기 할 수 있는 완전한 프로그램 예제입니다. 앞서 설명한 모든 단계, 주석, 선택적 조정이 포함되어 있습니다. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +`dotnet run`(또는 .NET CLI 사용)으로 컴파일·실행하세요. 콘솔에 파일 생성이 확인되고 실행 파일 옆에 `output.png`가 생성됩니다. + +## Wrap‑Up + +이제 Aspose.HTML을 이용해 C#에서 **HTML을 PNG로 렌더링**하는 전체 과정을 마스터했습니다. 문서 생성, 렌더링 옵션 조정, 사용자 정의 폰트 스타일 적용, 최종 이미지 저장까지 각 단계가 **왜** 중요한지와 **어떻게** 구현하는지를 설명했습니다. + +다른 포맷으로 **HTML을 이미지로 변환**하고 싶다면 `renderer.Save`의 파일 확장자를 `.jpeg` 혹은 `.bmp`로 바꾸고 `ImageSaveOptions`를 적절히 조정하면 됩니다. 수십 개의 페이지를 일괄 처리하려면 렌더링 블록을 `foreach` 루프로 감싸고 각 HTML 문자열이나 URL을 전달하면 됩니다. + +### What’s Next? + +- **PDF 생성 탐색** – Aspose.HTML은 유사한 옵션으로 PDF 내보내기도 지원합니다. +- **다중 페이지 결합** – 다페이지 HTML 문서의 각 페이지를 별도 PNG로 렌더링합니다. +- **ASP.NET Core와 통합** – PNG를 `FileResult`로 바로 반환해 실시간 스크린샷 서비스를 구현합니다. + +설정값을 마음대로 바꾸고, HTML 콘텐츠를 교체하거나, 이 코드를 웹 서비스에 연결해 보세요. **HTML에서 PNG 생성**을 실시간으로 수행할 수 있다면 가능성은 무한합니다. + +궁금한 점이나 어려운 사용 사례가 있으면 아래에 댓글을 남겨 주세요. 즐거운 코딩 되세요! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/polish/net/html-extensions-and-conversions/_index.md b/html/polish/net/html-extensions-and-conversions/_index.md index 5b553b002..bb91251b6 100644 --- a/html/polish/net/html-extensions-and-conversions/_index.md +++ b/html/polish/net/html-extensions-and-conversions/_index.md @@ -65,6 +65,8 @@ Dowiedz się, jak używać Aspose.HTML dla .NET do manipulowania dokumentami HTM Dowiedz się, jak konwertować HTML do TIFF za pomocą Aspose.HTML dla .NET. Postępuj zgodnie z naszym przewodnikiem krok po kroku, aby uzyskać skuteczną optymalizację treści internetowych. ### [Konwersja HTML do XPS w .NET za pomocą Aspose.HTML](./convert-html-to-xps/) Odkryj moc Aspose.HTML dla .NET: Konwertuj HTML na XPS bez wysiłku. Zawiera wymagania wstępne, przewodnik krok po kroku i FAQ. +### [Jak spakować HTML w C# – Samouczek z niestandardowym obsługiwaczem zasobów](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Dowiedz się, jak spakować plik HTML do archiwum ZIP w C# przy użyciu niestandardowego obsługiwacza zasobów w Aspose.HTML. ### [Jak spakować HTML w C# – Zapisz HTML do pliku ZIP](./how-to-zip-html-in-c-save-html-to-zip/) Dowiedz się, jak spakować plik HTML do archiwum ZIP w C# przy użyciu Aspose.HTML. ### [Utwórz dokument HTML ze stylowanym tekstem i wyeksportuj do PDF – Pełny przewodnik](./create-html-document-with-styled-text-and-export-to-pdf-full/) diff --git a/html/polish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/polish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..fd45ad7ca --- /dev/null +++ b/html/polish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-02-21 +description: Dowiedz się, jak spakować HTML do pliku zip przy użyciu własnego obsługiwacza + zasobów w C#. Ten przewodnik obejmuje także zapisywanie HTML jako zip, konwertowanie + HTML na zip oraz zapisywanie HTML do zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: pl +og_description: Jak spakować HTML w C# przy użyciu własnego obsługiwacza zasobów. + Krok po kroku kod, wyjaśnienia i wskazówki dotyczące zapisywania HTML jako zip. +og_title: Jak spakować HTML w C# – Kompletny przewodnik +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Jak spakować HTML w C# – Poradnik o niestandardowym obsługiwaniu zasobów +url: /pl/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak spakować HTML w formacie ZIP w C# – Samouczek z niestandardowym obsługiwaczem zasobów + +Zastanawiałeś się kiedyś **jak spakować HTML** bezpośrednio z aplikacji .NET, nie dotykając systemu plików? Nie jesteś sam. Wielu programistów musi zapakować dokument HTML wraz z jego zasobami — obrazami, CSS, skryptami — do jednego pliku ZIP, aby łatwo go przenieść lub przechować. + +W tym samouczku pokażemy czysty sposób **zapisania HTML jako zip** przy użyciu `ResourceHandler` z Aspose.HTML. Poruszymy także tematy pokrewne, takie jak **convert HTML to zip** i **save HTML to zip**, korzystając z wielokrotnego użycia obsługiwacza, który możesz wstawić do dowolnego projektu. Bez zewnętrznych narzędzi, bez plików tymczasowych — czysta magia w pamięci. + +## Czego się nauczysz + +* Jak utworzyć w‑pamięci `HTMLDocument`. +* Jak zaimplementować **niestandardowy obsługiwacz zasobów**, który strumieniuje każdy zasób do jednego archiwum ZIP. +* Dokładny kod potrzebny do **save HTML as zip** i pobrania tablicy bajtów. +* Wskazówki dotyczące obsługi przypadków brzegowych, takich jak duże obrazy czy wiele plików CSS. +* Pełny, gotowy przykład, który możesz skopiować i wkleić do Visual Studio. + +> **Wymagania wstępne** – Potrzebujesz .NET 6+ (lub .NET Framework 4.6+) oraz biblioteki Aspose.HTML for .NET zainstalowanej przez NuGet (`Install-Package Aspose.HTML`). Żadnych innych zależności. + +--- + +## Krok 1 – Utwórz dokument HTML (How to Zip HTML) + +Pierwszą rzeczą, której potrzebujemy, jest instancja `HTMLDocument` zawierająca znacznik, który chcemy skompresować. Traktuj to jako płótno dla dalszego procesu. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Dlaczego to ważne:** Używając `HTMLDocument` pozwalamy Aspose.HTML obsłużyć parsowanie CSS, układ i rozwiązywanie czcionek dokładnie tak, jak przeglądarka. To gwarantuje, że otrzymany PNG wygląda identycznie z tym, co użytkownik zobaczyłby w Chrome lub Edge. + +## Konwersja HTML do obrazu – Konfiguracja opcji renderowania + +Następnie definiujemy, jak silnik ma rasteryzować znacznik. To miejsce, w którym **ustawiasz szerokość i wysokość obrazu**, włączasz antyaliasing i wybierasz kolor tła. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Wskazówka:** Jeśli pominiesz `Width` i `Height`, Aspose.HTML użyje wbudowanego rozmiaru strony, który może być za mały dla miniatur. Jawne ustawienie tych wartości daje pełną kontrolę nad ostatecznymi wymiarami PNG. + +## Generowanie PNG z HTML – Zastosowanie stylów czcionki (opcjonalnie) + +Czasami potrzebujesz pogrubienia, kursywy lub kombinacji stylów. Enum `WebFontStyle` pozwala łączyć flagi przy użyciu operatora bitowego OR (`|`). Ten krok jest opcjonalny, ale pokazuje, jak **generować PNG z HTML** z niestandardowym stylowaniem. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **Co się dzieje:** `combinedFontStyle.ToString()` zwraca `"Bold, Italic"`, co silnik tłumaczy na prawidłową wartość CSS `font-style`. Wynikiem jest PNG, w którym tekst jest jednocześnie pogrubiony i pochylony. + +## Zapisz HTML jako PNG – Ostateczne wywołanie renderowania + +Teraz łączymy wszystko razem. Renderer `Image` zapisuje rasteryzowaną zawartość do pliku na dysku. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Uruchomienie programu tworzy `output.png` w katalogu roboczym. Otwórz go, a zobaczysz wynik **render html to png** — wyraźny, antyaliasowany tekst na białym tle, dokładnie 800 × 600 pikseli. + + + +> **Oczekiwany wynik:** Plik PNG pokazujący „Sample text” w czcionce Arial 24 px, pogrubionej i pochylonej, wyśrodkowanej w obrazie. Jeśli zmienisz łańcuch HTML lub wartości `Width`/`Height`, PNG zostanie odpowiednio zaktualizowany. + +## Konwersja HTML do obrazu – Wspólne warianty i przypadki brzegowe + +### 1. Renderowanie zdalnej strony internetowej + +Jeśli potrzebujesz **konwertować HTML na obraz** z żywego URL, po prostu przekaż URL do `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Upewnij się, że docelowa strona zezwala na dostęp programowy (CORS, uwierzytelnianie itp.). + +### 2. Przezroczyste tła + +Ustaw `BackColor = Color.Transparent` i wybierz format PNG obsługujący kanały alfa. To przydatne przy nakładaniu obrazu na inne elementy UI. + +### 3. Wyjście wysokiej rozdzielczości + +Dla grafik gotowych do druku zwiększ `Width` i `Height`, jednocześnie ustawiając `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Obsługa dużych arkuszy stylów + +Aspose.HTML automatycznie pobiera powiązane pliki CSS. Jeśli chcesz ograniczyć wywołania sieciowe, osadź krytyczny CSS bezpośrednio w łańcuchu HTML lub użyj `ResourceLoadingOptions` do buforowania zasobów. + +## Pełny, gotowy do uruchomienia przykład + +Poniżej znajduje się kompletny program, który możesz skopiować i wkleić do aplikacji konsolowej. Zawiera wszystkie kroki, komentarze i opcjonalne modyfikacje omówione powyżej. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Skompiluj i uruchom (`dotnet run`, jeśli używasz .NET CLI). Konsola potwierdzi utworzenie pliku, a `output.png` znajdziesz obok pliku wykonywalnego. + +## Podsumowanie + +Właśnie omówiliśmy wszystko, co potrzebne, aby **renderować HTML do PNG** przy użyciu Aspose.HTML w C#. Od tworzenia dokumentu, przez dostosowywanie opcji renderowania, stosowanie niestandardowych stylów czcionek, po ostateczne zapisywanie obrazu — każdy krok został wyjaśniony **dlaczego** jest ważny, a nie tylko **jak** go napisać. + +Jeśli chcesz **konwertować HTML na obraz** w innych formatach, po prostu zmień rozszerzenie pliku w `renderer.Save` na `.jpeg` lub `.bmp` i odpowiednio dostosuj `ImageSaveOptions`. Chcesz przetworzyć hurtowo dziesiątki stron? Owiń blok renderowania w pętlę `foreach` i podawaj każdy łańcuch HTML lub URL. + +### Co dalej? + +- **Zbadaj generowanie PDF** – Aspose.HTML może również eksportować do PDF z podobnymi opcjami. +- **Połącz wiele stron** – Renderuj każdą stronę wielostronicowego dokumentu HTML do osobnych PNG. +- **Integracja z ASP.NET Core** – Zwróć PNG bezpośrednio jako `FileResult` dla zrzutów ekranu w locie. + +Śmiało eksperymentuj z ustawieniami, wymieniaj zawartość HTML lub wstaw ten kod do usługi webowej. Nie ma ograniczeń, gdy możesz **generować PNG z HTML** w locie. + +Masz pytania lub trudny przypadek użycia? zostaw komentarz poniżej i szczęśliwego kodowania! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/portuguese/net/html-extensions-and-conversions/_index.md b/html/portuguese/net/html-extensions-and-conversions/_index.md index 8971d46a5..9cafe3721 100644 --- a/html/portuguese/net/html-extensions-and-conversions/_index.md +++ b/html/portuguese/net/html-extensions-and-conversions/_index.md @@ -75,9 +75,13 @@ Aprenda a salvar documentos HTML em arquivos ZIP usando Aspose.HTML para .NET co ### [Como compactar HTML em C# – Salvar HTML em ZIP](./how-to-zip-html-in-c-save-html-to-zip/) Aprenda a criar um arquivo ZIP contendo arquivos HTML usando Aspose.HTML para .NET em C#. + ### [Salvar HTML em ZIP em C# – Exemplo Completo em Memória](./save-html-to-zip-in-c-complete-in-memory-example/) Aprenda a salvar arquivos HTML em um arquivo ZIP usando C# com um exemplo completo totalmente em memória. +### [Como compactar HTML em C# – Tutorial de Manipulador de Recursos Personalizado](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Aprenda a compactar HTML em C# usando um manipulador de recursos personalizado com Aspose.HTML para .NET. + ## Conclusão Concluindo, extensões e conversões HTML são elementos essenciais do desenvolvimento web moderno. O Aspose.HTML para .NET simplifica o processo e o torna acessível a desenvolvedores de todos os níveis. Ao seguir nossos tutoriais, você estará no caminho certo para se tornar um desenvolvedor web proficiente com um amplo conjunto de habilidades. diff --git a/html/portuguese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/portuguese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..2494c7c0a --- /dev/null +++ b/html/portuguese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-02-21 +description: Aprenda a compactar HTML usando um manipulador de recursos personalizado + em C#. Este guia também aborda salvar HTML como zip, converter HTML para zip e salvar + HTML em zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: pt +og_description: Como compactar HTML em C# usando um manipulador de recursos personalizado. + Código passo a passo, explicações e dicas para salvar HTML como zip. +og_title: Como compactar HTML em C# – Guia completo +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Como Compactar HTML em C# – Tutorial de Manipulador de Recursos Personalizado +url: /pt/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como Compactar HTML em C# – Tutorial de Manipulador de Recursos Personalizado + +Já se perguntou **como compactar HTML** diretamente do seu aplicativo .NET sem tocar no sistema de arquivos? Você não está sozinho. Muitos desenvolvedores precisam empacotar um documento HTML junto com seus recursos — imagens, CSS, scripts — em um único arquivo ZIP para fácil transporte ou armazenamento. + +Neste tutorial, mostraremos uma forma limpa de **salvar HTML como zip** usando o `ResourceHandler` do Aspose.HTML. Também abordaremos tópicos relacionados como **converter HTML para zip** e **salvar HTML em zip** com um manipulador reutilizável que você pode inserir em qualquer projeto. Sem ferramentas externas, sem arquivos temporários — apenas pura magia em memória. + +## O que você aprenderá + +* Como criar um `HTMLDocument` em memória. +* Como implementar um **manipulador de recursos personalizado** que transmite cada recurso para um único arquivo ZIP. +* O código exato necessário para **salvar HTML como zip** e obter o array de bytes. +* Dicas para lidar com casos extremos, como imagens grandes ou múltiplos arquivos CSS. +* Um exemplo completo e executável que você pode copiar e colar no Visual Studio. + +> **Pré-requisitos** – Você precisa do .NET 6+ (ou .NET Framework 4.6+) e da biblioteca Aspose.HTML for .NET instalada via NuGet (`Install-Package Aspose.HTML`). Nenhuma outra dependência. + +--- + +## Etapa 1 – Criar o Documento HTML (Como Compactar HTML) + +A primeira coisa que precisamos é uma instância de `HTMLDocument` que contém o markup que queremos compactar. Pense nisso como a tela para o resto do processo. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Por que isso importa:** Ao usar `HTMLDocument` deixamos que o Aspose.HTML trate a análise de CSS, layout e resolução de fontes exatamente como um navegador faria. Isso garante que o PNG resultante seja idêntico ao que um usuário veria no Chrome ou Edge. + +## Converter HTML para Imagem – Configurar Opções de Renderização + +Em seguida definimos como o motor deve rasterizar o markup. É aqui que você **define a largura e altura da imagem**, habilita antialiasing e escolhe uma cor de fundo. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Dica profissional:** Se você omitir `Width` e `Height`, o Aspose.HTML usará o tamanho intrínseco da página, que pode ser pequeno demais para miniaturas. Definir explicitamente esses valores lhe dá controle total sobre as dimensões finais do PNG. + +## Gerar PNG a partir de HTML – Aplicar Estilos de Fonte (Opcional) + +Às vezes você precisa de negrito, itálico ou uma combinação de estilos. O enum `WebFontStyle` permite combinar flags usando o operador OR bit a bit (`|`). Esta etapa é opcional, mas demonstra como **gerar PNG a partir de HTML** com estilos personalizados. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **O que está acontecendo:** `combinedFontStyle.ToString()` retorna `"Bold, Italic"` que o motor traduz em um valor CSS `font-style` válido. O resultado é um PNG onde o texto aparece tanto em negrito quanto em itálico. + +## Salvar HTML como PNG – A Chamada Final de Renderização + +Agora juntamos tudo. O renderizador `Image` grava o conteúdo rasterizado em um arquivo no disco. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Executar o programa cria `output.png` no diretório de trabalho. Abra‑o e você verá o resultado do **render html to png** – texto nítido e antialiasado em um fundo branco, exatamente 800 × 600 pixels. + + + +> **Saída esperada:** Um arquivo PNG mostrando “Sample text” em Arial 24 px, negrito e itálico, centralizado na imagem. Se você alterar a string HTML ou os valores de `Width`/`Height`, o PNG será atualizado de acordo. + +## Converter HTML para Imagem – Variações Comuns e Casos de Borda + +### 1. Renderizando uma Página Web Remota + +Se você precisar **converter HTML para imagem** a partir de uma URL ao vivo, basta passar a URL para `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Certifique‑se de que o site de destino permite acesso programático (CORS, autenticação, etc.). + +### 2. Fundos Transparentes + +Defina `BackColor = Color.Transparent` e escolha um formato PNG que suporte canais alfa. Isso é útil para sobrepor a imagem em outros elementos de UI. + +### 3. Saída de Alta Resolução + +Para gráficos prontos para impressão, aumente `Width` e `Height` enquanto também define `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Lidando com Folhas de Estilo Grandes + +Aspose.HTML baixa automaticamente arquivos CSS vinculados. Se você quiser limitar chamadas de rede, incorpore CSS crítico diretamente na string HTML ou use `ResourceLoadingOptions` para armazenar recursos em cache. + +## Exemplo Completo e Executável + +Abaixo está o programa completo que você pode copiar‑colar em uma aplicação console. Ele inclui todas as etapas, comentários e ajustes opcionais discutidos acima. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Compile e execute (`dotnet run` se estiver usando o .NET CLI). O console confirmará a criação do arquivo, e você encontrará `output.png` ao lado do executável. + +## Conclusão + +Acabamos de cobrir tudo o que você precisa para **renderizar HTML para PNG** usando Aspose.HTML em C#. Desde a criação do documento, ajuste das opções de renderização, aplicação de estilos de fonte personalizados, até a gravação final da imagem — cada etapa foi explicada **por que** ela importa, não apenas **como** digitá‑la. + +Se você deseja **converter HTML para imagem** em outros formatos, basta mudar a extensão do arquivo em `renderer.Save` para `.jpeg` ou `.bmp` e ajustar `ImageSaveOptions` conforme necessário. Quer processar em lote dezenas de páginas? Envolva o bloco de renderização em um loop `foreach` e forneça cada string HTML ou URL. + +### O que vem a seguir? + +- **Explore a geração de PDF** – Aspose.HTML também pode exportar para PDF com opções semelhantes. +- **Combine múltiplas páginas** – Renderize cada página de um documento HTML de várias páginas em PNGs separados. +- **Integre com ASP.NET Core** – Retorne o PNG diretamente como um `FileResult` para capturas de tela em tempo real. + +Sinta‑se à vontade para experimentar as configurações, trocar o conteúdo HTML ou inserir este código em um serviço web. O céu é o limite quando você pode **gerar PNG a partir de HTML** em tempo real. + +Tem perguntas ou um caso de uso complicado? Deixe um comentário abaixo, e feliz codificação! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/russian/net/html-extensions-and-conversions/_index.md b/html/russian/net/html-extensions-and-conversions/_index.md index 00354e673..309a80aef 100644 --- a/html/russian/net/html-extensions-and-conversions/_index.md +++ b/html/russian/net/html-extensions-and-conversions/_index.md @@ -67,6 +67,8 @@ Aspose.HTML для .NET — это не просто библиотека; эт Откройте для себя мощь Aspose.HTML для .NET: конвертируйте HTML в XPS без усилий. Предварительные условия, пошаговое руководство и часто задаваемые вопросы включены. ### [Как заархивировать HTML в C# – Сохранить HTML в Zip](./how-to-zip-html-in-c-save-html-to-zip/) Узнайте, как упаковать HTML‑файлы в архив ZIP с помощью C# и Aspose.HTML, используя простой пошаговый пример. +### [Как заархивировать HTML в C# – учебник по пользовательскому обработчику ресурсов](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Узнайте, как упаковать HTML‑файлы в ZIP с помощью пользовательского обработчика ресурсов в C# и Aspose.HTML. ### [Создайте HTML‑документ со стилизованным текстом и экспортируйте в PDF – Полное руководство](./create-html-document-with-styled-text-and-export-to-pdf-full/) Пошаговое руководство по созданию HTML‑документа со стилизованным текстом и его конвертации в PDF с помощью Aspose.HTML для .NET. ### [Сохраните HTML в ZIP – Полный учебник C#](./save-html-as-zip-complete-c-tutorial/) diff --git a/html/russian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/russian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..9db0e6ee6 --- /dev/null +++ b/html/russian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,244 @@ +--- +category: general +date: 2026-02-21 +description: Узнайте, как упаковать HTML в zip с помощью пользовательского обработчика + ресурсов в C#. В этом руководстве также рассматриваются сохранение HTML в zip, преобразование + HTML в zip и сохранение HTML в zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: ru +og_description: Как упаковать HTML в zip в C# с помощью пользовательского обработчика + ресурсов. Пошаговый код, объяснения и советы по сохранению HTML в zip. +og_title: Как заархивировать HTML в C# – Полное руководство +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Как заархивировать HTML в C# – учебник по пользовательскому обработчику ресурсов +url: /ru/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +block placeholders remain. + +Let's craft. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как упаковать HTML в ZIP в C# – Руководство по пользовательскому обработчику ресурсов + +Когда‑то задавались вопросом **как упаковать HTML** напрямую из вашего .NET‑приложения, не касаясь файловой системы? Вы не одиноки. Многие разработчики нуждаются в том, чтобы собрать HTML‑документ вместе с его ресурсами — изображениями, CSS, скриптами — в один ZIP‑файл для удобной транспортировки или хранения. + +В этом руководстве мы покажем чистый способ **сохранить HTML как zip**, используя `ResourceHandler` из Aspose.HTML. Мы также коснёмся связанных тем, таких как **convert HTML to zip** и **save HTML to zip**, предоставив переиспользуемый обработчик, который можно добавить в любой проект. Без внешних инструментов, без временных файлов — только чистая работа в памяти. + +## Что вы узнаете + +* Как создать `HTMLDocument` в памяти. +* Как реализовать **пользовательский обработчик ресурсов**, который будет стримить каждый ресурс в один ZIP‑архив. +* Точный код, необходимый для **save HTML as zip** и получения массива байтов. +* Советы по обработке граничных случаев, таких как большие изображения или несколько CSS‑файлов. +* Полный, готовый к запуску пример, который можно скопировать‑вставить в Visual Studio. + +> **Prerequisites** – Требуется .NET 6+ (или .NET Framework 4.6+) и библиотека Aspose.HTML for .NET, установленная через NuGet (`Install-Package Aspose.HTML`). Других зависимостей нет. + +--- + +## Шаг 1 – Создание HTML‑документа (How to Zip HTML) + +Первое, что нам нужно, — экземпляр `HTMLDocument`, содержащий разметку, которую мы хотим сжать. Считайте это холстом для дальнейшего процесса. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Почему это важно:** Используя `HTMLDocument`, мы позволяем Aspose.HTML обрабатывать парсинг CSS, раскладку и разрешение шрифтов точно так же, как браузер. Это гарантирует, что полученный PNG будет выглядеть идентично тому, что пользователь видит в Chrome или Edge. + +## Преобразование HTML в изображение – Настройка параметров рендеринга + +Далее мы определяем, как движок должен растеризовать разметку. Здесь вы **указываете ширину и высоту изображения**, включаете сглаживание и выбираете цвет фона. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Совет профессионала:** Если опустить `Width` и `Height`, Aspose.HTML использует внутренний размер страницы, который может быть слишком маленьким для миниатюр. Явное задание этих значений даёт полный контроль над конечными размерами PNG. + +## Генерация PNG из HTML – Применение стилей шрифтов (по желанию) + +Иногда нужны жирный, курсивный или комбинированный стиль. Перечисление `WebFontStyle` позволяет объединять флаги с помощью побитового ИЛИ (`|`). Этот шаг необязателен, но демонстрирует, как **генерировать PNG из HTML** с пользовательским стилизацией. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **Что происходит:** `combinedFontStyle.ToString()` возвращает `"Bold, Italic"`, что движок переводит в корректное CSS‑значение `font-style`. В результате получаем PNG, где текст отображается одновременно жирным и курсивным. + +## Сохранение HTML как PNG – Финальный вызов рендеринга + +Теперь собираем всё вместе. Рендерер `Image` записывает растеризованное содержимое в файл на диске. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Запуск программы создаёт `output.png` в рабочем каталоге. Откройте его, и вы увидите результат **render html to png** — чёткий, сглаженный текст на белом фоне, точно 800 × 600 пикселей. + + + +> **Ожидаемый результат:** PNG‑файл, показывающий «Sample text» 24‑px Arial, жирный и курсивный, центрированный в изображении. Если изменить строку HTML или значения `Width`/`Height`, PNG обновится соответственно. + +## Преобразование HTML в изображение – Распространённые варианты и граничные случаи + +### 1. Рендеринг удалённой веб‑страницы + +Если нужно **преобразовать HTML в изображение** из живого URL, просто передайте URL в `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Убедитесь, что целевой сайт разрешает программный доступ (CORS, аутентификация и т.д.). + +### 2. Прозрачные фоны + +Установите `BackColor = Color.Transparent` и выберите формат PNG, поддерживающий альфа‑каналы. Это удобно для наложения изображения на другие UI‑элементы. + +### 3. Вывод высокого разрешения + +Для графики, готовой к печати, увеличьте `Width` и `Height`, одновременно задав `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Работа с большими таблицами стилей + +Aspose.HTML автоматически загружает связанные CSS‑файлы. Если хотите ограничить сетевые запросы, внедрите критический CSS непосредственно в строку HTML или используйте `ResourceLoadingOptions` для кэширования ресурсов. + +## Полный, готовый к запуску пример + +Ниже представлена полная программа, которую можно скопировать и вставить в консольное приложение. В ней собраны все шаги, комментарии и необязательные настройки, обсуждённые выше. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Скомпилируйте и запустите (`dotnet run`, если используете .NET CLI). Консоль подтвердит создание файла, а `output.png` появится рядом с исполняемым файлом. + +## Итоги + +Мы рассмотрели всё, что нужно для **преобразования HTML в PNG** с помощью Aspose.HTML в C#. От создания документа, настройки параметров рендеринга, применения пользовательских стилей шрифтов до финального сохранения изображения — каждый шаг объяснялся **почему** он важен, а не только **как** его выполнить. + +Если вам нужно **преобразовать HTML в изображение** в других форматах, просто измените расширение файла в `renderer.Save` на `.jpeg` или `.bmp` и скорректируйте `ImageSaveOptions` соответственно. Хотите пакетную обработку десятков страниц? Оберните блок рендеринга в цикл `foreach` и передавайте каждую строку HTML или URL. + +### Что дальше? + +- **Изучите генерацию PDF** — Aspose.HTML также умеет экспортировать в PDF с похожими параметрами. +- **Объединяйте несколько страниц** — рендерьте каждую страницу многостраничного HTML‑документа в отдельные PNG. +- **Интеграция с ASP.NET Core** — возвращайте PNG напрямую как `FileResult` для мгновенных скриншотов. + +Экспериментируйте с настройками, меняйте HTML‑контент или внедряйте этот код в веб‑службу. Возможности безграничны, когда вы можете **генерировать PNG из HTML** «на лету». + +Есть вопросы или сложный кейс? Оставляйте комментарий ниже, и удачной разработки! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/spanish/net/html-extensions-and-conversions/_index.md b/html/spanish/net/html-extensions-and-conversions/_index.md index 58e38eec4..df74da9c5 100644 --- a/html/spanish/net/html-extensions-and-conversions/_index.md +++ b/html/spanish/net/html-extensions-and-conversions/_index.md @@ -71,6 +71,8 @@ Aprenda a convertir HTML a TIFF con Aspose.HTML para .NET. Siga nuestra guía pa Descubra el poder de Aspose.HTML para .NET: convierta HTML a XPS sin esfuerzo. Requisitos previos, guía paso a paso y preguntas frecuentes incluidas. ### [Cómo comprimir HTML en C# – Guardar HTML en Zip](./how-to-zip-html-in-c-save-html-to-zip/) Aprenda a empaquetar archivos HTML en un archivo ZIP usando C# y Aspose.HTML. Guía paso a paso con ejemplos de código. +### [Cómo comprimir HTML en C# – Tutorial de controlador de recursos personalizado](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Aprenda a comprimir HTML usando un controlador de recursos personalizado en C#. Guía paso a paso con ejemplos de código. ### [Guardar HTML en ZIP en C# – Ejemplo completo en memoria](./save-html-to-zip-in-c-complete-in-memory-example/) Aprenda a guardar HTML en un archivo ZIP usando C# con un ejemplo completo en memoria. diff --git a/html/spanish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/spanish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..4bdd1620c --- /dev/null +++ b/html/spanish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-02-21 +description: Aprende a comprimir HTML usando un controlador de recursos personalizado + en C#. Esta guía también cubre cómo guardar HTML como zip, convertir HTML a zip + y guardar HTML en zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: es +og_description: Cómo comprimir HTML en C# usando un controlador de recursos personalizado. + Código paso a paso, explicaciones y consejos para guardar HTML como zip. +og_title: Cómo comprimir HTML en C# – Guía completa +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Cómo comprimir HTML en C# – Tutorial de manejador de recursos personalizado +url: /es/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +Now produce final answer with only translated content.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo comprimir HTML en C# – Tutorial de Custom Resource Handler + +¿Alguna vez te has preguntado **cómo comprimir HTML** directamente desde tu aplicación .NET sin tocar el sistema de archivos? No estás solo. Muchos desarrolladores necesitan empaquetar un documento HTML junto con sus recursos —imágenes, CSS, scripts— en un único archivo ZIP para facilitar su transporte o almacenamiento. + +En este tutorial te mostraremos una forma limpia de **guardar HTML como zip** usando `ResourceHandler` de Aspose.HTML. También abordaremos temas relacionados como **convertir HTML a zip** y **guardar HTML a zip** con un controlador reutilizable que puedes incorporar en cualquier proyecto. Sin herramientas externas, sin archivos temporales —solo magia pura en memoria. + +## Lo que aprenderás + +* Cómo crear un `HTMLDocument` en memoria. +* Cómo implementar un **custom resource handler** que transmite cada recurso a un único archivo ZIP. +* El código exacto necesario para **guardar HTML como zip** y obtener el arreglo de bytes. +* Consejos para manejar casos límite como imágenes grandes o múltiples archivos CSS. +* Un ejemplo completo y ejecutable que puedes copiar y pegar en Visual Studio. + +> **Prerequisitos** – Necesitas .NET 6+ (o .NET Framework 4.6+) y la biblioteca Aspose.HTML para .NET instalada vía NuGet (`Install-Package Aspose.HTML`). No hay otras dependencias. + +--- + +## Paso 1 – Crear el documento HTML (Cómo comprimir HTML) + +Lo primero que necesitamos es una instancia de `HTMLDocument` que contenga el marcado que queremos comprimir. Piensa en esto como el lienzo para el resto del proceso. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Por qué es importante:** Al usar `HTMLDocument` permitimos que Aspose.HTML maneje el análisis de CSS, el diseño y la resolución de fuentes exactamente como lo haría un navegador. Eso garantiza que el PNG que obtengas sea idéntico a lo que un usuario vería en Chrome o Edge. + +## Convert HTML to Image – Configurar opciones de renderizado + +A continuación definimos cómo debe rasterizar el motor el marcado. Aquí es donde **set image width height**, habilitas el antialiasing y eliges un color de fondo. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Consejo profesional:** Si omites `Width` y `Height`, Aspose.HTML usará el tamaño intrínseco de la página, lo que puede ser demasiado pequeño para miniaturas. Establecer explícitamente estos valores te brinda control total sobre las dimensiones finales del PNG. + +## Generate PNG from HTML – Aplicar estilos de fuente (Opcional) + +A veces necesitas negrita, cursiva o una combinación de estilos. El enum `WebFontStyle` te permite combinar banderas usando el operador OR a nivel de bits (`|`). Este paso es opcional pero demuestra cómo **generate PNG from HTML** con estilo personalizado. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **Qué está sucediendo:** `combinedFontStyle.ToString()` devuelve `"Bold, Italic"` que el motor traduce a un valor CSS `font-style` válido. El resultado es un PNG donde el texto aparece tanto en negrita como en cursiva. + +## Save HTML as PNG – La llamada final de renderizado + +Ahora unimos todo. El renderizador `Image` escribe el contenido rasterizado en un archivo en disco. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Ejecutar el programa crea `output.png` en el directorio de trabajo. Ábrelo y verás el resultado de **render html to png** — texto nítido y antialiasado sobre un lienzo blanco, exactamente 800 × 600 píxeles. + + + +> **Salida esperada:** Un archivo PNG que muestra “Sample text” en Arial de 24 px, negrita y cursiva, centrado en la imagen. Si cambias la cadena HTML o los valores de `Width`/`Height`, el PNG se actualizará en consecuencia. + +## Convert HTML to Image – Variaciones comunes y casos límite + +### 1. Renderizar una página web remota + +Si necesitas **convert HTML to image** desde una URL en vivo, simplemente pasa la URL a `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Asegúrate de que el sitio objetivo permita el acceso programático (CORS, autenticación, etc.). + +### 2. Fondos transparentes + +Establece `BackColor = Color.Transparent` y elige un formato PNG que soporte canales alfa. Esto es útil para superponer la imagen sobre otros elementos de UI. + +### 3. Salida de alta resolución + +Para gráficos listos para impresión, incrementa `Width` y `Height` mientras también configuras `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Manejo de hojas de estilo grandes + +Aspose.HTML descarga automáticamente los archivos CSS vinculados. Si deseas limitar las llamadas a la red, incrusta CSS crítico directamente en la cadena HTML o usa `ResourceLoadingOptions` para almacenar en caché los recursos. + +## Ejemplo completo y ejecutable + +A continuación se muestra el programa completo que puedes copiar‑pegar en una aplicación de consola. Incluye todos los pasos, comentarios y ajustes opcionales discutidos arriba. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Compila y ejecuta (`dotnet run` si usas la CLI de .NET). La consola confirmará la creación del archivo y encontrarás `output.png` junto al ejecutable. + +## Conclusión + +Acabamos de cubrir todo lo que necesitas para **render HTML to PNG** usando Aspose.HTML en C#. Desde crear el documento, ajustar las opciones de renderizado, aplicar estilos de fuente personalizados, hasta finalmente guardar la imagen — cada paso se explicó **por qué** es importante, no solo **cómo** escribirlo. + +Si buscas **convert HTML to image** para otros formatos, simplemente cambia la extensión del archivo en `renderer.Save` a `.jpeg` o `.bmp` y ajusta `ImageSaveOptions` en consecuencia. ¿Quieres procesar por lotes decenas de páginas? Envuelve el bloque de renderizado en un bucle `foreach` y proporciona cada cadena HTML o URL. + +### ¿Qué sigue? + +- **Explore PDF generation** – Aspose.HTML también puede exportar a PDF con opciones similares. +- **Combine multiple pages** – Renderiza cada página de un documento HTML multipágina a PNGs separados. +- **Integrate with ASP.NET Core** – Devuelve el PNG directamente como un `FileResult` para capturas de pantalla en tiempo real. + +Siéntete libre de experimentar con la configuración, cambiar el contenido HTML o integrar este código en un servicio web. El cielo es el límite cuando puedes **generate PNG from HTML** al instante. + +¿Tienes preguntas o un caso de uso complicado? Deja un comentario abajo, ¡y feliz codificación! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/swedish/net/html-extensions-and-conversions/_index.md b/html/swedish/net/html-extensions-and-conversions/_index.md index 6d01c9b96..01a926d96 100644 --- a/html/swedish/net/html-extensions-and-conversions/_index.md +++ b/html/swedish/net/html-extensions-and-conversions/_index.md @@ -65,6 +65,8 @@ Lär dig hur du konverterar HTML till TIFF med Aspose.HTML för .NET. Följ vår Upptäck kraften i Aspose.HTML för .NET: Konvertera HTML till XPS utan ansträngning. Förutsättningar, steg-för-steg-guide och vanliga frågor ingår. ### [Hur du zippar HTML i C# – Spara HTML till zip](./how-to-zip-html-in-c-save-html-to-zip/) Lär dig hur du packar HTML-filer i en zip-arkiv med C# och Aspose.HTML för .NET i en steg-för-steg-guide. +### [Hur du zippar HTML i C# – Anpassad resurs‑hanterare‑handledning](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Lär dig hur du zippar HTML-filer med en anpassad resurs‑hanterare i C# med Aspose.HTML för .NET. ### [Skapa HTML-dokument med formaterad text och exportera till PDF – Fullständig guide](./create-html-document-with-styled-text-and-export-to-pdf-full/) Lär dig skapa ett HTML-dokument med stiliserad text och konvertera det till PDF med Aspose.HTML för .NET i en komplett steg-för-steg-guide. ### [Skapa PDF från HTML – C# steg‑för‑steg‑guide](./create-pdf-from-html-c-step-by-step-guide/) diff --git a/html/swedish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/swedish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..a5118bd90 --- /dev/null +++ b/html/swedish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-02-21 +description: Lär dig hur du zippar HTML med en anpassad resurs‑hanterare i C#. Denna + guide täcker också att spara HTML som zip, konvertera HTML till zip och spara HTML + till zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: sv +og_description: Hur man zippar HTML i C# med en anpassad resurs‑hanterare. Steg‑för‑steg‑kod, + förklaringar och tips för att spara HTML som zip. +og_title: Hur hur man zippar HTML i C# – Komplett guide +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Hur man zippar HTML i C# – Handledning för anpassad resurs‑hanterare +url: /sv/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hur man zippar HTML i C# – Anpassad resurs‑hanterare‑tutorial + +Har du någonsin undrat **hur man zippar HTML** direkt från din .NET‑app utan att röra filsystemet? Du är inte ensam. Många utvecklare behöver paketera ett HTML‑dokument tillsammans med dess resurser—bilder, CSS, skript—i en enda ZIP‑fil för enkel transport eller lagring. + +I den här tutorialen visar vi ett rent sätt att **spara HTML som zip** med Aspose.HTML:s `ResourceHandler`. Vi berör också relaterade ämnen som **convert HTML to zip** och **save HTML to zip** med en återanvändbar hanterare som du kan släppa in i vilket projekt som helst. Inga externa verktyg, inga temporära filer—bara ren minnes‑magik. + +## Vad du kommer att lära dig + +* Hur man skapar ett **in‑memory** `HTMLDocument`. +* Hur man implementerar en **custom resource handler** som strömmar varje resurs till ett enda ZIP‑arkiv. +* Den exakta koden som behövs för att **save HTML as zip** och hämta byte‑arrayen. +* Tips för att hantera kantfall som stora bilder eller flera CSS‑filer. +* Ett komplett, körbart exempel som du kan kopiera‑klistra in i Visual Studio. + +> **Förutsättningar** – Du behöver .NET 6+ (eller .NET Framework 4.6+) och Aspose.HTML för .NET‑biblioteket installerat via NuGet (`Install-Package Aspose.HTML`). Inga andra beroenden. + +--- + +## Steg 1 – Skapa HTML‑dokumentet (How to Zip HTML) + +Det första vi behöver är en `HTMLDocument`‑instans som innehåller markupen vi vill komprimera. Tänk på detta som duken för resten av processen. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Varför detta är viktigt:** Genom att använda `HTMLDocument` låter vi Aspose.HTML hantera CSS‑parsing, layout och teckensnittslösning exakt som en webbläsare. Det garanterar att PNG‑filen du får ser identisk ut med vad en användare skulle se i Chrome eller Edge. + +## Konvertera HTML till bild – Konfigurera renderingsalternativ + +Nästa steg är att definiera hur motorn ska rasterisera markupen. Här **sätter du bildens bredd och höjd**, aktiverar antialiasing och väljer en bakgrundsfärg. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Proffstips:** Om du utelämnar `Width` och `Height` använder Aspose.HTML sidans inneboende storlek, vilket kan bli för litet för miniaturer. Genom att explicit ange dessa värden får du full kontroll över den slutliga PNG‑dimensionen. + +## Generera PNG från HTML – Applicera teckensnittsstilar (valfritt) + +Ibland behöver du fet, kursiv eller en kombination av stilar. `WebFontStyle`‑enumet låter dig slå ihop flaggor med bitvis OR‑operator (`|`). Detta steg är valfritt men visar hur du **genererar PNG från HTML** med anpassad styling. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **Vad som händer:** `combinedFontStyle.ToString()` returnerar `"Bold, Italic"` vilket motorn översätter till ett giltigt CSS‑`font-style`‑värde. Resultatet blir en PNG där texten både är fet och kursiv. + +## Spara HTML som PNG – Det sista renderingsanropet + +Nu knyter vi ihop allt. `Image`‑renderaren skriver det rasteriserade innehållet till en fil på disk. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +När programmet körs skapas `output.png` i arbetskatalogen. Öppna den så ser du **render html to png**‑resultatet – skarp, antialiasad text på en vit canvas, exakt 800 × 600 pixlar. + + + +> **Förväntad utskrift:** En PNG‑fil som visar “Sample text” i 24‑px Arial, fet och kursiv, centrerad i bilden. Om du ändrar HTML‑strängen eller `Width`/`Height`‑värdena uppdateras PNG‑filen därefter. + +## Konvertera HTML till bild – Vanliga variationer & kantfall + +### 1. Rendera en fjärrwebbsida + +Om du behöver **konvertera HTML till bild** från en levande URL, skicka bara URL:en till `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Se till att målwebbplatsen tillåter programmatisk åtkomst (CORS, autentisering osv.). + +### 2. Transparenta bakgrunder + +Sätt `BackColor = Color.Transparent` och välj ett PNG‑format som stödjer alfakanaler. Detta är praktiskt när du vill lägga bilden ovanpå andra UI‑element. + +### 3. Högupplöst utskrift + +För tryckklara grafik, öka `Width` och `Height` samt sätt `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Hantera stora stilmallar + +Aspose.HTML laddar automatiskt länkade CSS‑filer. Om du vill begränsa nätverksanrop, bädda in kritisk CSS direkt i HTML‑strängen eller använd `ResourceLoadingOptions` för att cache‑resurser. + +## Fullt körbart exempel + +Nedan är hela programmet som du kan kopiera‑klistra in i en konsolapplikation. Det innehåller alla steg, kommentarer och valfria justeringar som diskuterats ovan. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Kompilera och kör (`dotnet run` om du använder .NET CLI). Konsolen bekräftar att filen skapats, och du hittar `output.png` bredvid den körbara filen. + +## Sammanfattning + +Vi har nu gått igenom allt du behöver för att **rendera HTML till PNG** med Aspose.HTML i C#. Från att skapa dokumentet, justera renderingsalternativ, applicera anpassade teckensnittsstilar, till att slutligen spara bilden – varje steg förklarades **varför** det är viktigt, inte bara **hur** du skriver det. + +Om du vill **konvertera HTML till bild** i andra format, byt bara filändelsen i `renderer.Save` till `.jpeg` eller `.bmp` och justera `ImageSaveOptions` därefter. Vill du batch‑processa dussintals sidor? Lägg renderingsblocket i en `foreach`‑loop och mata in varje HTML‑sträng eller URL. + +### Vad blir nästa steg? + +- **Utforska PDF‑generering** – Aspose.HTML kan också exportera till PDF med liknande alternativ. +- **Kombinera flera sidor** – Rendera varje sida i ett flersidigt HTML‑dokument till separata PNG‑filer. +- **Integrera med ASP.NET Core** – Returnera PNG‑filen direkt som ett `FileResult` för on‑the‑fly‑skärmbilder. + +Känn dig fri att experimentera med inställningarna, byta ut HTML‑innehållet eller plugga in koden i en webbtjänst. Himlen är gränsen när du kan **generera PNG från HTML** i farten. + +Har du frågor eller ett knepigt användningsfall? Lämna en kommentar nedan, och lycka till med kodandet! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/thai/net/html-extensions-and-conversions/_index.md b/html/thai/net/html-extensions-and-conversions/_index.md index 2474ca32c..38359b7f1 100644 --- a/html/thai/net/html-extensions-and-conversions/_index.md +++ b/html/thai/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Aspose.HTML สำหรับ .NET ไม่ใช่แค่ไลบรา บันทึกไฟล์ HTML เป็น ZIP อย่างครบถ้วนด้วย C# ตามขั้นตอนของเรา ### [บันทึก HTML เป็น ZIP ใน C# – ตัวอย่างทำงานในหน่วยความจำเต็มรูปแบบ](./save-html-to-zip-in-c-complete-in-memory-example/) บันทึกไฟล์ HTML เป็นไฟล์ ZIP โดยใช้ C# ด้วยตัวอย่างทำงานในหน่วยความจำเต็มรูปแบบ +### [วิธีบีบอัด HTML เป็น Zip ใน C# – บทแนะนำตัวจัดการทรัพยากรแบบกำหนดเอง](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +เรียนรู้วิธีบีบอัดไฟล์ HTML เป็น Zip ด้วย C# โดยใช้ตัวจัดการทรัพยากรแบบกำหนดเองใน Aspose.HTML สำหรับ .NET ## บทสรุป diff --git a/html/thai/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/thai/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..facea4f58 --- /dev/null +++ b/html/thai/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-02-21 +description: เรียนรู้วิธีบีบอัด HTML เป็นไฟล์ zip ด้วยตัวจัดการทรัพยากรแบบกำหนดเองใน + C# คู่มือนี้ยังครอบคลุมการบันทึก HTML เป็น zip, การแปลง HTML เป็น zip, และการบันทึก + HTML ไปยัง zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: th +og_description: วิธีบีบอัด HTML เป็น zip ใน C# ด้วยตัวจัดการทรัพยากรแบบกำหนดเอง โค้ดทีละขั้นตอน + คำอธิบาย และเคล็ดลับในการบันทึก HTML เป็น zip. +og_title: วิธีบีบอัด HTML ด้วย C# – คู่มือฉบับสมบูรณ์ +tags: +- Aspose.HTML +- C# +- ZIP compression +title: วิธีบีบอัด HTML ด้วย C# – บทแนะนำการจัดการทรัพยากรแบบกำหนดเอง +url: /th/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +- "Conclusion" etc. + +- final paragraph. + +Make sure to keep markdown formatting: headings (#, ##, ###), blockquote >, bullet lists *, etc. + +Also keep code block placeholders unchanged. + +Let's produce final answer.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีบีบอัด HTML เป็น ZIP ใน C# – การสอนตัวจัดการทรัพยากรแบบกำหนดเอง + +เคยสงสัย **วิธีบีบอัด HTML** โดยตรงจากแอป .NET ของคุณโดยไม่ต้องสัมผัสระบบไฟล์หรือไม่? คุณไม่ได้เป็นคนเดียวที่มีคำถามนี้ นักพัฒนาหลายคนต้องการแพ็คเอกสาร HTML พร้อมกับทรัพยากรของมัน—รูปภาพ, CSS, สคริปต์—เป็นไฟล์ ZIP เดียวเพื่อการขนส่งหรือจัดเก็บที่ง่ายขึ้น + +ในบทเรียนนี้เราจะแสดงวิธีที่สะอาดในการ **บันทึก HTML เป็น zip** ด้วย `ResourceHandler` ของ Aspose.HTML เราจะพูดถึงหัวข้อที่เกี่ยวข้องเช่น **convert HTML to zip** และ **save HTML to zip** ด้วยตัวจัดการที่นำกลับมาใช้ใหม่ได้ซึ่งคุณสามารถใส่ลงในโปรเจคใดก็ได้ ไม่ต้องใช้เครื่องมือภายนอก ไม่ต้องสร้างไฟล์ชั่วคราว—เพียงแค่เวทมนตร์ในหน่วยความจำเท่านั้น + +## สิ่งที่คุณจะได้เรียนรู้ + +* วิธีสร้าง `HTMLDocument` ในหน่วยความจำ +* วิธีทำ **custom resource handler** ที่สตรีมทุกทรัพยากรเข้าไปในไฟล์ ZIP เดียว +* โค้ดที่จำเป็นในการ **save HTML as zip** และดึงอาเรย์ไบต์ออกมา +* เคล็ดลับการจัดการกรณีขอบเช่นรูปภาพขนาดใหญ่หรือหลายไฟล์ CSS +* ตัวอย่างเต็มที่สามารถรันได้และคัดลอก‑วางลง Visual Studio + +> **Prerequisites** – คุณต้องมี .NET 6+ (หรือ .NET Framework 4.6+) และไลบรารี Aspose.HTML for .NET ที่ติดตั้งผ่าน NuGet (`Install-Package Aspose.HTML`). ไม่มีการพึ่งพาอื่นใด + +--- + +## Step 1 – Create the HTML Document (How to Zip HTML) + +สิ่งแรกที่เราต้องการคืออินสแตนซ์ `HTMLDocument` ที่ถือ markup ที่เราต้องการบีบอัด คิดว่าเป็นผ้าใบสำหรับกระบวนการที่เหลือ + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **ทำไมเรื่องนี้ถึงสำคัญ:** การใช้ `HTMLDocument` ทำให้ Aspose.HTML จัดการการพาร์ส CSS, การจัดวาง, และการแก้ไขฟอนต์ได้เหมือนกับเบราว์เซอร์จริง ๆ ซึ่งรับประกันว่า PNG ที่ได้จะดูเหมือนกับที่ผู้ใช้เห็นใน Chrome หรือ Edge + +## Convert HTML to Image – Configure Rendering Options + +ต่อไปเรากำหนดวิธีที่เอนจินจะ rasterize markup. ที่นี่คุณ **set image width height**, เปิด antialiasing, และเลือกสีพื้นหลัง + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **เคล็ดลับ:** หากคุณละ `Width` และ `Height` ไว้, Aspose.HTML จะใช้ขนาดตาม intrinsic ของหน้า ซึ่งอาจเล็กเกินไปสำหรับภาพย่อ การกำหนดค่าที่ชัดเจนทำให้คุณควบคุมมิติของ PNG สุดท้ายได้เต็มที่ + +## Generate PNG from HTML – Apply Font Styles (Optional) + +บางครั้งคุณต้องการตัวหนา, ตัวเอียง, หรือการผสมสไตล์. enum `WebFontStyle` ให้คุณรวม flag ด้วยตัวดำเนินการบิตเวิร์ส OR (`|`). ขั้นตอนนี้เป็นออปชัน แต่แสดงวิธี **generate PNG from HTML** ด้วยสไตล์ที่กำหนดเอง + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **กำลังเกิดอะไรขึ้น:** `combinedFontStyle.ToString()` จะคืนค่า `"Bold, Italic"` ซึ่งเอนจินแปลงเป็นค่า CSS `font-style` ที่ถูกต้อง ผลลัพธ์คือ PNG ที่ข้อความแสดงเป็นตัวหนาและเอียงพร้อมกัน + +## Save HTML as PNG – The Final Rendering Call + +ตอนนี้เรามาผสานทุกอย่างเข้าด้วยกัน. เราใช้ renderer `Image` เพื่อเขียนเนื้อหาที่ rasterized ลงไฟล์บนดิสก์ + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +การรันโปรแกรมจะสร้าง `output.png` ในไดเรกทอรีทำงาน เปิดไฟล์แล้วคุณจะเห็นผลลัพธ์ของ **render html to png** – ข้อความคมชัด, มี antialiasing บนแคนวาสสีขาว, ขนาด 800 × 600 พิกเซล + + + +> **ผลลัพธ์ที่คาดหวัง:** ไฟล์ PNG แสดงข้อความ “Sample text” ขนาด 24‑px Arial, ตัวหนาและเอียง, อยู่กึ่งกลางภาพ หากคุณเปลี่ยนสตริง HTML หรือค่า `Width`/`Height` PNG จะอัปเดตตามนั้น + +## Convert HTML to Image – Common Variations & Edge Cases + +### 1. Rendering a Remote Web Page + +หากต้องการ **convert HTML to image** จาก URL จริง ๆ เพียงส่ง URL ให้ `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +ตรวจสอบให้แน่ใจว่าไซต์เป้าหมายอนุญาตการเข้าถึงแบบโปรแกรม (CORS, การยืนยันตัวตน ฯลฯ) + +### 2. Transparent Backgrounds + +ตั้งค่า `BackColor = Color.Transparent` และเลือกฟอร์แมต PNG ที่รองรับช่อง alpha นี่เป็นประโยชน์เมื่อต้องวางภาพบน UI อื่น + +### 3. High‑Resolution Output + +สำหรับกราฟิกพร้อมพิมพ์ เพิ่มค่า `Width` และ `Height` พร้อมตั้งค่า `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Handling Large Stylesheets + +Aspose.HTML จะดาวน์โหลดไฟล์ CSS ที่ลิงก์โดยอัตโนมัติ หากต้องการจำกัดการเรียกเครือข่าย ให้ฝัง CSS ที่สำคัญลงในสตริง HTML โดยตรง หรือใช้ `ResourceLoadingOptions` เพื่อแคชทรัพยากร + +## Full, Runnable Example + +ด้านล่างเป็นโปรแกรมเต็มที่คุณสามารถคัดลอก‑วางลงในแอปพลิเคชันคอนโซล มันรวมทุกขั้นตอน, คอมเมนต์, และการปรับแต่งออปชันที่ได้พูดถึงไว้ + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +คอมไพล์และรัน (`dotnet run` หากใช้ .NET CLI) คอนโซลจะแจ้งการสร้างไฟล์และคุณจะพบ `output.png` อยู่ข้างไฟล์ executable + +## Wrap‑Up + +เราได้ครอบคลุมทุกอย่างที่คุณต้องการเพื่อ **render HTML to PNG** ด้วย Aspose.HTML ใน C# ตั้งแต่การสร้างเอกสาร, ปรับตัวเลือกการเรนเดอร์, ใช้สไตล์ฟอนต์แบบกำหนดเอง, จนถึงการบันทึกภาพ—แต่ละขั้นตอนอธิบาย **why** จึงสำคัญ ไม่ใช่แค่ **how** พิมพ์ + +หากคุณต้องการ **convert HTML to image** เป็นฟอร์แมตอื่น เพียงเปลี่ยนนามสกุลไฟล์ใน `renderer.Save` เป็น `.jpeg` หรือ `.bmp` แล้วปรับ `ImageSaveOptions` ให้สอดคล้อง ต้องการประมวลผลหลายหน้า? ห่อบล็อกการเรนเดอร์ในลูป `foreach` แล้วป้อนสตริง HTML หรือ URL แต่ละรายการ + +### What’s Next? + +- **Explore PDF generation** – Aspose.HTML สามารถส่งออกเป็น PDF ด้วยตัวเลือกคล้ายกัน +- **Combine multiple pages** – Render แต่ละหน้าของเอกสาร HTML หลายหน้าเป็น PNG แยกกัน +- **Integrate with ASP.NET Core** – ส่ง PNG กลับเป็น `FileResult` เพื่อสร้างสกรีนช็อตแบบเรียลไทม์ + +ลองปรับแต่งการตั้งค่า, สลับเนื้อหา HTML, หรือเชื่อมโค้ดนี้เข้ากับเว็บเซอร์วิสได้เลย ความเป็นไปได้ไม่มีขีดจำกัดเมื่อคุณสามารถ **generate PNG from HTML** ได้แบบออน‑เดมานด์ + +มีคำถามหรือกรณีการใช้งานที่ท้าทาย? แสดงความคิดเห็นด้านล่าง แล้วขอให้สนุกกับการเขียนโค้ด! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/turkish/net/html-extensions-and-conversions/_index.md b/html/turkish/net/html-extensions-and-conversions/_index.md index 8dd996b05..885db85b2 100644 --- a/html/turkish/net/html-extensions-and-conversions/_index.md +++ b/html/turkish/net/html-extensions-and-conversions/_index.md @@ -66,6 +66,7 @@ Aspose.HTML for .NET ile HTML'yi TIFF'e nasıl dönüştüreceğinizi öğrenin. ### [HTML'den PDF Oluşturma – C# Adım Adım Kılavuz](./create-pdf-from-html-c-step-by-step-guide/) Aspose.HTML for .NET kullanarak HTML'den PDF'ye nasıl dönüştüreceğinizi adım adım öğrenin. ### [C#'ta HTML'i Zip Dosyasına Sıkıştırma](./how-to-zip-html-in-c-save-html-to-zip/) +### [C#'ta HTML'i Zip Dosyasına Sıkıştırma – Özel Kaynak İşleyicisi Öğreticisi](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) ### [Stil Verilmiş Metinle HTML Belgesi Oluşturma ve PDF'ye Dışa Aktarma – Tam Kılavuz](./create-html-document-with-styled-text-and-export-to-pdf-full/) ### [HTML'yi ZIP Olarak Kaydet – Tam C# Öğreticisi](./save-html-as-zip-complete-c-tutorial/) Aspose.HTML for .NET kullanarak HTML dosyalarını ZIP arşivine kaydetmeyi adım adım öğrenin. diff --git a/html/turkish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/turkish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..d476123a7 --- /dev/null +++ b/html/turkish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-02-21 +description: C#'ta özel bir kaynak işleyicisi kullanarak HTML'yi zip'lemeyi öğrenin. + Bu rehber ayrıca HTML'yi zip olarak kaydetme, HTML'yi zip'e dönüştürme ve HTML'yi + zip'e kaydetme konularını da kapsar. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: tr +og_description: Özel bir kaynak işleyicisi kullanarak C#'ta HTML'yi zip'leme. Adım + adım kod, açıklamalar ve HTML'yi zip olarak kaydetme ipuçları. +og_title: C#'de HTML Nasıl Sıkıştırılır – Tam Rehber +tags: +- Aspose.HTML +- C# +- ZIP compression +title: C#'ta HTML Nasıl Sıkıştırılır – Özel Kaynak İşleyici Öğreticisi +url: /tr/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +exactly. + +Now produce final output.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML'i C#'ta Zipleme – Özel Kaynak İşleyici Öğreticisi + +Hiç **HTML'i zipleme** .NET uygulamanızdan dosya sistemine dokunmadan nasıl yapılacağını merak ettiniz mi? Yalnız değilsiniz. Birçok geliştirici, bir HTML belgesini kaynakları—görseller, CSS, betikler—ile birlikte tek bir ZIP dosyasında paketleyerek kolay taşıma veya depolama ihtiyacı duyar. + +Bu öğreticide, Aspose.HTML'in `ResourceHandler`'ını kullanarak **HTML'i zip olarak kaydetme**'nin temiz bir yolunu göstereceğiz. Ayrıca **HTML'i zip'e dönüştürme** ve **HTML'i zip'e kaydetme** gibi ilgili konulara da değineceğiz; bu, herhangi bir projeye ekleyebileceğiniz yeniden kullanılabilir bir işleyici. Harici araçlar yok, geçici dosyalar yok—sadece saf bellek içi sihir. + +## Öğrenecekleriniz + +* Bellek içinde bir `HTMLDocument` nasıl oluşturulur. +* Her kaynağı tek bir ZIP arşivine akıtacak **özel kaynak işleyicisi** nasıl uygulanır. +* **HTML'i zip olarak kaydetme** ve bayt dizisini almak için gereken tam kod. +* Büyük görseller veya birden fazla CSS dosyası gibi uç durumları ele almak için ipuçları. +* Visual Studio'ya kopyala‑yapıştır yapabileceğiniz tam, çalıştırılabilir bir örnek. + +> **Önkoşullar** – .NET 6+ (veya .NET Framework 4.6+) ve NuGet üzerinden kurulu Aspose.HTML for .NET kütüphanesine (`Install-Package Aspose.HTML`) ihtiyacınız var. Başka bir bağımlılık yok. + +--- + +## 1. Adım – HTML Belgesini Oluşturma (HTML'i Zipleme) + +İlk olarak ihtiyacımız, sıkıştırmak istediğimiz işaretlemeyi tutan bir `HTMLDocument` örneğidir. Bunu, sürecin geri kalanının tuvali olarak düşünün. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Neden önemli:** `HTMLDocument` kullanarak Aspose.HTML'in CSS ayrıştırmasını, yerleşimini ve yazı tipi çözümlemesini bir tarayıcının yaptığı gibi yapmasını sağlarız. Bu, elde ettiğiniz PNG'nin Chrome veya Edge'de bir kullanıcının gördüğüyle aynı görünmesini garantiler. + +## Convert HTML to Image – Render Seçeneklerini Yapılandırma + +Sonra motorun işaretlemeyi nasıl rasterleştireceğini tanımlıyoruz. İşte **set image width height** ayarladığınız, antialiasing'i etkinleştirdiğiniz ve bir arka plan rengi seçtiğiniz yer. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Pro tip:** `Width` ve `Height` değerlerini atlamanız durumunda Aspose.HTML sayfanın içsel boyutunu kullanır, bu da küçük resimler için çok küçük olabilir. Bu değerleri açıkça ayarlamak, nihai PNG boyutları üzerinde tam kontrol sağlar. + +## Generate PNG from HTML – Yazı Tipi Stillerini Uygula (İsteğe Bağlı) + +Bazen kalın, italik veya bir kombinasyon stiline ihtiyaç duyarsınız. `WebFontStyle` enum'ı, bayrakları bit düzeyinde OR operatörü (`|`) ile birleştirmenize izin verir. Bu adım isteğe bağlıdır ancak özel stil ile **generate PNG from HTML** nasıl yapılır gösterir. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **What’s happening:** `combinedFontStyle.ToString()` `"Bold, Italic"` döndürür ve motor bunu geçerli bir CSS `font-style` değerine çevirir. Sonuç, metnin hem kalın hem de italik göründüğü bir PNG'dir. + +## Save HTML as PNG – Son Render Çağrısı + +Şimdi her şeyi birleştiriyoruz. `Image` renderlayıcı rasterleştirilmiş içeriği diskte bir dosyaya yazar. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Programı çalıştırdığınızda çalışma dizininde `output.png` oluşturulur. Açın ve **render html to png** sonucunu göreceksiniz – beyaz bir kanvas üzerinde keskin, antialiaslı metin, tam olarak 800 × 600 piksel. + + + +> **Expected output:** 24‑px Arial, kalın ve italik “Sample text” metnini gösteren bir PNG dosyası, görüntünün ortasında. HTML dizesini veya `Width`/`Height` değerlerini değiştirirseniz PNG buna göre güncellenir. + +## Convert HTML to Image – Yaygın Varyasyonlar ve Kenar Durumları + +### 1. Uzaktaki Web Sayfasını Render Etme + +Eğer canlı bir URL'den **convert HTML to image** yapmanız gerekiyorsa, sadece URL'yi `HTMLDocument`'e geçirin: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Hedef sitenin programatik erişime (CORS, kimlik doğrulama vb.) izin verdiğinden emin olun. + +### 2. Şeffaf Arka Planlar + +`BackColor = Color.Transparent` ayarlayın ve alfa kanallarını destekleyen bir PNG formatı seçin. Bu, görüntüyü diğer UI öğelerinin üzerine yerleştirmek için kullanışlıdır. + +### 3. Yüksek Çözünürlüklü Çıktı + +Yazdırmaya hazır grafikler için `Width` ve `Height` değerlerini artırın ve aynı zamanda `DPI` ayarlayın: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Büyük Stil Sayfalarını İşleme + +Aspose.HTML, bağlı CSS dosyalarını otomatik olarak indirir. Ağ çağrılarını sınırlamak istiyorsanız, kritik CSS'i doğrudan HTML dizesine gömün veya kaynakları önbelleğe almak için `ResourceLoadingOptions` kullanın. + +## Tam, Çalıştırılabilir Örnek + +Aşağıda, bir konsol uygulamasına kopyalayıp‑yapıştırabileceğiniz tam program yer alıyor. Yukarıda tartışılan tüm adımları, yorumları ve isteğe bağlı ayarlamaları içerir. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Derleyin ve çalıştırın (`dotnet run` .NET CLI kullanıyorsanız). Konsol dosya oluşturulmasını onaylayacak ve yürütülebilir dosyanın yanında `output.png` bulacaksınız. + +## Özet + +Aspose.HTML'i C# içinde kullanarak **render HTML to PNG** yapmak için ihtiyacınız olan her şeyi yeni kapsadık. Belge oluşturma, render seçeneklerini ayarlama, özel yazı tipi stilleri uygulama ve sonunda görüntüyü kaydetme—her adım **why** (neden) önemli olduğu, sadece **how** (nasıl) yazılacağı değil, açıklanmıştır. + +Eğer diğer formatlar için **convert HTML to image** yapmak istiyorsanız, `renderer.Save` içindeki dosya uzantısını `.jpeg` ya da `.bmp` olarak değiştirin ve `ImageSaveOptions`'ı buna göre ayarlayın. Yüzlerce sayfayı toplu işlemek mi istiyorsunuz? Render bloğunu bir `foreach` döngüsü içinde sarın ve her HTML dizesini veya URL'yi besleyin. + +### Sıradaki Adımlar? + +- **Explore PDF generation** – Aspose.HTML benzer seçeneklerle PDF'ye de dışa aktarabilir. +- **Combine multiple pages** – Çok sayfalı bir HTML belgesinin her sayfasını ayrı PNG'lere render edin. +- **Integrate with ASP.NET Core** – PNG'yi doğrudan bir `FileResult` olarak döndürerek anlık ekran görüntüleri alın. + +Ayarlarla denemeler yapmaktan, HTML içeriğini değiştirmekten veya bu kodu bir web servisine entegre etmekten çekinmeyin. Anında **generate PNG from HTML** yapabildiğinizde sınır yoktur. + +Sorularınız veya zor bir kullanım senaryonuz mu var? Aşağıya yorum bırakın, iyi kodlamalar! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/vietnamese/net/html-extensions-and-conversions/_index.md b/html/vietnamese/net/html-extensions-and-conversions/_index.md index 169c7624f..dd6cc1a7e 100644 --- a/html/vietnamese/net/html-extensions-and-conversions/_index.md +++ b/html/vietnamese/net/html-extensions-and-conversions/_index.md @@ -65,6 +65,8 @@ Tìm hiểu cách chuyển đổi HTML sang TIFF bằng Aspose.HTML cho .NET. L Khám phá sức mạnh của Aspose.HTML cho .NET: Chuyển đổi HTML sang XPS dễ dàng. Bao gồm các điều kiện tiên quyết, hướng dẫn từng bước và Câu hỏi thường gặp. ### [Cách Nén HTML thành Zip trong C# – Lưu HTML vào Zip](./how-to-zip-html-in-c-save-html-to-zip/) Hướng dẫn chi tiết cách nén HTML thành tệp Zip bằng C# và Aspose.HTML, kèm ví dụ mã và các tùy chọn cấu hình. +### [Cách Nén HTML trong C# – Hướng Dẫn Trình Xử Lý Tài Nguyên Tùy Chỉnh](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) +Hướng dẫn chi tiết cách nén HTML thành ZIP trong C# bằng trình xử lý tài nguyên tùy chỉnh với Aspose.HTML. ### [Tạo tài liệu HTML với văn bản có kiểu dáng và xuất ra PDF – Hướng dẫn đầy đủ](./create-html-document-with-styled-text-and-export-to-pdf-full/) Hướng dẫn chi tiết cách tạo tài liệu HTML có văn bản định dạng và xuất ra PDF bằng Aspose.HTML cho .NET. ### [Tạo PDF từ HTML – Hướng dẫn từng bước C#](./create-pdf-from-html-c-step-by-step-guide/) diff --git a/html/vietnamese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md b/html/vietnamese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md new file mode 100644 index 000000000..2ceb89795 --- /dev/null +++ b/html/vietnamese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-02-21 +description: Tìm hiểu cách nén HTML thành zip bằng trình xử lý tài nguyên tùy chỉnh + trong C#. Hướng dẫn này cũng bao gồm lưu HTML dưới dạng zip, chuyển đổi HTML sang + zip và lưu HTML thành zip. +draft: false +keywords: +- how to zip html +- custom resource handler +- save html as zip +- convert html to zip +- save html to zip +language: vi +og_description: Cách nén HTML thành zip trong C# bằng trình xử lý tài nguyên tùy chỉnh. + Mã từng bước, giải thích và mẹo để lưu HTML dưới dạng zip. +og_title: Cách Nén HTML trong C# – Hướng Dẫn Toàn Diện +tags: +- Aspose.HTML +- C# +- ZIP compression +title: Cách Nén HTML thành Zip trong C# – Hướng Dẫn Xử Lý Tài Nguyên Tùy Chỉnh +url: /vi/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách Nén HTML thành ZIP trong C# – Hướng Dẫn Xử Lý Tài Nguyên Tùy Chỉnh + +Bạn đã bao giờ tự hỏi **cách nén HTML** trực tiếp từ ứng dụng .NET mà không cần chạm tới hệ thống tệp chưa? Bạn không phải là người duy nhất. Nhiều nhà phát triển cần đóng gói một tài liệu HTML cùng với các tài nguyên của nó—hình ảnh, CSS, script—vào một file ZIP duy nhất để dễ dàng truyền tải hoặc lưu trữ. + +Trong tutorial này, chúng tôi sẽ chỉ cho bạn một cách sạch sẽ để **lưu HTML dưới dạng zip** bằng cách sử dụng `ResourceHandler` của Aspose.HTML. Chúng tôi cũng sẽ đề cập đến các chủ đề liên quan như **chuyển đổi HTML sang zip** và **lưu HTML vào zip** với một handler tái sử dụng mà bạn có thể đưa vào bất kỳ dự án nào. Không cần công cụ bên ngoài, không có file tạm—chỉ toàn bộ quá trình trong bộ nhớ. + +## Những Điều Bạn Sẽ Học + +* Cách tạo một `HTMLDocument` trong bộ nhớ. +* Cách triển khai **custom resource handler** để truyền mọi tài nguyên vào một file ZIP duy nhất. +* Đoạn mã chính xác để **lưu HTML dưới dạng zip** và lấy mảng byte. +* Mẹo xử lý các trường hợp đặc biệt như hình ảnh lớn hoặc nhiều file CSS. +* Một ví dụ hoàn chỉnh, có thể chạy ngay mà bạn có thể sao chép‑dán vào Visual Studio. + +> **Yêu cầu trước** – Bạn cần .NET 6+ (hoặc .NET Framework 4.6+) và thư viện Aspose.HTML for .NET được cài đặt qua NuGet (`Install-Package Aspose.HTML`). Không có phụ thuộc nào khác. + +--- + +## Bước 1 – Tạo Tài Liệu HTML (Cách Nén HTML) + +Điều đầu tiên chúng ta cần là một thể hiện `HTMLDocument` chứa markup mà chúng ta muốn nén. Hãy nghĩ đây là canvas cho phần còn lại của quy trình. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System.IO; + +// Simple HTML string – replace with your own markup or load from a file +string htmlContent = "Sample text
"); +``` + +> **Why this matters:** Bằng cách sử dụng `HTMLDocument` chúng ta để Aspose.HTML xử lý việc phân tích CSS, bố cục, và giải quyết phông chữ chính xác như một trình duyệt. Điều này đảm bảo PNG bạn nhận được trông giống hệt những gì người dùng sẽ thấy trong Chrome hoặc Edge. + +## Convert HTML to Image – Cấu Hình Các Tùy Chọn Render + +Tiếp theo chúng ta định nghĩa cách engine sẽ rasterize markup. Đây là nơi bạn **set image width height**, bật antialiasing, và chọn màu nền. + +```csharp +// Step 2: Set up image rendering options (antialiasing, hinting, background, size) +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + UseAntialiasing = true, // smoother edges for shapes and text + TextOptions = { UseHinting = true }, // clearer glyph shapes on high‑DPI + BackColor = Color.White, // solid white background (transparent also works) + Width = 800, // set image width + Height = 600 // set image height +}; +``` + +> **Pro tip:** Nếu bạn bỏ qua `Width` và `Height`, Aspose.HTML sẽ sử dụng kích thước nội tại của trang, có thể quá nhỏ cho ảnh thu nhỏ. Việc đặt rõ các giá trị này cho bạn kiểm soát hoàn toàn kích thước PNG cuối cùng. + +## Generate PNG from HTML – Áp Dụng Kiểu Font (Tùy Chọn) + +Đôi khi bạn cần chữ đậm, nghiêng, hoặc kết hợp cả hai. Enum `WebFontStyle` cho phép bạn hợp nhất các flag bằng toán tử OR bitwise (`|`). Bước này là tùy chọn nhưng minh họa cách **generate PNG from HTML** với kiểu dáng tùy chỉnh. + +```csharp +// Step 3: Combine desired font styles using the WebFontStyle enum +WebFontStyle combinedFontStyle = WebFontStyle.Bold | WebFontStyle.Italic; + +// Step 4: Apply the combined font style to the document via CSS +htmlDoc.Body.Style.FontStyle = combinedFontStyle.ToString(); // enum → CSS string +``` + +> **What’s happening:** `combinedFontStyle.ToString()` trả về `"Bold, Italic"` mà engine chuyển thành giá trị CSS `font-style` hợp lệ. Kết quả là một PNG trong đó văn bản xuất hiện cả đậm và nghiêng. + +## Save HTML as PNG – Lệnh Render Cuối Cùng + +Bây giờ chúng ta gộp mọi thứ lại. Trình render `Image` ghi nội dung đã rasterize vào một tệp trên đĩa. + +```csharp +// Step 5: Render the HTML document to a PNG image file +using (Image renderer = new Image()) +{ + renderer.Save(htmlDoc, renderingOptions, "output.png"); +} +``` + +Chạy chương trình sẽ tạo `output.png` trong thư mục làm việc. Mở nó lên, và bạn sẽ thấy kết quả **render html to png** – văn bản sắc nét, được antialias, trên nền trắng, đúng 800 × 600 pixel. + + + +> **Expected output:** Một tệp PNG hiển thị “Sample text” với phông Arial 24 px, đậm và nghiêng, căn giữa trong ảnh. Nếu bạn thay đổi chuỗi HTML hoặc các giá trị `Width`/`Height`, PNG sẽ được cập nhật tương ứng. + +## Convert HTML to Image – Các Biến Thể Thông Thường & Trường Hợp Đặc Biệt + +### 1. Render Trang Web Từ Xa + +Nếu bạn cần **convert HTML to image** từ một URL trực tiếp, chỉ cần truyền URL vào `HTMLDocument`: + +```csharp +HTMLDocument remoteDoc = new HTMLDocument("https://example.com"); +renderer.Save(remoteDoc, renderingOptions, "remote.png"); +``` + +Đảm bảo trang mục tiêu cho phép truy cập chương trình (CORS, xác thực, v.v.). + +### 2. Nền Trong Suốt + +Đặt `BackColor = Color.Transparent` và chọn định dạng PNG hỗ trợ kênh alpha. Điều này hữu ích khi bạn muốn đặt ảnh lên các thành phần UI khác. + +### 3. Đầu Ra Độ Phân Giải Cao + +Đối với đồ họa chuẩn in, tăng `Width` và `Height` đồng thời thiết lập `DPI`: + +```csharp +renderingOptions.DpiX = 300; +renderingOptions.DpiY = 300; +renderingOptions.Width = 2400; // 8 × 300 dpi +renderingOptions.Height = 1800; // 6 × 300 dpi +``` + +### 4. Xử Lý Stylesheet Lớn + +Aspose.HTML tự động tải các tệp CSS liên kết. Nếu bạn muốn hạn chế các cuộc gọi mạng, hãy nhúng CSS quan trọng trực tiếp vào chuỗi HTML hoặc sử dụng `ResourceLoadingOptions` để cache tài nguyên. + +## Full, Runnable Example + +Dưới đây là chương trình hoàn chỉnh bạn có thể copy‑paste vào một ứng dụng console. Nó bao gồm tất cả các bước, chú thích, và các tinh chỉnh tùy chọn đã thảo luận ở trên. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +namespace HtmlToPngDemo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Create the HTML document (inline string for demo) + HTMLDocument htmlDoc = new HTMLDocument( + "" + + "Sample text
" + + ""); + + // 2️⃣ Configure rendering options – this is where we **set image width height** + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = { UseHinting = true }, + BackColor = Color.White, + Width = 800, + Height = 600 + }; + + // 3️⃣ (Optional) Apply combined font style – bold + italic + WebFontStyle combinedStyle = WebFontStyle.Bold | WebFontStyle.Italic; + htmlDoc.Body.Style.FontStyle = combinedStyle.ToString(); + + // 4️⃣ Render and **save HTML as PNG** + using (Image renderer = new Image()) + { + renderer.Save(htmlDoc, renderingOptions, "output.png"); + } + + // 5️⃣ Let the user know we’re done + System.Console.WriteLine("✅ PNG generated: output.png"); + } + } +} +``` + +Biên dịch và chạy (`dotnet run` nếu bạn dùng .NET CLI). Console sẽ xác nhận việc tạo tệp, và bạn sẽ tìm thấy `output.png` bên cạnh file thực thi. + +## Wrap‑Up + +Chúng ta vừa mới bao quát mọi thứ bạn cần để **render HTML to PNG** bằng Aspose.HTML trong C#. Từ việc tạo tài liệu, tinh chỉnh các tùy chọn render, áp dụng kiểu font tùy chỉnh, đến cuối cùng là lưu ảnh — mỗi bước đều được giải thích **tại sao** nó quan trọng, không chỉ **cách** gõ nó. + +Nếu bạn muốn **convert HTML to image** sang các định dạng khác, chỉ cần thay đổi phần mở rộng file trong `renderer.Save` thành `.jpeg` hoặc `.bmp` và điều chỉnh `ImageSaveOptions` cho phù hợp. Muốn xử lý hàng chục trang cùng lúc? Đặt khối render trong một vòng lặp `foreach` và cung cấp mỗi chuỗi HTML hoặc URL. + +### What’s Next? + +- **Khám phá tạo PDF** – Aspose.HTML cũng có thể xuất ra PDF với các tùy chọn tương tự. +- **Kết hợp nhiều trang** – Render mỗi trang của tài liệu HTML đa trang thành các PNG riêng biệt. +- **Tích hợp với ASP.NET Core** – Trả về PNG trực tiếp dưới dạng `FileResult` để chụp màn hình ngay lập tức. + +Hãy thoải mái thử nghiệm các cài đặt, thay đổi nội dung HTML, hoặc nhúng đoạn code này vào một dịch vụ web. Khi bạn có thể **generate PNG from HTML** ngay lập tức, không gì là không thể. + +Có câu hỏi hoặc trường hợp sử dụng khó khăn? Để lại bình luận bên dưới, và chúc bạn lập trình vui vẻ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file