From 1102efebfaf439f029fb84fb393f58f2908a85ea Mon Sep 17 00:00:00 2001 From: Muhammad Adil Date: Sat, 21 Feb 2026 11:26:33 +0000 Subject: [PATCH] Add 2 html net tutorials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Categories: html-extensions-and-conversions, rendering-html-documents Source: AI Search API Tutorials: - How to Zip HTML in C# – Custom Resource Handler Tutorial - Render HTML to PNG in C# – Complete Step‑by‑Step Guide Auto-generated by Professionalize.Tutorials Agent --- .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 237 ++++++++++++++++ .../net/rendering-html-documents/_index.md | 5 + .../_index.md | 218 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 236 ++++++++++++++++ .../net/rendering-html-documents/_index.md | 3 + .../_index.md | 216 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 244 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 4 + .../_index.md | 216 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 4 +- .../_index.md | 248 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 2 + .../_index.md | 228 ++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 239 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 4 + .../_index.md | 216 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 5 + .../_index.md | 216 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 38 +-- .../_index.md | 245 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 3 + .../_index.md | 218 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 241 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 2 + .../_index.md | 218 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 22 +- .../_index.md | 240 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 7 +- .../_index.md | 216 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 6 + .../_index.md | 236 ++++++++++++++++ .../net/rendering-html-documents/_index.md | 4 + .../_index.md | 216 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 2 + .../_index.md | 218 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 250 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 3 + .../_index.md | 218 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 252 ++++++++++++++++++ .../net/rendering-html-documents/_index.md | 2 + .../_index.md | 218 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 247 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 3 + .../_index.md | 215 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 239 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 3 + .../_index.md | 216 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 6 +- .../_index.md | 218 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 4 + .../_index.md | 238 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 4 + .../_index.md | 218 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 244 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 3 + .../_index.md | 220 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 238 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 2 + .../_index.md | 218 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 2 + .../_index.md | 218 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 248 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 2 + .../_index.md | 217 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 1 + .../_index.md | 240 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 2 + .../_index.md | 216 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 240 +++++++++++++++++ .../net/rendering-html-documents/_index.md | 2 + .../_index.md | 218 +++++++++++++++ 92 files changed, 10723 insertions(+), 29 deletions(-) create mode 100644 html/arabic/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/arabic/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/chinese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/chinese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/czech/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/czech/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/dutch/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/dutch/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/english/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/french/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/french/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/german/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/german/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/greek/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/greek/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/hindi/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/hindi/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/hongkong/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/hongkong/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/hungarian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/hungarian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/indonesian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/indonesian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/italian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/italian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/japanese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/japanese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/korean/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/korean/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/polish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/polish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/portuguese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/portuguese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/russian/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/russian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/spanish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/spanish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/swedish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/swedish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/thai/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/thai/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/turkish/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/turkish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md create mode 100644 html/vietnamese/net/html-extensions-and-conversions/how-to-zip-html-in-c-custom-resource-handler-tutorial/_index.md create mode 100644 html/vietnamese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md diff --git a/html/arabic/net/html-extensions-and-conversions/_index.md b/html/arabic/net/html-extensions-and-conversions/_index.md index 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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **لماذا هذا مهم:** من خلال إبقاء المستند في الذاكرة نتجنب تأخير القرص ونجعل العملية بأكملها مناسبة لوظائف السحابة أو الخدمات الصغيرة. + +## الخطوة 2 – بناء معالج موارد مخصص (Custom Resource Handler) + +Aspose.HTML يستدعي `ResourceHandler.HandleResource` لكل أصل خارجي يكتشفه (الصور، CSS، الخطوط). من خلال إرجاع نفس `MemoryStream` في كل مرة يمكننا تجميع كل تلك الموارد في حزمة ZIP واحدة. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **نصيحة احترافية:** إذا كنت بحاجة لتحديد حجم ملف ZIP الناتج، يمكنك تغليف `zipStream` في `LimitedStream` وإلقاء استثناء عندما يتجاوز الحد. + +## الخطوة 3 – حفظ المستند كحزمة ZIP (حفظ HTML كـ ZIP) + +الآن نربط كل شيء معًا. نقوم بإنشاء معالجنا، نطلب من Aspose.HTML حفظ المستند بصيغة `SaveFormat.Zip`، وأخيرًا نستخرج البايتات الخام. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +في هذه المرحلة يحتوي `zipBytes` على ملف ZIP صالح تمامًا يمكنك: + +* إرجاعه من Web API (`File(zipBytes, "application/zip", "page.zip")`); +* رفعها إلى Azure Blob Storage; +* إرسالها عبر مقبس (socket) إلى خدمة أخرى. + +## الخطوة 4 – التحقق من الناتج (تحويل HTML إلى ZIP – اختبار سريع) + +تحقق سريع من الصحة هو كتابة البايتات إلى القرص (للتصحيح فقط) وفتح الأرشيف بأي عارض ZIP. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +عند فتح `debug_output.zip` يجب أن ترى: + +* `index.html` (العلامات الأصلية) +* أي صور، ملفات CSS، أو خطوط مرجعية مدمجة بجانبه. + +> **لماذا هذا يعمل:** Aspose.HTML يعتبر ملف HTML الرئيسي هو المورد الأول، ثم يبث كل أصل مرتبط بالترتيب الذي يواجهه. معالجنا يجمعهم جميعًا في نفس `MemoryStream`، ثم تقوم المكتبة بإنهائه كأرشيف ZIP. + +## الخطوة 5 – معالجة الحالات الخاصة الشائعة (أفضل ممارسات حفظ HTML إلى ZIP) + +### ملفات CSS متعددة + +إذا كانت صفحتك ترتبط بعدة أوراق أنماط، سيُضاف كل منها كإدخال منفصل. لا حاجة إلى كود إضافي، لكن قد ترغب في فرض اتفاقية تسمية (مثلاً `styles/style1.css`) لتجنب التعارضات. + +### موارد ثنائية كبيرة + +بالنسبة للصور الضخمة (>10 ميغابايت) فكر في بثها مباشرةً إلى تدفق مدعوم بملف بدلاً من `MemoryStream` النقي. استبدل `MemoryStream` بـ `FileStream` في `MemoryZipHandler` وعدّل `GetResult` وفقًا لذلك. + +### مشاكل الترميز + +Aspose.HTML يحترم مجموعة الأحرف المعلنة في رأس HTML. إذا كنت بحاجة إلى إخراج UTF‑8، تأكد من وجود وسم `` قبل إنشاء `HTMLDocument`. + +## مثال كامل يعمل (حفظ HTML إلى ZIP) + +فيما يلي البرنامج الكامل الذي يمكنك لصقه في تطبيق كونسول وتشغيله كما هو. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**الناتج المتوقع:** +``` +ZIP created – 1234 bytes +``` + +فتح `output.zip` يظهر `index.html` يحتوي على العلامة `

Hello World

`. لم تكن هناك حاجة إلى ملفات إضافية. + +--- + +## الأسئلة المتكررة (FAQs) + +**س: هل يعمل هذا مع عناوين URL خارجية (مثلاً، صور مستضافة على CDN)؟** +ج: نعم. Aspose.HTML سيقوم بتحميل المورد البعيد، ثم يمرره إلى `HandleResource`. فقط كن على علم بتأخير الشبكة ومتطلبات المصادقة المحتملة. + +**س: هل يمكنني تعيين اسم مخصص لملف HTML الرئيسي داخل ZIP؟** +ج: بشكل افتراضي هو `index.html`. لإعادة تسميته، ستحتاج إلى معالجة الـ ZIP بعد الانتهاء من `Save` (مثلاً باستخدام `System.IO.Compression.ZipArchive`). + +**س: ماذا لو احتجت لضغط عدة مستندات HTML معًا؟** +ج: أنشئ `HTMLDocument` منفصل لكل صفحة واستدعِ `Save` على نفس `MemoryZipHandler`. سيستمر المعالج في إلحاق الموارد، مما ينتج ZIP متعدد الصفحات. + +## الخلاصة + +أصبح لديك الآن وصفة قوية لـ **كيفية ضغط HTML** تستفيد من **معالج موارد مخصص** لـ **حفظ HTML كملف zip**، **تحويل HTML إلى zip**، و **حفظ HTML إلى zip**—كل ذلك دون لمس نظام الملفات. النهج خفيف الوزن، بالكامل في الذاكرة، ويتناسب جيدًا مع Web APIs، وظائف الخلفية، أو أي خدمة .NET تحتاج إلى إرسال حزم HTML في الوقت الفعلي. + +هل أنت مستعد للخطوة التالية؟ جرّب توسيع المعالج لضغط الناتج أكثر باستخدام `System.IO.Compression.GZipStream`، أو دمجه في وحدة تحكم ASP.NET Core تُعيد الـ ZIP مباشرةً إلى المتصفح. السماء هي الحد، والآن لديك الأساس للبناء عليه. + +برمجة سعيدة! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/arabic/net/rendering-html-documents/_index.md b/html/arabic/net/rendering-html-documents/_index.md index 7d8baa5d7..f7ac83db6 100644 --- a/html/arabic/net/rendering-html-documents/_index.md +++ b/html/arabic/net/rendering-html-documents/_index.md @@ -45,11 +45,13 @@ url: /ar/net/rendering-html-documents/ ### [كيفية تحويل HTML إلى PNG – دليل C# كامل](./how-to-render-html-as-png-complete-c-guide/) تعلم خطوة بخطوة كيفية تحويل مستندات HTML إلى صور PNG باستخدام Aspose.HTML وC# في هذا الدليل الشامل. + ### [كيفية استخدام Aspose لتحويل HTML إلى PNG – دليل خطوة بخطوة](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) تعلم كيفية تحويل مستندات HTML إلى صور PNG باستخدام Aspose.HTML في .NET خطوة بخطوة. ### [إنشاء PNG من HTML – دليل كامل للتصيير باستخدام C#](./create-png-from-html-full-c-rendering-guide/) تعلم كيفية تحويل صفحات HTML إلى صور PNG باستخدام Aspose.HTML في دليل شامل يوضح كل خطوة في C#. + ### [عرض EPUB بتنسيق XPS في .NET باستخدام Aspose.HTML](./render-epub-as-xps/) تعرف على كيفية إنشاء مستندات HTML وعرضها باستخدام Aspose.HTML لـ .NET في هذا البرنامج التعليمي الشامل. انغمس في عالم معالجة HTML وكشط الويب والمزيد. @@ -68,6 +70,9 @@ url: /ar/net/rendering-html-documents/ ### [كيفية تحويل HTML إلى PNG باستخدام Aspose – دليل كامل](./how-to-render-html-to-png-with-aspose-complete-guide/) تعلم خطوة بخطوة كيفية تحويل مستندات HTML إلى صور PNG باستخدام Aspose.HTML في .NET. +### [تحويل HTML إلى PNG في C# – دليل كامل خطوة بخطوة](./render-html-to-png-in-c-complete-step-by-step-guide/) +تعلم كيفية تحويل مستندات HTML إلى صور PNG باستخدام Aspose.HTML في C# خطوة بخطوة. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/arabic/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/arabic/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..be99c3e65 --- /dev/null +++ b/html/arabic/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-02-21 +description: قم بتحويل HTML إلى PNG بسرعة باستخدام Aspose.HTML. تعلّم كيفية تحويل + HTML إلى صورة، وتحديد عرض وارتفاع الصورة، وحفظ HTML كملف PNG ببضع أسطر من C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: ar +og_description: تحويل HTML إلى PNG باستخدام Aspose.HTML. يوضح هذا الدليل كيفية تحويل + HTML إلى صورة، وتحديد عرض وارتفاع الصورة، وحفظ HTML كملف PNG في C#. +og_title: تحويل HTML إلى PNG في C# – دليل كامل +tags: +- Aspose.HTML +- C# +- Image Rendering +title: تحويل HTML إلى PNG في C# – دليل كامل خطوة بخطوة +url: /ar/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +}} + +Make sure to keep them. + +Now produce final output.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG – دليل خطوة بخطوة كامل + +هل احتجت يوماً إلى **render HTML to PNG** لكنك لم تكن متأكدًا من المكتبة التي تختارها أو كيفية تكوين الإخراج؟ لست وحدك. يواجه العديد من المطورين نفس المشكلة عندما يحاولون *convert HTML to image* لصور مصغرة للبريد الإلكتروني، لقطات تقارير، أو اختبار واجهة المستخدم الآلي. + +في هذا الدرس سنستعرض مثالًا عمليًا جاهزًا للتنفيذ يوضح لك كيفية **save HTML as PNG**، التحكم بأبعاد الصورة، وضبط جودة التصيير—كل ذلك بضع أسطر باستخدام Aspose.HTML for .NET. في النهاية ستحصل على مقتطف قابل لإعادة الاستخدام يمكنك إدراجه في أي مشروع C#. + +## ما ستحتاجه + +- **.NET 6.0 أو أحدث** (API يعمل مع .NET Framework و .NET Core و .NET 5+) +- **حزمة NuGet Aspose.HTML for .NET** (`Aspose.Html`) المثبتة في مشروعك. +- فهم أساسي لصياغة C# — لا شيء معقد مطلوب. +- مجلد إخراج حيث سيتم كتابة ملف PNG المُولد. + +هذا كل شيء. لا تحتاج إلى SDK إضافية، ولا ملفات تنفيذية خارجية، مجرد مرجع NuGet واحد. + +## render HTML to PNG – إعداد المستند + +أول شيء نقوم به هو إنشاء كائن `HTMLDocument` يحتوي على العلامات التي نريد تحويلها إلى صورة نقطية. يمكنك تحميل HTML من سلسلة نصية، ملف، أو حتى URL. للتوضيح سنبدأ بسلسلة نصية بسيطة داخلية. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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 بكسل. + +![مثال ناتج render html to png](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Why this matters:** 通过将文档保存在内存中,我们避免了磁盘延迟,使整个操作适用于云函数或微服务。 + +## 第二步 – 构建自定义资源处理程序(Custom Resource Handler) + +Aspose.HTML 会对它发现的每个外部资源(图片、CSS、字体)调用 `ResourceHandler.HandleResource`。每次返回同一个 `MemoryStream`,即可将所有资源汇聚到一个 ZIP 包中。 + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro tip:** 如果需要限制生成的 ZIP 大小,可以将 `zipStream` 包装在 `LimitedStream` 中,并在超出限制时抛出异常。 + +## 第三步 – 将文档保存为 ZIP 包(Save HTML as ZIP) + +现在把所有部件组合起来。实例化我们的处理程序,指示 Aspose.HTML 使用 `SaveFormat.Zip` 保存文档,最后获取原始字节。 + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +此时 `zipBytes` 包含一个完全有效的 ZIP 文件,你可以: + +* 从 Web API 返回 (`File(zipBytes, "application/zip", "page.zip")`); +* 上传到 Azure Blob Storage; +* 通过套接字发送给其他服务。 + +## 第四步 – 验证输出(Convert HTML to ZIP – 快速测试) + +一个快速的完整性检查是将字节写入磁盘(仅用于调试),然后使用任意 ZIP 查看器打开归档。 + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +打开 `debug_output.zip` 时应看到: + +* `index.html`(原始标记) +* 所有引用的图片、CSS 文件或字体均已嵌入其中。 + +> **Why this works:** Aspose.HTML 将主 HTML 文件视为第一个资源,然后按发现顺序流式写入每个链接的资产。我们的处理程序将它们全部聚合到同一个 `MemoryStream`,库随后将其最终生成 ZIP 归档。 + +## 第五步 – 处理常见边缘情况(Save HTML to ZIP 最佳实践) + +### 多个 CSS 文件 + +如果页面链接了多个样式表,每个都会作为单独的条目添加。无需额外代码,但建议使用命名约定(例如 `styles/style1.css`)以避免冲突。 + +### 大型二进制资源 + +对于体积巨大的图片(>10 MB),考虑直接流式写入基于文件的流,而不是纯 `MemoryStream`。在 `MemoryZipHandler` 中将 `MemoryStream` 替换为 `FileStream`,并相应调整 `GetResult`。 + +### 编码问题 + +Aspose.HTML 会遵循 HTML 头部声明的字符集。如果需要 UTF‑8 输出,请确保在创建 `HTMLDocument` 之前已包含 `` 标签。 + +## 完整可运行示例(Save HTML to ZIP) + +下面是完整的程序代码,可直接粘贴到控制台应用并运行。 + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Expected output:** +``` +ZIP created – 1234 bytes +``` + +打开 `output.zip` 可看到 `index.html` 包含 `

Hello World

` 标记。无需额外文件。 + +--- + +## 常见问题 (FAQs) + +**Q: Does this work with external URLs (e.g., images hosted on a CDN)?** +A: Yes. Aspose.HTML will download the remote resource, then pass it to `HandleResource`. Just be aware of network latency and possible authentication requirements. + +**Q: Can I set a custom name for the main HTML file inside the ZIP?** +A: By default it’s `index.html`. To rename it, you’d need to post‑process the ZIP (e.g., using `System.IO.Compression.ZipArchive`) after `Save` completes. + +**Q: What if I need to zip multiple HTML documents together?** +A: Create a separate `HTMLDocument` for each page and call `Save` on the same `MemoryZipHandler`. The handler will keep appending resources, resulting in a multi‑page ZIP. + +## 结论 + +你现在拥有了一套完整的 **how to zip HTML** 方案,利用 **custom resource handler** 实现 **save HTML as zip**、**convert HTML to zip** 与 **save HTML to zip**,全程不触及文件系统。该方法轻量、完全基于内存,适用于 Web API、后台任务或任何需要即时发送 HTML 包的 .NET 服务。 + +准备好下一步了吗?尝试使用 `System.IO.Compression.GZipStream` 进一步压缩输出,或将其集成到 ASP.NET Core 控制器中直接返回 ZIP 给浏览器。可能性无限,而你已经拥有了构建的基石。 + +祝编码愉快! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/chinese/net/rendering-html-documents/_index.md b/html/chinese/net/rendering-html-documents/_index.md index 320ef98cc..c2ad627f5 100644 --- a/html/chinese/net/rendering-html-documents/_index.md +++ b/html/chinese/net/rendering-html-documents/_index.md @@ -69,6 +69,9 @@ Aspose.HTML for .NET 凭借其丰富的功能、出色的文档和活跃的社 ### [使用 Aspose.HTML 在 .NET 中从 HTML 创建 PNG – 完整 C# 渲染指南](./create-png-from-html-full-c-rendering-guide/) 完整的 C# 示例,展示如何使用 Aspose.HTML 将 HTML 渲染为 PNG,涵盖所有关键步骤和最佳实践。 +### [在 C# 中使用 Aspose.HTML 将 HTML 渲染为 PNG – 完整分步指南](./render-html-to-png-in-c-complete-step-by-step-guide/) +学习如何使用 Aspose.HTML for .NET 在 C# 中将 HTML 渲染为 PNG,提供完整的分步示例和最佳实践。 + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/chinese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/chinese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..e251e9696 --- /dev/null +++ b/html/chinese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-02-21 +description: 使用 Aspose.HTML 快速将 HTML 渲染为 PNG。了解如何将 HTML 转换为图像、设置图像宽高,以及在几行 C# 代码中将 + HTML 保存为 PNG。 +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: zh +og_description: 使用 Aspose.HTML 将 HTML 渲染为 PNG。本教程展示了如何将 HTML 转换为图像、设置图像宽高,以及在 C# 中将 + HTML 保存为 PNG。 +og_title: 在 C# 中将 HTML 渲染为 PNG – 完整指南 +tags: +- Aspose.HTML +- C# +- Image Rendering +title: 在 C# 中将 HTML 渲染为 PNG – 完整的分步指南 +url: /zh/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG – 完整分步指南 + +是否曾经需要**将 HTML 渲染为 PNG**,却不确定该选哪个库或如何配置输出?你并不孤单。许多开发者在尝试*将 HTML 转换为图像*用于电子邮件缩略图、报告快照或自动化 UI 测试时,都会碰到同样的难题。 + +在本教程中,我们将通过一个实用、可直接运行的示例,展示如何**将 HTML 保存为 PNG**、控制图像尺寸以及微调渲染质量——只需几行代码,使用 Aspose.HTML for .NET。完成后,你将拥有一个可在任何 C# 项目中复用的代码片段。 + +## 所需环境 + +在开始之前,请确保你具备以下条件: + +- **.NET 6.0 或更高**(该 API 同时支持 .NET Framework、.NET Core 与 .NET 5+) +- 项目中已安装 **Aspose.HTML for .NET** NuGet 包(`Aspose.Html`) +- 对 C# 语法有基本了解——不需要任何高级技巧 +- 一个用于写入生成 PNG 的输出文件夹 + +就这些。无需额外 SDK、外部二进制文件,只需一个 NuGet 引用。 + +## Render HTML to PNG – 设置文档 + +首先我们创建一个 `HTMLDocument` 对象,用来保存需要光栅化的标记。可以从字符串、文件或 URL 加载 HTML。为保持清晰,这里使用一个简单的内联字符串。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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 像素。 + +![渲染 html 为 png 输出示例](output.png) + +> **预期输出:** 一个 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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Why this matters:** Tím, že dokument držíme v paměti, vyhneme se latenci disku a celá operace je vhodná pro cloudové funkce nebo mikro‑služby. + +## Krok 2 – Vytvořte vlastní Resource Handler (Custom Resource Handler) + +Aspose.HTML volá `ResourceHandler.HandleResource` pro každý externí asset, který objeví (obrázky, CSS, fonty). Vrácením stejného `MemoryStream` pokaždé můžeme všechny tyto zdroje nasměrovat do jediného ZIP balíčku. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro tip:** Pokud potřebujete omezit velikost výsledného ZIP, můžete obalit `zipStream` do `LimitedStream` a vyhodit výjimku, když limit překročíte. + +## Krok 3 – Uložte dokument jako ZIP balíček (Save HTML as ZIP) + +Nyní vše spojíme. Vytvoříme náš handler, požádáme Aspose.HTML, aby uložil dokument v `SaveFormat.Zip`, a nakonec získáme surové bajty. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +V tomto okamžiku `zipBytes` obsahuje naprosto platný ZIP soubor, který můžete: + +* Vrátit z Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Nahrát do Azure Blob Storage; +* Poslat přes socket do jiné služby. + +## Krok 4 – Ověřte výstup (Convert HTML to ZIP – Quick Test) + +Rychlá kontrola je zapsat bajty na disk (jen pro ladění) a otevřít archiv v libovolném ZIP prohlížeči. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +Když otevřete `debug_output.zip`, měli byste vidět: + +* `index.html` (původní značkování) +* Všechny odkazované obrázky, CSS soubory nebo fonty vložené vedle něj. + +> **Why this works:** Aspose.HTML považuje hlavní HTML soubor za první zdroj, pak streamuje každý propojený asset v pořadí, v jakém jej narazí. Náš handler je všechny agreguje do stejného `MemoryStream`, který knihovna následně dokončí jako ZIP archiv. + +## Krok 5 – Řešení běžných okrajových případů (Save HTML to ZIP Best Practices) + +### Více CSS souborů + +Pokud stránka odkazuje na několik stylových listů, každý bude přidán jako samostatná položka. Žádný další kód není potřeba, ale můžete chtít vynutit pojmenovací konvenci (např. `styles/style1.css`), aby nedošlo ke kolizím. + +### Velké binární zdroje + +U masivních obrázků (>10 MB) zvažte streamování přímo do souborově podloženého streamu místo čistého `MemoryStream`. Nahraďte `MemoryStream` za `FileStream` v `MemoryZipHandler` a upravte `GetResult` podle toho. + +### Problémy s kódováním + +Aspose.HTML respektuje charset deklarovaný v hlavičce HTML. Pokud potřebujete výstup v UTF‑8, ujistěte se, že je před vytvořením `HTMLDocument` přítomna značka ``. + +## Kompletní funkční příklad (Save HTML to ZIP) + +Níže je kompletní program, který můžete vložit do konzolové aplikace a spustit tak, jak je. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Očekávaný výstup:** +``` +ZIP created – 1234 bytes +``` + +Otevřením `output.zip` uvidíte `index.html` obsahující značkování `

Hello World

`. Nebyly potřeba žádné další soubory. + +--- + +## Často kladené otázky (FAQs) + +**Q: Funguje to i s externími URL (např. obrázky hostované na CDN)?** +A: Ano. Aspose.HTML stáhne vzdálený zdroj a poté jej předá `HandleResource`. Buďte si vědomi latence sítě a možných požadavků na autentizaci. + +**Q: Můžu nastavit vlastní název hlavního HTML souboru uvnitř ZIP?** +A: Ve výchozím nastavení je to `index.html`. Pro přejmenování budete muset po dokončení `Save` provést post‑processing ZIP (např. pomocí `System.IO.Compression.ZipArchive`). + +**Q: Co když potřebuji zipovat více HTML dokumentů dohromady?** +A: Vytvořte samostatný `HTMLDocument` pro každou stránku a zavolejte `Save` na stejném `MemoryZipHandler`. Handler bude přidávat zdroje, což povede k vícestránkovému ZIP. + +--- + +## Závěr + +Nyní máte solidní **jak zipovat HTML** recept, který využívá **custom resource handler** k **save HTML as zip**, **convert HTML to zip** a **save HTML to zip** — vše bez dotyku souborového systému. Přístup je lehký, zcela v paměti a skvěle se hodí do webových API, background jobů nebo jakékoli .NET služby, která potřebuje na‑letě odesílat HTML balíčky. + +Jste připraveni na další krok? Zkuste rozšířit handler o další kompresi pomocí `System.IO.Compression.GZipStream`, nebo jej integrovat do ASP.NET Core controlleru, který vrací ZIP přímo prohlížeči. Možnosti jsou neomezené a nyní máte pevný základ, na kterém můžete stavět. + +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/czech/net/rendering-html-documents/_index.md b/html/czech/net/rendering-html-documents/_index.md index 5e42f8047..bb3a127e4 100644 --- a/html/czech/net/rendering-html-documents/_index.md +++ b/html/czech/net/rendering-html-documents/_index.md @@ -66,9 +66,13 @@ Naučte se, jak pomocí Aspose.HTML v .NET převést HTML do PNG pomocí podrobn ### [Jak vykreslit HTML do PNG pomocí Aspose – Kompletní průvodce](./how-to-render-html-to-png-with-aspose-complete-guide/) Kompletní návod, jak pomocí Aspose.HTML v .NET převést HTML soubory do PNG s podrobnými kroky a tipy. + ### [Vytvořte PNG z HTML – Kompletní průvodce renderováním v C#](./create-png-from-html-full-c-rendering-guide/) Naučte se, jak pomocí Aspose.HTML pro .NET převést HTML do PNG pomocí kompletního C# průvodce. +### [Renderujte HTML do PNG v C# – Kompletní průvodce krok za krokem](./render-html-to-png-in-c-complete-step-by-step-guide/) +Kompletní krok‑za‑krokem návod v C#, jak s Aspose.HTML převést HTML soubory do PNG formátu. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/czech/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/czech/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..c28c472bc --- /dev/null +++ b/html/czech/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-02-21 +description: Rychle renderujte HTML do PNG pomocí Aspose.HTML. Naučte se, jak převést + HTML na obrázek, nastavit šířku a výšku obrázku a uložit HTML jako PNG v několika + řádcích C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: cs +og_description: Vykreslete HTML do PNG pomocí Aspose.HTML. Tento tutoriál ukazuje, + jak převést HTML na obrázek, nastavit šířku a výšku obrázku a uložit HTML jako PNG + v C#. +og_title: Vykreslení HTML do PNG v C# – Kompletní průvodce +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Vykreslení HTML do PNG v C# – Kompletní průvodce krok za krokem +url: /cs/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG – Kompletní krok‑za‑krokem průvodce + +Už jste někdy potřebovali **render HTML to PNG**, ale nebyli jste si jisti, kterou knihovnu zvolit nebo jak nakonfigurovat výstup? Nejste v tom sami. Mnoho vývojářů narazí na stejný problém, když se snaží *convert HTML to image* pro náhledy e‑mailů, snímky zpráv nebo automatizované testování UI. + +V tomto tutoriálu vás provedeme praktickým, připraveným k spuštění příkladem, který vám ukáže, jak **save HTML as PNG**, ovládat rozměry obrázku a doladit kvalitu renderování — vše pomocí několika řádků s Aspose.HTML for .NET. Na konci budete mít znovupoužitelný úryvek, který můžete vložit do libovolného projektu C#. + +## Co budete potřebovat + +- **.NET 6.0 nebo novější** (API funguje s .NET Framework, .NET Core a .NET 5+) +- **Aspose.HTML for .NET** NuGet balíček (`Aspose.Html`) nainstalovaný ve vašem projektu. +- Základní znalost syntaxe C# — nic složitého není potřeba. +- Výstupní složka, kam bude vygenerovaný PNG uložen. + +A to je vše. Žádné extra SDK, žádné externí binární soubory, jen jediná reference na NuGet. + +## Render HTML do PNG – Nastavení dokumentu + +Prvním krokem je vytvořit objekt `HTMLDocument`, který obsahuje značkování, které chceme rasterizovat. HTML můžete načíst ze řetězce, souboru nebo dokonce z URL. Pro přehlednost začneme jednoduchým vloženým řetězcem. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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ů. + +![render html to png output example](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Waarom dit belangrijk is:** Door het document in het geheugen te houden vermijden we schijflatentie en maken we de hele bewerking geschikt voor cloud‑functies of micro‑services. + +## Stap 2 – Bouw een Custom Resource Handler (Custom Resource Handler) + +Aspose.HTML roept `ResourceHandler.HandleResource` aan voor elke externe asset die het ontdekt (afbeeldingen, CSS, fonts). Door elke keer dezelfde `MemoryStream` terug te geven, kunnen we al die bronnen in één ZIP‑pakket bundelen. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro tip:** Als je de grootte van de resulterende ZIP wilt beperken, kun je `zipStream` omhullen met een `LimitedStream` en een uitzondering gooien wanneer de limiet wordt overschreden. + +## Stap 3 – Sla het document op als ZIP‑pakket (Save HTML as ZIP) + +Nu koppelen we alles samen. We instantieren onze handler, vragen Aspose.HTML om het document op te slaan in `SaveFormat.Zip`, en halen tenslotte de ruwe bytes op. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +Op dit moment bevat `zipBytes` een perfect geldig ZIP‑bestand dat je kunt: + +* Retourneren vanuit een Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Uploaden naar Azure Blob Storage; +* Versturen via een socket naar een andere service. + +## Stap 4 – Verifieer de output (Convert HTML to ZIP – Quick Test) + +Een snelle sanity‑check is om de bytes naar schijf te schrijven (alleen voor debugging) en het archief te openen met een willekeurige ZIP‑viewer. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +Wanneer je `debug_output.zip` opent, zou je moeten zien: + +* `index.html` (de oorspronkelijke markup) +* Alle verwezen afbeeldingen, CSS‑bestanden of fonts die ernaast zijn ingebed. + +> **Waarom dit werkt:** Aspose.HTML behandelt het hoofd‑HTML‑bestand als de eerste resource, waarna het elke gekoppelde asset streamt in de volgorde waarin het ze tegenkomt. Onze handler verzamelt ze allemaal in dezelfde `MemoryStream`, die de bibliotheek vervolgens finaliseert als een ZIP‑archief. + +## Stap 5 – Veelvoorkomende randgevallen afhandelen (Save HTML to ZIP Best Practices) + +### Meerdere CSS‑bestanden + +Als je pagina naar verschillende style sheets linkt, wordt elk toegevoegd als een apart item. Er is geen extra code nodig, maar je wilt misschien een naamgevingsconventie afdwingen (bijv. `styles/style1.css`) om conflicten te vermijden. + +### Grote binaire resources + +Voor enorme afbeeldingen (>10 MB) overweeg je ze direct naar een file‑backed stream te streamen in plaats van een pure `MemoryStream`. Vervang `MemoryStream` door een `FileStream` in `MemoryZipHandler` en pas `GetResult` dienovereenkomstig aan. + +### Encoding‑problemen + +Aspose.HTML respecteert de charset die in de HTML‑header is gedeclareerd. Als je UTF‑8 output nodig hebt, zorg er dan voor dat de ``‑tag aanwezig is voordat je de `HTMLDocument` maakt. + +## Volledig werkend voorbeeld (Save HTML to ZIP) + +Hieronder staat het complete programma dat je kunt plakken in een console‑applicatie en direct kunt uitvoeren. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Verwachte output:** +``` +ZIP created – 1234 bytes +``` + +Het openen van `output.zip` toont `index.html` met de `

Hello World

`‑markup. Er waren geen extra bestanden nodig. + +--- + +## Veelgestelde vragen (FAQs) + +**Q: Werkt dit met externe URL’s (bijv. afbeeldingen gehost op een CDN)?** +A: Ja. Aspose.HTML downloadt de externe resource en geeft deze vervolgens door aan `HandleResource`. Houd rekening met netwerklatentie en eventuele authenticatie‑vereisten. + +**Q: Kan ik een aangepaste naam instellen voor het hoofd‑HTML‑bestand binnen de ZIP?** +A: Standaard is dit `index.html`. Om het te hernoemen, moet je de ZIP na het `Save`‑proces post‑processen (bijv. met `System.IO.Compression.ZipArchive`). + +**Q: Wat als ik meerdere HTML‑documenten tegelijk wil zippen?** +A: Maak een aparte `HTMLDocument` voor elke pagina en roep `Save` aan op dezelfde `MemoryZipHandler`. De handler blijft resources toevoegen, waardoor je een multi‑page ZIP krijgt. + +--- + +## Conclusie + +Je beschikt nu over een solide **how to zip HTML**‑recept dat een **custom resource handler** gebruikt om **HTML op te slaan als zip**, **convert HTML to zip** en **save HTML to zip** uit te voeren — alles zonder het bestandssysteem aan te raken. De aanpak is lichtgewicht, volledig in‑memory, en past perfect in web‑API’s, achtergrondtaken of elke .NET‑service die HTML‑bundels on‑the‑fly moet leveren. + +Klaar voor de volgende stap? Probeer de handler uit te breiden met extra compressie via `System.IO.Compression.GZipStream`, of integreer hem in een ASP.NET Core‑controller die de ZIP direct naar de browser retourneert. De mogelijkheden zijn eindeloos, en nu heb je de basis om verder op te bouwen. + +Happy coding! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/dutch/net/rendering-html-documents/_index.md b/html/dutch/net/rendering-html-documents/_index.md index 088e7bab1..965ae260c 100644 --- a/html/dutch/net/rendering-html-documents/_index.md +++ b/html/dutch/net/rendering-html-documents/_index.md @@ -60,6 +60,8 @@ Leer hoe u met Aspose.HTML HTML naar PNG kunt renderen met een duidelijke stap Leer stap voor stap hoe u HTML naar PNG converteert met Aspose.HTML in deze volledige gids. ### [PNG maken vanuit HTML – Volledige C# Renderinggids](./create-png-from-html-full-c-rendering-guide/) Leer hoe u met Aspose.HTML voor .NET HTML naar PNG converteert met een volledige C#-renderinggids. +### [HTML naar PNG renderen in C# – Complete stapsgewijze gids](./render-html-to-png-in-c-complete-step-by-step-guide/) +Leer stap voor stap hoe u HTML naar PNG rendert met C# en Aspose.HTML in deze volledige gids. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/dutch/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/dutch/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..0fb42cffa --- /dev/null +++ b/html/dutch/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,228 @@ +--- +category: general +date: 2026-02-21 +description: Render HTML snel naar PNG met Aspose.HTML. Leer hoe je HTML naar een + afbeelding converteert, de breedte en hoogte van de afbeelding instelt, en HTML + opslaat als PNG in een paar regels C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: nl +og_description: Render HTML naar PNG met Aspose.HTML. Deze tutorial laat zien hoe + je HTML naar afbeelding converteert, de breedte en hoogte van de afbeelding instelt, + en HTML opslaat als PNG in C#. +og_title: HTML renderen naar PNG in C# – Complete gids +tags: +- Aspose.HTML +- C# +- Image Rendering +title: HTML renderen naar PNG in C# – Complete stap‑voor‑stap gids +url: /nl/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +!" + +Translate. + +"Heb je vragen of een lastig gebruiksgeval? Laat een reactie achter hieronder, en happy coding!" + +Then closing shortcodes. + +Make sure to keep all shortcodes unchanged. + +Now produce final output with everything. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML naar PNG renderen – Complete stapsgewijze gids + +Heb je ooit **HTML naar PNG renderen** moeten doen, maar wist je niet welke bibliotheek je moest kiezen of hoe je de output moet configureren? Je bent niet de enige. Veel ontwikkelaars lopen tegen dezelfde muur aan wanneer ze proberen *HTML naar afbeelding te converteren* voor e‑mail‑miniaturen, rapport‑snapshots of geautomatiseerd UI‑testen. + +In deze tutorial lopen we door een praktisch, kant‑klaar voorbeeld dat laat zien hoe je **HTML als PNG kunt opslaan**, de afbeeldingsafmetingen kunt regelen en de renderkwaliteit kunt aanpassen — allemaal met een handvol regels code met Aspose.HTML voor .NET. Aan het einde heb je een herbruikbare snippet die je in elk C#‑project kunt plaatsen. + +## Wat je nodig hebt + +- **.NET 6.0 of later** (de API werkt met .NET Framework, .NET Core en .NET 5+) +- **Aspose.HTML for .NET** NuGet‑pakket (`Aspose.Html`) geïnstalleerd in je project. +- Een basisbegrip van C#‑syntaxis — niets ingewikkelds vereist. +- Een output‑map waar de gegenereerde PNG wordt weggeschreven. + +Dat is alles. Geen extra SDK's, geen externe binaries, alleen een enkele NuGet‑referentie. + +## HTML naar PNG renderen – Document instellen + +Het eerste wat we doen is een `HTMLDocument`‑object aanmaken dat de markup bevat die we willen rasteren. Je kunt HTML laden vanuit een string, een bestand of zelfs een URL. Voor de duidelijkheid beginnen we met een eenvoudige inline‑string. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![render html to png output example](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Why this matters:** By keeping the document in memory we avoid disk latency and make the whole operation suitable for cloud functions or micro‑services. + +## Step 2 – Build a Custom Resource Handler (Custom Resource Handler) + +Aspose.HTML calls `ResourceHandler.HandleResource` for every external asset it discovers (images, CSS, fonts). By returning the same `MemoryStream` each time we can funnel all those resources into a single ZIP package. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro tip:** If you need to limit the size of the resulting ZIP, you can wrap `zipStream` in a `LimitedStream` and throw when the limit is exceeded. + +## Step 3 – Save the Document as a ZIP Package (Save HTML as ZIP) + +Now we tie everything together. We instantiate our handler, ask Aspose.HTML to save the document in `SaveFormat.Zip`, and finally pull the raw bytes. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +At this point `zipBytes` contains a perfectly valid ZIP file that you can: + +* Return from a Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Upload to Azure Blob Storage; +* Send over a socket to another service. + +## Step 4 – Verify the Output (Convert HTML to ZIP – Quick Test) + +A quick sanity check is to write the bytes to disk (just for debugging) and open the archive with any ZIP viewer. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +When you open `debug_output.zip` you should see: + +* `index.html` (the original markup) +* Any referenced images, CSS files, or fonts embedded alongside it. + +> **Why this works:** Aspose.HTML treats the main HTML file as the first resource, then streams each linked asset in the order it encounters them. Our handler aggregates them all into the same `MemoryStream`, which the library then finalizes as a ZIP archive. + +## Step 5 – Handling Common Edge Cases (Save HTML to ZIP Best Practices) + +### Multiple CSS Files + +If your page links to several style sheets, each will be added as a separate entry. No extra code is needed, but you might want to enforce a naming convention (e.g., `styles/style1.css`) to avoid clashes. + +### Large Binary Resources + +For massive images (>10 MB) consider streaming them directly to a file-backed stream instead of a pure `MemoryStream`. Replace `MemoryStream` with a `FileStream` in `MemoryZipHandler` and adjust `GetResult` accordingly. + +### Encoding Issues + +Aspose.HTML respects the charset declared in the HTML header. If you need UTF‑8 output, make sure the `` tag is present before you create the `HTMLDocument`. + +## Full Working Example (Save HTML to ZIP) + +Below is the complete program you can paste into a console app and run as‑is. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Expected output:** +``` +ZIP created – 1234 bytes +``` + +Opening `output.zip` shows `index.html` containing the `

Hello World

` markup. No extra files were required. + +--- + +## Frequently Asked Questions (FAQs) + +**Q: Does this work with external URLs (e.g., images hosted on a CDN)?** +A: Yes. Aspose.HTML will download the remote resource, then pass it to `HandleResource`. Just be aware of network latency and possible authentication requirements. + +**Q: Can I set a custom name for the main HTML file inside the ZIP?** +A: By default it’s `index.html`. To rename it, you’d need to post‑process the ZIP (e.g., using `System.IO.Compression.ZipArchive`) after `Save` completes. + +**Q: What if I need to zip multiple HTML documents together?** +A: Create a separate `HTMLDocument` for each page and call `Save` on the same `MemoryZipHandler`. The handler will keep appending resources, resulting in a multi‑page ZIP. + +--- + +## Conclusion + +You now have a solid, **how to zip HTML** recipe that leverages a **custom resource handler** to **save HTML as zip**, **convert HTML to zip**, and **save HTML to zip**—all without touching the file system. The approach is lightweight, fully in‑memory, and fits nicely into web APIs, background jobs, or any .NET service that needs to ship HTML bundles on the fly. + +Ready for the next step? Try extending the handler to compress the output further with `System.IO.Compression.GZipStream`, or integrate it into an ASP.NET Core controller that returns the ZIP directly to the browser. The sky’s the limit, and now you’ve got the foundation to build on. + +Happy coding! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/english/net/rendering-html-documents/_index.md b/html/english/net/rendering-html-documents/_index.md index e7f281cce..0b013a31c 100644 --- a/html/english/net/rendering-html-documents/_index.md +++ b/html/english/net/rendering-html-documents/_index.md @@ -42,6 +42,10 @@ Now that you have Aspose.HTML for .NET set up, it’s time to explore the tutori ### [Render HTML as PNG in .NET with Aspose.HTML](./render-html-as-png/) Learn to work with Aspose.HTML for .NET: Manipulate HTML, convert to various formats, and more. Dive into this comprehensive tutorial! + +### [Render HTML to PNG in C# – Complete Step‑by‑Step Guide](./render-html-to-png-in-c-complete-step-by-step-guide/) +Step‑by‑step guide to render HTML to PNG using C# and Aspose.HTML for .NET, covering setup, options, and best practices. + ### [How to Render HTML as PNG – Complete C# Guide](./how-to-render-html-as-png-complete-c-guide/) Step-by-step C# guide to render HTML pages as PNG images using Aspose.HTML for .NET, covering setup, options, and best practices! ### [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) diff --git a/html/english/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/english/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..c48b64400 --- /dev/null +++ b/html/english/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-02-21 +description: Render HTML to PNG quickly with Aspose.HTML. Learn how to convert HTML + to image, set image width height, and save HTML as PNG in a few lines of C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: en +og_description: Render HTML to PNG with Aspose.HTML. This tutorial shows how to convert + HTML to image, set image width height, and save HTML as PNG in C#. +og_title: Render HTML to PNG in C# – Complete Guide +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Render HTML to PNG in C# – Complete Step‑by‑Step Guide +url: /net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG – Complete Step‑by‑Step Guide + +Ever needed to **render HTML to PNG** but weren’t sure which library to pick or how to configure the output? You’re not alone. Many developers hit the same wall when they try to *convert HTML to image* for email thumbnails, report snapshots, or automated UI testing. + +In this tutorial we’ll walk through a practical, ready‑to‑run example that shows you how to **save HTML as PNG**, control the image dimensions, and tweak rendering quality—all with a handful of lines using Aspose.HTML for .NET. By the end you’ll have a reusable snippet that you can drop into any C# project. + +## What You’ll Need + +Before we dive in, make sure you have: + +- **.NET 6.0 or later** (the API works with .NET Framework, .NET Core, and .NET 5+) +- **Aspose.HTML for .NET** NuGet package (`Aspose.Html`) installed in your project. +- A basic understanding of C# syntax—nothing fancy required. +- An output folder where the generated PNG will be written. + +That’s it. No extra SDKs, no external binaries, just a single NuGet reference. + +## Render HTML to PNG – Set Up the Document + +The first thing we do is create an `HTMLDocument` object that holds the markup we want to rasterize. You can load HTML from a string, a file, or even a URL. For clarity we’ll start with a simple inline string. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![render html to png output example](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Pourquoi c’est important** : En conservant le document en mémoire, nous évitons la latence du disque et rendons l’ensemble de l’opération adaptée aux fonctions cloud ou aux micro‑services. + +## Étape 2 – Construire un gestionnaire de ressources personnalisé (Custom Resource Handler) + +Aspose.HTML appelle `ResourceHandler.HandleResource` pour chaque ressource externe qu’il découvre (images, CSS, polices). En renvoyant le même `MemoryStream` à chaque fois, nous pouvons acheminer toutes ces ressources dans un seul paquet ZIP. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Astuce** : Si vous devez limiter la taille du ZIP résultant, vous pouvez envelopper `zipStream` dans un `LimitedStream` et lever une exception lorsque la limite est dépassée. + +## Étape 3 – Enregistrer le document en tant que paquet ZIP (Save HTML as ZIP) + +Nous rassemblons maintenant le tout. Nous créons une instance de notre gestionnaire, demandons à Aspose.HTML d’enregistrer le document au format `SaveFormat.Zip`, puis récupérons les octets bruts. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +À ce stade, `zipBytes` contient un fichier ZIP parfaitement valide que vous pouvez : + +* Retourner depuis une Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Télécharger vers Azure Blob Storage ; +* Envoyer via un socket à un autre service. + +## Étape 4 – Vérifier la sortie (Convert HTML to ZIP – Test rapide) + +Une vérification rapide consiste à écrire les octets sur le disque (juste pour le débogage) et à ouvrir l’archive avec n’importe quel visualiseur ZIP. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +Lorsque vous ouvrez `debug_output.zip`, vous devriez voir : + +* `index.html` (le balisage original) +* Toutes les images, fichiers CSS ou polices référencés, intégrés à côté. + +> **Pourquoi cela fonctionne** : Aspose.HTML considère le fichier HTML principal comme la première ressource, puis diffuse chaque ressource liée dans l’ordre où il les rencontre. Notre gestionnaire les agrège toutes dans le même `MemoryStream`, que la bibliothèque finalise ensuite en archive ZIP. + +## Étape 5 – Gestion des cas limites courants (Bonnes pratiques pour Save HTML to ZIP) + +### Plusieurs fichiers CSS + +Si votre page lie plusieurs feuilles de style, chacune sera ajoutée comme une entrée distincte. Aucun code supplémentaire n’est nécessaire, mais vous pouvez vouloir imposer une convention de nommage (par ex., `styles/style1.css`) pour éviter les conflits. + +### Ressources binaires volumineuses + +Pour les images très volumineuses (>10 Mo), envisagez de les diffuser directement vers un flux basé sur un fichier plutôt qu’un simple `MemoryStream`. Remplacez `MemoryStream` par un `FileStream` dans `MemoryZipHandler` et ajustez `GetResult` en conséquence. + +### Problèmes d’encodage + +Aspose.HTML respecte le jeu de caractères déclaré dans l’en‑tête HTML. Si vous avez besoin d’une sortie UTF‑8, assurez‑vous que la balise `` est présente avant de créer le `HTMLDocument`. + +## Exemple complet fonctionnel (Save HTML to ZIP) + +Voici le programme complet que vous pouvez coller dans une application console et exécuter tel quel. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Sortie attendue :** +``` +ZIP created – 1234 bytes +``` + +L’ouverture de `output.zip` montre `index.html` contenant le balisage `

Hello World

`. Aucun fichier supplémentaire n’était requis. + +--- + +## Questions fréquentes (FAQ) + +**Q : Cette méthode fonctionne‑t‑elle avec des URL externes (par ex., des images hébergées sur un CDN) ?** +R : Oui. Aspose.HTML téléchargera la ressource distante, puis la transmettra à `HandleResource`. Soyez simplement conscient de la latence réseau et des éventuelles exigences d’authentification. + +**Q : Puis‑je définir un nom personnalisé pour le fichier HTML principal à l’intérieur du ZIP ?** +R : Par défaut, il s’agit de `index.html`. Pour le renommer, vous devez post‑traiter le ZIP (par ex., en utilisant `System.IO.Compression.ZipArchive`) après la fin de `Save`. + +**Q : Que faire si je dois compresser plusieurs documents HTML ensemble ?** +R : Créez un `HTMLDocument` distinct pour chaque page et appelez `Save` sur le même `MemoryZipHandler`. Le gestionnaire continuera d’ajouter des ressources, ce qui donnera un ZIP multi‑pages. + +## Conclusion + +Vous disposez maintenant d’une méthode solide, **comment compresser du HTML en ZIP**, qui exploite un **gestionnaire de ressources personnalisé** pour **enregistrer du HTML en zip**, **convertir du HTML en zip**, et **enregistrer du HTML en zip** — le tout sans toucher au système de fichiers. Cette approche est légère, entièrement en mémoire, et s’intègre parfaitement aux API web, aux tâches en arrière‑plan ou à tout service .NET qui doit livrer des paquets HTML à la volée. + +Prêt pour l’étape suivante ? Essayez d’étendre le gestionnaire pour compresser davantage la sortie avec `System.IO.Compression.GZipStream`, ou intégrez‑le dans un contrôleur ASP.NET Core qui renvoie le ZIP directement au navigateur. Le ciel est la limite, et vous avez maintenant la base pour construire dessus. + +Bon codage ! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/french/net/rendering-html-documents/_index.md b/html/french/net/rendering-html-documents/_index.md index b8ecffbeb..fc363f49b 100644 --- a/html/french/net/rendering-html-documents/_index.md +++ b/html/french/net/rendering-html-documents/_index.md @@ -45,6 +45,7 @@ Apprenez à travailler avec Aspose.HTML pour .NET : manipulez du HTML, converti ### [Comment utiliser Aspose pour rendre du HTML en PNG – Guide étape par étape](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) Apprenez à convertir du HTML en images PNG avec Aspose.HTML pour .NET grâce à ce guide détaillé étape par étape. + ### [Créer un PNG à partir de HTML – Guide complet de rendu C#](./create-png-from-html-full-c-rendering-guide/) Apprenez à générer des images PNG à partir de HTML en utilisant Aspose.HTML pour .NET avec un guide complet en C#. @@ -65,9 +66,13 @@ Libérez la puissance d'Aspose.HTML pour .NET ! Apprenez à restituer un docume ### [Comment rendre HTML au format PNG – Guide complet C#](./how-to-render-html-as-png-complete-c-guide/) Apprenez à convertir du HTML en PNG avec C# grâce à ce guide complet et pratique. + ### [Comment rendre le HTML en PNG avec Aspose – Guide complet](./how-to-render-html-to-png-with-aspose-complete-guide/) Apprenez à convertir du HTML en images PNG avec Aspose grâce à ce guide complet et détaillé. +### [Rendre le HTML au format PNG en C# – Guide complet étape par étape](./render-html-to-png-in-c-complete-step-by-step-guide/) +Apprenez à convertir du HTML en images PNG avec C# grâce à ce guide complet et détaillé, étape par étape. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/french/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/french/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..505b6dc0e --- /dev/null +++ b/html/french/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-02-21 +description: Rendre le HTML en PNG rapidement avec Aspose.HTML. Apprenez comment convertir + le HTML en image, définir la largeur et la hauteur de l'image, et enregistrer le + HTML au format PNG en quelques lignes de C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: fr +og_description: Rendre le HTML en PNG avec Aspose.HTML. Ce tutoriel montre comment + convertir le HTML en image, définir la largeur et la hauteur de l'image, et enregistrer + le HTML au format PNG en C#. +og_title: Rendu du HTML en PNG en C# – Guide complet +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Rendu du HTML en PNG en C# – Guide complet étape par étape +url: /fr/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Rendu HTML en PNG – Guide complet étape par étape + +Vous avez déjà eu besoin de **render HTML to PNG** mais vous ne saviez pas quelle bibliothèque choisir ou comment configurer la sortie ? Vous n'êtes pas seul. De nombreux développeurs rencontrent le même problème lorsqu'ils essaient de *convert HTML to image* pour des vignettes d'e‑mail, des captures d'écran de rapports ou des tests UI automatisés. + +Dans ce tutoriel, nous parcourrons un exemple pratique, prêt à l'exécution, qui vous montre comment **save HTML as PNG**, contrôler les dimensions de l'image et ajuster la qualité du rendu — le tout en quelques lignes avec Aspose.HTML for .NET. À la fin, vous disposerez d'un extrait réutilisable que vous pourrez intégrer dans n'importe quel projet C#. + +## Ce dont vous avez besoin + +- **.NET 6.0 ou ultérieur** (l'API fonctionne avec .NET Framework, .NET Core et .NET 5+) +- **Aspose.HTML for .NET** package NuGet (`Aspose.Html`) installé dans votre projet. +- Une compréhension de base de la syntaxe C# — rien de compliqué requis. +- Un dossier de sortie où le PNG généré sera écrit. + +C’est tout. Aucun SDK supplémentaire, aucun binaire externe, juste une seule référence NuGet. + +## Rendu HTML en PNG – Configurer le document + +La première chose que nous faisons est de créer un objet `HTMLDocument` qui contient le balisage que nous voulons rasteriser. Vous pouvez charger du HTML depuis une chaîne, un fichier ou même une URL. Pour plus de clarté, nous commencerons avec une simple chaîne en ligne. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![exemple de sortie render html to png](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Warum das wichtig ist:** Indem das Dokument im Speicher bleibt, vermeiden wir Festplatten‑Latenz und machen den gesamten Vorgang für Cloud‑Funktionen oder Micro‑Services geeignet. + +## Schritt 2 – Einen benutzerdefinierten Resource Handler bauen (Custom Resource Handler) + +Aspose.HTML ruft `ResourceHandler.HandleResource` für jede externe Ressource auf, die es entdeckt (Bilder, CSS, Fonts). Indem wir jedes Mal denselben `MemoryStream` zurückgeben, können wir all diese Ressourcen in ein einziges ZIP‑Paket leiten. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro‑Tipp:** Wenn Sie die Größe des resultierenden ZIPs begrenzen möchten, können Sie `zipStream` in einen `LimitedStream` einwickeln und eine Ausnahme werfen, sobald das Limit überschritten wird. + +## Schritt 3 – Das Dokument als ZIP‑Paket speichern (Save HTML as ZIP) + +Jetzt fügen wir alles zusammen. Wir instanziieren unseren Handler, lassen Aspose.HTML das Dokument im `SaveFormat.Zip` speichern und holen schließlich die rohen Bytes. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +An diesem Punkt enthält `zipBytes` eine vollkommen gültige ZIP‑Datei, die Sie: + +* Von einer Web‑API zurückgeben können (`File(zipBytes, "application/zip", "page.zip")`); +* In Azure Blob Storage hochladen; +* Über einen Socket an einen anderen Dienst senden. + +## Schritt 4 – Ausgabe verifizieren (Convert HTML to ZIP – Schnelltest) + +Ein schneller Plausibilitätstest besteht darin, die Bytes zur Fehlersuche auf die Festplatte zu schreiben und das Archiv mit einem beliebigen ZIP‑Viewer zu öffnen. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +Wenn Sie `debug_output.zip` öffnen, sollten Sie sehen: + +* `index.html` (das ursprüngliche Markup) +* Alle referenzierten Bilder, CSS‑Dateien oder Fonts, die daneben eingebettet sind. + +> **Warum das funktioniert:** Aspose.HTML behandelt die Haupt‑HTML‑Datei als erste Ressource und streamt dann jede verknüpfte Datei in der Reihenfolge, in der sie gefunden wird. Unser Handler sammelt sie alle in demselben `MemoryStream`, den die Bibliothek anschließend zu einem ZIP‑Archiv finalisiert. + +## Schritt 5 – Umgang mit gängigen Sonderfällen (Save HTML to ZIP Best Practices) + +### Mehrere CSS‑Dateien + +Wenn Ihre Seite auf mehrere Stylesheets verweist, wird jede als separater Eintrag hinzugefügt. Kein zusätzlicher Code ist nötig, aber Sie sollten eventuell eine Namenskonvention (z. B. `styles/style1.css`) durchsetzen, um Kollisionen zu vermeiden. + +### Große Binärressourcen + +Für massive Bilder (> 10 MB) sollten Sie erwägen, sie direkt in einen dateibasierten Stream zu schreiben, anstatt einen reinen `MemoryStream` zu verwenden. Ersetzen Sie `MemoryStream` durch einen `FileStream` in `MemoryZipHandler` und passen Sie `GetResult` entsprechend an. + +### Kodierungsprobleme + +Aspose.HTML respektiert das im HTML‑Header deklarierte Charset. Wenn Sie UTF‑8‑Ausgabe benötigen, stellen Sie sicher, dass das ``‑Tag vorhanden ist, bevor Sie das `HTMLDocument` erstellen. + +## Vollständiges funktionierendes Beispiel (Save HTML to ZIP) + +Unten finden Sie das komplette Programm, das Sie in eine Konsolen‑App einfügen und unverändert ausführen können. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Erwartete Ausgabe:** +``` +ZIP created – 1234 bytes +``` + +Das Öffnen von `output.zip` zeigt `index.html` mit dem Markup `

Hello World

`. Es wurden keine zusätzlichen Dateien benötigt. + +--- + +## Häufig gestellte Fragen (FAQs) + +**F: Funktioniert das mit externen URLs (z. B. Bilder, die auf einem CDN gehostet werden)?** +A: Ja. Aspose.HTML lädt die entfernte Ressource herunter und übergibt sie dann an `HandleResource`. Beachten Sie jedoch Netzwerklatenz und mögliche Authentifizierungsanforderungen. + +**F: Kann ich einen eigenen Namen für die Haupt‑HTML‑Datei im ZIP festlegen?** +A: Standardmäßig heißt sie `index.html`. Um sie umzubenennen, müssen Sie das ZIP nach dem `Save`‑Vorgang nachbearbeiten (z. B. mit `System.IO.Compression.ZipArchive`). + +**F: Was, wenn ich mehrere HTML‑Dokumente zusammen zippen muss?** +A: Erstellen Sie für jede Seite ein separates `HTMLDocument` und rufen Sie `Save` mit demselben `MemoryZipHandler` auf. Der Handler fügt die Ressourcen fortlaufend hinzu, sodass ein Mehrseiten‑ZIP entsteht. + +--- + +## Fazit + +Sie besitzen nun ein solides **Wie‑man‑HTML‑zippt**‑Rezept, das einen **benutzerdefinierten Resource Handler** nutzt, um **HTML als ZIP zu speichern**, **HTML in ZIP zu konvertieren** und **HTML zu ZIP zu speichern** – alles ohne das Dateisystem zu berühren. Der Ansatz ist leichtgewichtig, komplett im Speicher und lässt sich hervorragend in Web‑APIs, Hintergrundjobs oder jeden .NET‑Dienst integrieren, der HTML‑Bundles on‑the‑fly ausliefern muss. + +Bereit für den nächsten Schritt? Versuchen Sie, den Handler zu erweitern, um die Ausgabe mit `System.IO.Compression.GZipStream` weiter zu komprimieren, oder integrieren Sie ihn in einen ASP.NET Core‑Controller, der das ZIP direkt an den Browser zurückgibt. Der Himmel ist die Grenze, und Sie haben jetzt das Fundament, darauf aufzubauen. + +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/german/net/rendering-html-documents/_index.md b/html/german/net/rendering-html-documents/_index.md index ad113650f..b5c3aeaa5 100644 --- a/html/german/net/rendering-html-documents/_index.md +++ b/html/german/net/rendering-html-documents/_index.md @@ -53,6 +53,9 @@ Erfahren Sie, wie Sie HTML‑Inhalte mit Aspose in PNG‑Bilder umwandeln – ei ### [PNG aus HTML erstellen – Vollständiger C#-Rendering-Leitfaden](./create-png-from-html-full-c-rendering-guide/) Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in PNG konvertieren – ein umfassender Leitfaden für C#-Entwickler. +### [HTML zu PNG rendern in C# – Vollständiger Schritt‑für‑Schritt‑Leitfaden](./render-html-to-png-in-c-complete-step-by-step-guide/) +Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in PNG konvertieren – vollständiger C#‑Leitfaden mit Schritt‑für‑Schritt‑Anleitung. + ### [Rendern Sie EPUB als XPS in .NET mit Aspose.HTML](./render-epub-as-xps/) Erfahren Sie in diesem umfassenden Tutorial, wie Sie mit Aspose.HTML für .NET HTML-Dokumente erstellen und rendern. Tauchen Sie ein in die Welt der HTML-Manipulation, des Web Scraping und mehr. diff --git a/html/german/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/german/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..4fba887d0 --- /dev/null +++ b/html/german/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-02-21 +description: Rendern Sie HTML schnell zu PNG mit Aspose.HTML. Erfahren Sie, wie Sie + HTML in ein Bild konvertieren, Bildbreite und -höhe festlegen und HTML in wenigen + C#‑Zeilen als PNG speichern. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: de +og_description: Rendern Sie HTML zu PNG mit Aspose.HTML. Dieses Tutorial zeigt, wie + man HTML in ein Bild konvertiert, die Bildbreite und -höhe festlegt und HTML als + PNG in C# speichert. +og_title: HTML zu PNG rendern in C# – Vollständiger Leitfaden +tags: +- Aspose.HTML +- C# +- Image Rendering +title: HTML in PNG rendern in C# – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML zu PNG rendern – Vollständige Schritt‑für‑Schritt‑Anleitung + +Haben Sie jemals **HTML zu PNG rendern** müssen, waren sich aber nicht sicher, welche Bibliothek Sie wählen oder wie Sie die Ausgabe konfigurieren sollten? Sie sind nicht allein. Viele Entwickler stoßen auf dasselbe Problem, wenn sie versuchen, *HTML zu Bild zu konvertieren* für E‑Mail‑Thumbnails, Berichtsschnappschüsse oder automatisierte UI‑Tests. + +In diesem Tutorial führen wir Sie durch ein praktisches, sofort ausführbares Beispiel, das zeigt, wie Sie **HTML als PNG speichern**, die Bildabmessungen steuern und die Renderqualität anpassen – alles mit wenigen Zeilen mithilfe von Aspose.HTML für .NET. Am Ende haben Sie ein wiederverwendbares Snippet, das Sie in jedes C#‑Projekt einbinden können. + +## Was Sie benötigen + +Bevor wir starten, stellen Sie sicher, dass Sie Folgendes haben: + +- **.NET 6.0 oder höher** (die API funktioniert mit .NET Framework, .NET Core und .NET 5+) +- **Aspose.HTML for .NET** NuGet‑Paket (`Aspose.Html`) in Ihrem Projekt installiert. +- Ein grundlegendes Verständnis der C#‑Syntax – nichts Besonderes erforderlich. +- Ein Ausgabeverzeichnis, in das das erzeugte PNG geschrieben wird. + +Das war’s. Keine zusätzlichen SDKs, keine externen Binärdateien, nur ein einzelner NuGet‑Verweis. + +## HTML zu PNG rendern – Dokument einrichten + +Das erste, was wir tun, ist ein `HTMLDocument`‑Objekt zu erstellen, das das Markup enthält, das wir rasterisieren möchten. Sie können HTML aus einem String, einer Datei oder sogar einer URL laden. Zur Veranschaulichung beginnen wir mit einem einfachen Inline‑String. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![render html to png output example](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Γιατί είναι σημαντικό:** Κρατώντας το έγγραφο στη μνήμη αποφεύγουμε την καθυστέρηση του δίσκου και κάνουμε όλη τη λειτουργία κατάλληλη για cloud functions ή micro‑services. + +## Βήμα 2 – Δημιουργία Προσαρμοσμένου Διαχειριστή Πόρων (Custom Resource Handler) + +Το Aspose.HTML καλεί το `ResourceHandler.HandleResource` για κάθε εξωτερικό στοιχείο που εντοπίζει (εικόνες, CSS, γραμματοσειρές). Επιστρέφοντας το ίδιο `MemoryStream` κάθε φορά, μπορούμε να κατευθύνουμε όλους αυτούς τους πόρους σε ένα ενιαίο πακέτο ZIP. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro tip:** Αν χρειάζεται να περιορίσετε το μέγεθος του τελικού ZIP, μπορείτε να τυλίξετε το `zipStream` σε ένα `LimitedStream` και να ρίξετε εξαίρεση όταν ξεπεραστεί το όριο. + +## Βήμα 3 – Αποθήκευση του Εγγράφου ως Πακέτο ZIP (Save HTML as ZIP) + +Τώρα συνδέουμε όλα τα κομμάτια. Δημιουργούμε το handler μας, ζητάμε από το Aspose.HTML να αποθηκεύσει το έγγραφο σε `SaveFormat.Zip` και, τέλος, εξάγουμε τα ακατέργαστα bytes. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +Σε αυτό το σημείο το `zipBytes` περιέχει ένα τέλεια έγκυρο αρχείο ZIP που μπορείτε να: + +* Επιστρέψετε από ένα Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Ανεβάσετε στο Azure Blob Storage; +* Στείλετε μέσω socket σε άλλη υπηρεσία. + +## Βήμα 4 – Επαλήθευση του Αποτελέσματος (Convert HTML to ZIP – Quick Test) + +Μια γρήγορη δοκιμή είναι να γράψετε τα bytes σε δίσκο (μόνο για debugging) και να ανοίξετε το αρχείο με οποιονδήποτε προβολέα ZIP. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +Όταν ανοίξετε το `debug_output.zip` θα πρέπει να δείτε: + +* `index.html` (το αρχικό markup) +* Οποιαδήποτε εικόνα, CSS ή γραμματοσειρά που αναφέρεται, ενσωματωμένα δίπλα του. + +> **Γιατί λειτουργεί:** Το Aspose.HTML θεωρεί το κύριο αρχείο HTML ως τον πρώτο πόρο, έπειτα ρέει κάθε συνδεδεμένο στοιχείο με τη σειρά που τα εντοπίζει. Ο handler μας τα συγκεντρώνει όλα στο ίδιο `MemoryStream`, το οποίο η βιβλιοθήκη στη συνέχεια ολοκληρώνει ως αρχείο ZIP. + +## Βήμα 5 – Διαχείριση Συνηθισμένων Ειδικών Περιπτώσεων (Save HTML to ZIP Best Practices) + +### Πολλαπλά Αρχεία CSS + +Αν η σελίδα σας συνδέεται με πολλά style sheets, το καθένα θα προστεθεί ως ξεχωριστή καταχώρηση. Δεν απαιτείται επιπλέον κώδικας, αλλά ίσως θελήσετε να εφαρμόσετε μια σύμβαση ονοματοδοσίας (π.χ., `styles/style1.css`) για να αποφύγετε συγκρούσεις. + +### Μεγάλοι Δυαδικοί Πόροι + +Για τεράστιες εικόνες (>10 MB) σκεφτείτε να ρέετε τα δεδομένα απευθείας σε ένα stream που βασίζεται σε αρχείο αντί για καθαρό `MemoryStream`. Αντικαταστήστε το `MemoryStream` με ένα `FileStream` στο `MemoryZipHandler` και προσαρμόστε το `GetResult` αναλόγως. + +### Προβλήματα Κωδικοποίησης + +Το Aspose.HTML σέβεται το charset που δηλώνεται στην κεφαλίδα του HTML. Αν χρειάζεστε έξοδο UTF‑8, βεβαιωθείτε ότι υπάρχει η ετικέτα `` πριν δημιουργήσετε το `HTMLDocument`. + +## Πλήρες Παράδειγμα Εργασίας (Save HTML to ZIP) + +Παρακάτω βρίσκεται το πλήρες πρόγραμμα που μπορείτε να επικολλήσετε σε μια console εφαρμογή και να τρέξετε όπως είναι. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Αναμενόμενη έξοδος:** +``` +ZIP created – 1234 bytes +``` + +Ανοίγοντας το `output.zip` θα δείτε το `index.html` που περιέχει το markup `

Hello World

`. Δεν απαιτήθηκαν επιπλέον αρχεία. + +--- + +## Συχνές Ερωτήσεις (FAQs) + +**Ε: Λειτουργεί αυτό με εξωτερικά URLs (π.χ., εικόνες σε CDN);** +Α: Ναι. Το Aspose.HTML θα κατεβάσει τον απομακρυσμένο πόρο, έπειτα θα τον περάσει στο `HandleResource`. Να έχετε υπόψη την καθυστέρηση δικτύου και τυχόν απαιτήσεις αυθεντικοποίησης. + +**Ε: Μπορώ να ορίσω προσαρμοσμένο όνομα για το κύριο αρχείο HTML μέσα στο ZIP;** +Α: Από προεπιλογή είναι `index.html`. Για να το μετονομάσετε, θα χρειαστεί να επεξεργαστείτε το ZIP μετά το `Save` (π.χ., χρησιμοποιώντας `System.IO.Compression.ZipArchive`). + +**Ε: Τι γίνεται αν χρειαστεί να συμπιέσω πολλαπλά έγγραφα HTML μαζί;** +Α: Δημιουργήστε ξεχωριστό `HTMLDocument` για κάθε σελίδα και καλέστε `Save` στον ίδιο `MemoryZipHandler`. Ο handler θα συνεχίσει να προσθέτει πόρους, δημιουργώντας ένα πολυ‑σελίδες ZIP. + +--- + +## Συμπέρασμα + +Τώρα έχετε μια σταθερή **συνταγή how to zip HTML** που αξιοποιεί έναν **προσαρμοσμένο διαχειριστή πόρων** για **save HTML as zip**, **convert HTML to zip**, και **save HTML to zip** — όλα χωρίς να αγγίξετε το σύστημα αρχείων. Η προσέγγιση είναι ελαφριά, πλήρως στη μνήμη, και ταιριάζει άψογα σε web APIs, background jobs ή οποιαδήποτε υπηρεσία .NET που χρειάζεται να στέλνει HTML bundles “on the fly”. + +Έτοιμοι για το επόμενο βήμα; Δοκιμάστε να επεκτείνετε τον handler ώστε να συμπιέζει περαιτέρω την έξοδο με `System.IO.Compression.GZipStream`, ή ενσωματώστε το σε έναν ASP.NET Core controller που επιστρέφει το ZIP απευθείας στον browser. Ο ουρανός είναι το όριο, και τώρα έχετε τη βάση για να χτίσετε πάνω του. + +Καλή προγραμματιστική! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/greek/net/rendering-html-documents/_index.md b/html/greek/net/rendering-html-documents/_index.md index f874e075c..aeffdb19a 100644 --- a/html/greek/net/rendering-html-documents/_index.md +++ b/html/greek/net/rendering-html-documents/_index.md @@ -60,6 +60,8 @@ url: /el/net/rendering-html-documents/ Μάθετε πώς να μετατρέψετε HTML σε PNG χρησιμοποιώντας το Aspose.HTML για .NET σε αυτόν τον πλήρη οδηγό. ### [Δημιουργία PNG από HTML – Πλήρης Οδηγός Απόδοσης C#](./create-png-from-html-full-c-rendering-guide/) Μάθετε πώς να δημιουργήσετε PNG από HTML χρησιμοποιώντας το Aspose.HTML για .NET με πλήρη οδηγό C#. +### [Απόδοση HTML σε PNG σε C# – Πλήρης Οδηγός Βήμα‑βήμα](./render-html-to-png-in-c-complete-step-by-step-guide/) +Μάθετε πώς να μετατρέψετε HTML σε PNG χρησιμοποιώντας C# και το Aspose.HTML για .NET σε αυτόν τον πλήρη οδηγό βήμα‑βήμα. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/greek/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/greek/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..e1a565831 --- /dev/null +++ b/html/greek/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-02-21 +description: Αποδώστε HTML σε PNG γρήγορα με το Aspose.HTML. Μάθετε πώς να μετατρέπετε + HTML σε εικόνα, να ορίζετε το πλάτος και το ύψος της εικόνας και να αποθηκεύετε + το HTML ως PNG με λίγες γραμμές κώδικα C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: el +og_description: Απόδοση HTML σε PNG με το Aspose.HTML. Αυτό το σεμινάριο δείχνει πώς + να μετατρέψετε το HTML σε εικόνα, να ορίσετε το πλάτος και το ύψος της εικόνας και + να αποθηκεύσετε το HTML ως PNG σε C#. +og_title: Απόδοση HTML σε PNG σε C# – Πλήρης Οδηγός +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Απόδοση HTML σε PNG σε C# – Πλήρης Οδηγός Βήμα‑βήμα +url: /el/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG – Complete Step‑by‑Step Guide + +Ποτέ χρειάστηκε να **αποδώσετε HTML σε PNG** αλλά δεν ήξερες ποια βιβλιοθήκη να επιλέξεις ή πώς να ρυθμίσεις την έξοδο; Δεν είσαι μόνος. Πολλοί προγραμματιστές αντιμετωπίζουν το ίδιο πρόβλημα όταν προσπαθούν να *μετατρέψουν HTML σε εικόνα* για μικρογραφίες email, στιγμιότυπα αναφορών ή αυτοματοποιημένο UI testing. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από ένα πρακτικό, έτοιμο‑για‑εκτέλεση παράδειγμα που δείχνει πώς να **αποθηκεύσετε HTML ως PNG**, να ελέγξετε τις διαστάσεις της εικόνας και να ρυθμίσετε την ποιότητα απόδοσης — όλα με λίγες γραμμές κώδικα χρησιμοποιώντας το Aspose.HTML for .NET. Στο τέλος θα έχετε ένα επαναχρησιμοποιήσιμο snippet που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο C#. + +## What You’ll Need + +Πριν ξεκινήσουμε, βεβαιωθείτε ότι έχετε: + +- **.NET 6.0 ή νεότερο** (το API λειτουργεί με .NET Framework, .NET Core και .NET 5+) +- **Aspose.HTML for .NET** πακέτο NuGet (`Aspose.Html`) εγκατεστημένο στο έργο σας. +- Βασική κατανόηση της σύνταξης C# — δεν απαιτείται τίποτα περίπλοκο. +- Έναν φάκελο εξόδου όπου θα γραφτεί το παραγόμενο PNG. + +Αυτό είναι όλο. Χωρίς επιπλέον SDKs, χωρίς εξωτερικά binaries, μόνο μια αναφορά NuGet. + +## Render HTML to PNG – Set Up the Document + +Το πρώτο που κάνουμε είναι να δημιουργήσουμε ένα αντικείμενο `HTMLDocument` που περιέχει το markup που θέλουμε να rasterize. Μπορείτε να φορτώσετε HTML από string, αρχείο ή ακόμη και URL. Για σαφήνεια θα ξεκινήσουμε με ένα απλό inline string. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![παράδειγμα εξόδου render html to png](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Why this matters:** डॉक्यूमेंट को मेमोरी में रखकर हम डिस्क लेटेंसी से बचते हैं और पूरी ऑपरेशन को क्लाउड फ़ंक्शन्स या माइक्रो‑सर्विसेज़ के लिए उपयुक्त बनाते हैं। + +## Step 2 – Build a Custom Resource Handler (Custom Resource Handler) + +Aspose.HTML हर बाहरी एसेट (इमेजेज, CSS, फ़ॉन्ट्स) को खोजते समय `ResourceHandler.HandleResource` को कॉल करता है। हर बार वही `MemoryStream` रिटर्न करके हम सभी रिसोर्सेज़ को एक ही ZIP पैकेज में फनल कर सकते हैं। + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro tip:** यदि आपको बनते ZIP का आकार सीमित करना है, तो `zipStream` को `LimitedStream` में रैप कर सकते हैं और लिमिट ओवर होने पर एक्सेप्शन थ्रो कर सकते हैं। + +## Step 3 – Save the Document as a ZIP Package (Save HTML as ZIP) + +अब हम सब कुछ जोड़ते हैं। हैंडलर को इंस्टैंशिएट करते हैं, Aspose.HTML को `SaveFormat.Zip` में डॉक्यूमेंट सेव करने के लिए कहते हैं, और अंत में रॉ बाइट्स निकालते हैं। + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +इस चरण पर `zipBytes` में एक पूरी तरह वैध ZIP फ़ाइल होगी जिसे आप: + +* Web API से रिटर्न कर सकते हैं (`File(zipBytes, "application/zip", "page.zip")`); +* Azure Blob Storage में अपलोड कर सकते हैं; +* किसी अन्य सर्विस को सॉकेट के माध्यम से भेज सकते हैं। + +## Step 4 – Verify the Output (Convert HTML to ZIP – Quick Test) + +एक त्वरित वैधता जांच के लिए बाइट्स को डिस्क पर लिखें (सिर्फ डिबगिंग के लिए) और किसी भी ZIP व्यूअर से आर्काइव खोलें। + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +जब आप `debug_output.zip` खोलेंगे तो आपको दिखना चाहिए: + +* `index.html` (मूल मार्कअप) +* सभी रेफ़रेंस्ड इमेजेज, CSS फ़ाइलें, या फ़ॉन्ट्स जो उसके साथ एम्बेडेड हों। + +> **Why this works:** Aspose.HTML मुख्य HTML फ़ाइल को पहला रिसोर्स मानता है, फिर क्रमशः हर लिंक्ड एसेट को स्ट्रीम करता है। हमारा हैंडलर उन्हें सभी को एक ही `MemoryStream` में एकत्रित करता है, जिसे लाइब्रेरी अंत में ZIP आर्काइव के रूप में फाइनल करती है। + +## Step 5 – Handling Common Edge Cases (Save HTML to ZIP Best Practices) + +### Multiple CSS Files + +यदि आपका पेज कई स्टाइल शीट्स लिंक करता है, तो प्रत्येक को अलग एंट्री के रूप में जोड़ा जाएगा। अतिरिक्त कोड की जरूरत नहीं, लेकिन नामकरण सम्मेलन (जैसे `styles/style1.css`) लागू करने से क्लैश से बचा जा सकता है। + +### Large Binary Resources + +बड़े इमेजेज (>10 MB) के लिए `MemoryStream` की बजाय फ़ाइल‑बैक्ड स्ट्रीम का उपयोग करने पर विचार करें। `MemoryZipHandler` में `MemoryStream` को `FileStream` से बदलें और `GetResult` को उसी अनुसार एडजस्ट करें। + +### Encoding Issues + +Aspose.HTML HTML हेडर में घोषित charset का सम्मान करता है। यदि आपको UTF‑8 आउटपुट चाहिए, तो `HTMLDocument` बनाने से पहले `` टैग मौजूद होना सुनिश्चित करें। + +## Full Working Example (Save HTML to ZIP) + +नीचे पूरा प्रोग्राम दिया गया है जिसे आप एक कंसोल ऐप में पेस्ट करके 그대로 चला सकते हैं। + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Expected output:** +``` +ZIP created – 1234 bytes +``` + +`output.zip` खोलने पर `index.html` में `

Hello World

` मार्कअप दिखेगा। कोई अतिरिक्त फ़ाइल की जरूरत नहीं थी। + +--- + +## Frequently Asked Questions (FAQs) + +**Q: क्या यह बाहरी URLs (जैसे CDN पर होस्टेड इमेजेज) के साथ काम करता है?** +A: हाँ। Aspose.HTML रिमोट रिसोर्स को डाउनलोड करेगा, फिर उसे `HandleResource` को पास करेगा। नेटवर्क लेटेंसी और संभावित ऑथेंटिकेशन आवश्यकताओं का ध्यान रखें। + +**Q: क्या मैं ZIP के अंदर मुख्य HTML फ़ाइल का कस्टम नाम सेट कर सकता हूँ?** +A: डिफ़ॉल्ट रूप से यह `index.html` होता है। इसे रीनेम करने के लिए `Save` पूरा होने के बाद `System.IO.Compression.ZipArchive` जैसी क्लास का उपयोग करके पोस्ट‑प्रोसेस करना पड़ेगा। + +**Q: यदि मुझे कई HTML डॉक्यूमेंट्स को एक साथ ज़िप करना हो तो क्या करें?** +A: प्रत्येक पेज के लिए अलग `HTMLDocument` बनाएं और एक ही `MemoryZipHandler` पर `Save` कॉल करें। हैंडलर रिसोर्सेज़ को जोड़ता रहेगा, जिससे मल्टी‑पेज ZIP बन जाएगा। + +--- + +## Conclusion + +अब आपके पास एक ठोस **HTML को ज़िप करने** की रेसिपी है जो **कस्टम रिसोर्स हैंडलर** का उपयोग करके **HTML को ज़िप के रूप में सेव**, **HTML को ज़िप में कनवर्ट**, और **HTML को ज़िप में सेव** करती है—बिना फ़ाइल सिस्टम को छुए। यह हल्का, पूरी तरह इन‑मेमोरी, और वेब APIs, बैकग्राउंड जॉब्स, या किसी भी .NET सर्विस में फिट बैठता है जिसे रन‑टाइम पर HTML बंडल्स भेजने की जरूरत है। + +अगला कदम क्या है? हैंडलर को `System.IO.Compression.GZipStream` से और कॉम्प्रेस करने के लिए एक्सटेंड करें, या इसे एक ASP.NET Core कंट्रोलर में इंटीग्रेट करें जो सीधे ब्राउज़र को ZIP रिटर्न करे। संभावनाएँ अनंत हैं, और अब आपके पास निर्माण का आधार है। + +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/rendering-html-documents/_index.md b/html/hindi/net/rendering-html-documents/_index.md index f656f4636..109824ad4 100644 --- a/html/hindi/net/rendering-html-documents/_index.md +++ b/html/hindi/net/rendering-html-documents/_index.md @@ -57,17 +57,22 @@ Aspose.HTML for .NET में रेंडरिंग टाइमआउट ### [Aspose.HTML के साथ .NET में SVG दस्तावेज़ को PNG के रूप में प्रस्तुत करें](./render-svg-doc-as-png/) .NET के लिए Aspose.HTML की शक्ति अनलॉक करें! SVG Doc को आसानी से PNG के रूप में रेंडर करना सीखें। चरण-दर-चरण उदाहरणों और FAQ में गोता लगाएँ। अभी शुरू करें! + ### [HTML को PNG के रूप में रेंडर करने का पूर्ण C# गाइड](./how-to-render-html-as-png-complete-c-guide/) -C# में Aspose.HTML का उपयोग करके HTML को PNG में बदलने के चरण-दर-चरण निर्देश। +C# में Aspose.HTML का उपयोग करके HTML को PNG में बदलने के चरण-दर-स्तर निर्देश। ### [Aspose का उपयोग करके HTML को PNG में रेंडर करने का चरण‑दर‑चरण गाइड](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) Aspose.HTML के साथ HTML को PNG फ़ॉर्मेट में बदलने की पूरी प्रक्रिया सीखें, कोड उदाहरण और टिप्स के साथ। ### [Aspose के साथ HTML को PNG में रेंडर करने का पूर्ण गाइड](./how-to-render-html-to-png-with-aspose-complete-guide/) Aspose.HTML का उपयोग करके HTML को PNG फ़ॉर्मेट में बदलने की पूरी प्रक्रिया सीखें, कोड उदाहरण और टिप्स के साथ। + ### [HTML से PNG बनाएं – पूर्ण C# रेंडरिंग गाइड](./create-png-from-html-full-c-rendering-guide/) HTML को PNG में बदलने के लिए पूर्ण C# रेंडरिंग चरणों को सीखें और Aspose.HTML का उपयोग करके उच्च गुणवत्ता वाले परिणाम प्राप्त करें। +### [C# में HTML को PNG में रेंडर करने का पूर्ण चरण‑दर‑चरण गाइड](./render-html-to-png-in-c-complete-step-by-step-guide/) +C# में Aspose.HTML का उपयोग करके HTML को PNG में बदलने की पूरी चरण‑दर‑चरण गाइड। + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/hindi/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/hindi/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3661dea9d --- /dev/null +++ b/html/hindi/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-02-21 +description: Aspose.HTML के साथ HTML को जल्दी PNG में रेंडर करें। जानें कैसे HTML + को इमेज में बदलें, इमेज की चौड़ाई और ऊँचाई सेट करें, और कुछ ही C# लाइनों में HTML + को PNG के रूप में सहेजें। +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: hi +og_description: Aspose.HTML के साथ HTML को PNG में रेंडर करें। यह ट्यूटोरियल दिखाता + है कि HTML को इमेज में कैसे बदलें, इमेज की चौड़ाई और ऊँचाई सेट करें, और C# में HTML + को PNG के रूप में कैसे सहेजें। +og_title: C# में HTML को PNG में रेंडर करना – पूर्ण गाइड +tags: +- Aspose.HTML +- C# +- Image Rendering +title: C# में HTML को PNG में रेंडर करें – पूर्ण चरण‑दर‑चरण गाइड +url: /hi/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML को PNG में रेंडर करें – पूर्ण चरण‑दर‑चरण गाइड + +क्या आपको कभी **render HTML to PNG** करने की ज़रूरत पड़ी है लेकिन यह नहीं पता था कि कौन‑सी लाइब्रेरी चुनें या आउटपुट को कैसे कॉन्फ़िगर करें? आप अकेले नहीं हैं। कई डेवलपर्स को वही समस्या आती है जब वे ईमेल थंबनेल, रिपोर्ट स्नैपशॉट या ऑटोमेटेड UI टेस्टिंग के लिए *convert HTML to image* करने की कोशिश करते हैं। + +इस ट्यूटोरियल में हम एक व्यावहारिक, तुरंत चलाने योग्य उदाहरण के माध्यम से आपको दिखाएंगे कि कैसे **save HTML as PNG** किया जाता है, इमेज के आयामों को नियंत्रित किया जाता है, और रेंडरिंग क्वालिटी को ट्यून किया जाता है—सिर्फ कुछ लाइनों में Aspose.HTML for .NET का उपयोग करके। अंत तक आपके पास एक पुन: उपयोग योग्य स्निपेट होगा जिसे आप किसी भी C# प्रोजेक्ट में डाल सकते हैं। + +## आपको क्या चाहिए + +- **.NET 6.0 या बाद का** (API .NET Framework, .NET Core, और .NET 5+ के साथ काम करता है) +- **Aspose.HTML for .NET** NuGet पैकेज (`Aspose.Html`) आपके प्रोजेक्ट में इंस्टॉल किया हुआ। +- C# सिंटैक्स की बुनियादी समझ—कोई विशेष चीज़ आवश्यक नहीं। +- एक आउटपुट फ़ोल्डर जहाँ जेनरेट किया गया PNG लिखा जाएगा। + +बस इतना ही। कोई अतिरिक्त SDK नहीं, कोई बाहरी बाइनरी नहीं, सिर्फ एक ही NuGet रेफ़रेंस। + +## HTML को PNG में रेंडर करें – दस्तावेज़ सेट अप करें + +पहला कदम यह है कि हम एक `HTMLDocument` ऑब्जेक्ट बनाते हैं जो उस मार्कअप को रखता है जिसे हम रास्टराइज़ करना चाहते हैं। आप HTML को स्ट्रिंग, फ़ाइल, या यहाँ तक कि URL से लोड कर सकते हैं। स्पष्टता के लिए हम एक साधारण इनलाइन स्ट्रिंग से शुरू करेंगे। + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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 पिक्सेल। + +![render html to png आउटपुट उदाहरण](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Why this matters:** 透過將文件保留在記憶體中,我們避免了磁碟延遲,讓整個操作適用於雲端函式或微服務。 + +## Step 2 – Build a Custom Resource Handler (Custom Resource Handler) + +Aspose.HTML 會對每個發現的外部資產(圖片、CSS、字型)呼叫 `ResourceHandler.HandleResource`。只要每次回傳相同的 `MemoryStream`,就能把所有資源匯入同一個 ZIP 套件。 + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro tip:** 若需要限制產生的 ZIP 大小,可將 `zipStream` 包裝在 `LimitedStream` 中,超過上限時拋出例外。 + +## Step 3 – Save the Document as a ZIP Package (Save HTML as ZIP) + +現在把所有東西串起來。建立我們的處理程式,指示 Aspose.HTML 以 `SaveFormat.Zip` 保存文件,最後取得原始位元組。 + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +此時 `zipBytes` 已是一個完整且有效的 ZIP 檔,你可以: + +* 從 Web API 回傳 (`File(zipBytes, "application/zip", "page.zip")`); +* 上傳至 Azure Blob Storage; +* 透過 socket 傳送給其他服務。 + +## Step 4 – Verify the Output (Convert HTML to ZIP – Quick Test) + +為了快速驗證,將位元組寫入磁碟(僅供除錯用),再以任意 ZIP 檢視器開啟壓縮檔。 + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +當你開啟 `debug_output.zip` 時,應該會看到: + +* `index.html`(原始標記) +* 所有被引用的圖片、CSS 檔或字型,皆與之同列。 + +> **Why this works:** Aspose.HTML 會把主 HTML 檔視為第一個資源,接著依照發現的順序串流每個連結資產。我們的處理程式將它們全部聚合到同一個 `MemoryStream`,最後由函式庫完成 ZIP 打包。 + +## Step 5 – Handling Common Edge Cases (Save HTML to ZIP Best Practices) + +### Multiple CSS Files + +如果頁面連結了多個樣式表,會各自作為獨立條目加入。無需額外程式碼,但建議使用命名慣例(例如 `styles/style1.css`)以避免衝突。 + +### Large Binary Resources + +對於巨型圖片(>10 MB),建議直接串流至檔案型別的 Stream,而非純 `MemoryStream`。只要在 `MemoryZipHandler` 中將 `MemoryStream` 換成 `FileStream`,並相應調整 `GetResult` 即可。 + +### Encoding Issues + +Aspose.HTML 會遵循 HTML 標頭中宣告的字元集。若需 UTF‑8 輸出,請確保在建立 `HTMLDocument` 前,HTML 中已包含 `` 標籤。 + +## Full Working Example (Save HTML to ZIP) + +以下是完整程式碼,你可以直接貼到 Console App 中執行。 + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Expected output:** +``` +ZIP created – 1234 bytes +``` + +開啟 `output.zip` 後會看到 `index.html`,其內容為 `

Hello World

` 的標記。無需額外檔案。 + +--- + +## Frequently Asked Questions (FAQs) + +**Q: Does this work with external URLs (e.g., images hosted on a CDN)?** +A: Yes. Aspose.HTML will download the remote resource, then pass it to `HandleResource`. Just be aware of network latency and possible authentication requirements. + +**Q: Can I set a custom name for the main HTML file inside the ZIP?** +A: By default it’s `index.html`. To rename it, you’d need to post‑process the ZIP (e.g., using `System.IO.Compression.ZipArchive`) after `Save` completes. + +**Q: What if I need to zip multiple HTML documents together?** +A: Create a separate `HTMLDocument` for each page and call `Save` on the same `MemoryZipHandler`. The handler will keep appending resources, resulting in a multi‑page ZIP. + +## Conclusion + +現在你已掌握一套完整的 **how to zip HTML** 作法,透過 **custom resource handler** 實現 **save HTML as zip**、**convert HTML to zip** 與 **save HTML to zip**,全程不觸碰檔案系統。此方法輕量、全記憶體,十分適合 Web API、背景工作或任何需要即時傳送 HTML 包的 .NET 服務。 + +準備好下一步了嗎?試著將處理程式再加入 `System.IO.Compression.GZipStream` 進一步壓縮輸出,或將它整合到 ASP.NET Core 控制器中,直接回傳 ZIP 給瀏覽器。可能性無限,而你已擁有了堅實的基礎。 + +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/hongkong/net/rendering-html-documents/_index.md b/html/hongkong/net/rendering-html-documents/_index.md index dcea15c4c..209ab0325 100644 --- a/html/hongkong/net/rendering-html-documents/_index.md +++ b/html/hongkong/net/rendering-html-documents/_index.md @@ -45,6 +45,7 @@ Aspose.HTML for .NET 因其豐富的功能、優秀的文件和活躍的社群 ### [如何將 HTML 渲染為 PNG – 完整 C# 指南](./how-to-render-html-as-png-complete-c-guide/) 學習使用 Aspose.HTML for .NET 在 C# 中將 HTML 渲染為 PNG,涵蓋完整步驟與最佳實踐。 + ### [從 HTML 建立 PNG – 完整 C# 渲染指南](./create-png-from-html-full-c-rendering-guide/) 學習如何使用 Aspose.HTML for .NET 以 C# 完整渲染 HTML 並將其保存為 PNG 圖像。 @@ -69,6 +70,9 @@ Aspose.HTML for .NET 因其豐富的功能、優秀的文件和活躍的社群 ### [如何使用 Aspose 將 HTML 渲染為 PNG – 完整指南](./how-to-render-html-to-png-with-aspose-complete-guide/) 完整步驟教您使用 Aspose.HTML for .NET 將 HTML 轉換為 PNG 圖像,掌握所有設定與最佳實踐。 +### [在 C# 中將 HTML 渲染為 PNG – 完整步驟指南](./render-html-to-png-in-c-complete-step-by-step-guide/) +一步步教您使用 Aspose.HTML for .NET 在 C# 中將 HTML 轉換為 PNG 圖像,掌握所有設定與最佳實踐。 + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/hongkong/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/hongkong/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..79feb5d30 --- /dev/null +++ b/html/hongkong/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-02-21 +description: 使用 Aspose.HTML 快速將 HTML 渲染為 PNG。了解如何將 HTML 轉換為圖像、設定圖像寬度與高度,以及在 C# 中僅用幾行程式碼將 + HTML 儲存為 PNG。 +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: zh-hant +og_description: 使用 Aspose.HTML 將 HTML 渲染為 PNG。本教學示範如何將 HTML 轉換為圖像、設定圖像寬度與高度,並在 C# + 中將 HTML 儲存為 PNG。 +og_title: 在 C# 中將 HTML 渲染為 PNG – 完整指南 +tags: +- Aspose.HTML +- C# +- Image Rendering +title: 在 C# 中將 HTML 渲染為 PNG – 完整逐步指南 +url: /zh-hant/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG – 完整逐步指南 + +是否曾需要 **將 HTML 轉換為 PNG**,卻不確定該選哪個函式庫或如何設定輸出?你並不孤單。許多開發者在嘗試 *將 HTML 轉成影像* 用於電郵縮圖、報告快照或自動化 UI 測試時,都會卡在同一個問題上。 + +在本教學中,我們將示範一個實用、可直接執行的範例,說明如何 **將 HTML 儲存為 PNG**、控制影像尺寸,並微調渲染品質——全部只需幾行程式碼,使用 Aspose.HTML for .NET。完成後,你將得到一段可重複使用的程式碼,隨時可以放入任何 C# 專案。 + +## 需要的環境 + +在開始之前,請先確認你已具備: + +- **.NET 6.0 或更新版本**(此 API 同時支援 .NET Framework、.NET Core 與 .NET 5+) +- 已在專案中安裝 **Aspose.HTML for .NET** NuGet 套件(`Aspose.Html`) +- 基本的 C# 語法概念——不需要任何進階知識 +- 一個可寫入的輸出資料夾,用來放產生的 PNG + +就這些。無需額外 SDK、外部二進位檔,只要一個 NuGet 參考即可。 + +## Render HTML to PNG – 設定文件 + +首先,我們建立一個 `HTMLDocument` 物件,裡面放入要 rasterize 的標記。HTML 可以從字串、檔案,甚至 URL 載入。為了說明,我們先以簡單的內嵌字串為例。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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 像素。 + +![render html to png output example](output.png) + +> **預期輸出:** 一個 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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Miért fontos:** A dokumentum memóriában tartásával elkerülhetjük a lemez‑latenciát, és a teljes művelet alkalmas lesz felhő‑függvények vagy mikro‑szolgáltatások számára. + +## 2. lépés – Egyedi erőforráskezelő felépítése (Custom Resource Handler) + +Az Aspose.HTML minden külső eszköz (képek, CSS, betűkészletek) felfedezésekor meghívja a `ResourceHandler.HandleResource`‑t. Ha minden alkalommal ugyanazt a `MemoryStream`‑et adjuk vissza, az összes erőforrást egyetlen ZIP‑csomagba tudjuk összegyűjteni. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro tipp:** Ha korlátozni szeretnéd a létrejövő ZIP méretét, a `zipStream`‑et becsomagolhatod egy `LimitedStream`‑be, és dobj kivételt, ha a határ túllépésre kerül. + +## 3. lépés – Dokumentum mentése ZIP csomagként (Save HTML as ZIP) + +Most összekapcsoljuk a részeket. Létrehozzuk a kezelőnket, megkérjük az Aspose.HTML‑t, hogy mentse a dokumentumot `SaveFormat.Zip` formátumban, majd kinyerjük a nyers byte‑okat. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +Ekkor a `zipBytes` egy tökéletesen érvényes ZIP‑fájlt tartalmaz, amelyet: + +* Visszaadhatsz egy Web API‑ból (`File(zipBytes, "application/zip", "page.zip")`); +* Feltölthetsz az Azure Blob Storage‑ba; +* Küldhetsz egy socketen keresztül egy másik szolgáltatásnak. + +## 4. lépés – Kimenet ellenőrzése (Convert HTML to ZIP – Quick Test) + +Egy gyors ellenőrzéshez írd a byte‑okat lemezre (csak hibakereséshez), majd nyisd meg a archívumot bármelyik ZIP‑nézővel. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +Amikor megnyitod a `debug_output.zip` fájlt, a következőket kell látnod: + +* `index.html` (az eredeti markup) +* Az összes hivatkozott kép, CSS‑fájl vagy betűkészlet, amely mellé van ágyazva. + +> **Miért működik:** Az Aspose.HTML a fő HTML‑fájlt tekinti az első erőforrásnak, majd a megtalált összes kapcsolódó eszközt a felfedezési sorrendben stream‑eli. A mi kezelőnk mindet egy `MemoryStream`‑be gyűjti, amelyet a könyvtár ZIP‑archívummá finalizál. + +## 5. lépés – Gyakori szélsőséges esetek kezelése (Save HTML to ZIP Best Practices) + +### Több CSS‑fájl + +Ha az oldal több stíluslapra hivatkozik, mindegyik külön bejegyzésként kerül hozzáadásra. Nem szükséges extra kód, de érdemes lehet elnevezési konvenciót alkalmazni (pl. `styles/style1.css`), hogy elkerüld az ütközéseket. + +### Nagy bináris erőforrások + +Nagy képek (>10 MB) esetén fontold meg, hogy közvetlenül egy fájl‑alapú stream‑re írod őket a tiszta `MemoryStream` helyett. Cseréld le a `MemoryStream`‑et egy `FileStream`‑re a `MemoryZipHandler`‑ben, és módosítsd a `GetResult` metódust ennek megfelelően. + +### Kódolási problémák + +Az Aspose.HTML tiszteletben tartja a HTML fejlécekben deklarált karakterkészletet. Ha UTF‑8 kimenetet szeretnél, győződj meg róla, hogy a `` tag jelen van, mielőtt létrehoznád a `HTMLDocument`‑ot. + +## Teljes működő példa (Save HTML to ZIP) + +Az alábbi program teljes, beilleszthető egy konzol‑alkalmazásba, és azonnal futtatható. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Várt kimenet:** +``` +ZIP created – 1234 bytes +``` + +A `output.zip` megnyitásakor látható lesz az `index.html`, amely a `

Hello World

` markup‑ot tartalmazza. Nem volt szükség extra fájlokra. + +--- + +## Gyakran Ismételt Kérdések (FAQs) + +**Q: Működik ez külső URL‑ekkel (pl. CDN‑en tárolt képek)?** +A: Igen. Az Aspose.HTML letölti a távoli erőforrást, majd átadja a `HandleResource`‑nek. Csak vedd figyelembe a hálózati késleltetést és az esetleges hitelesítési követelményeket. + +**Q: Beállíthatok egyedi nevet a fő HTML‑fájlhoz a ZIP‑ben?** +A: Alapértelmezés szerint `index.html`. Ha átnevezni szeretnéd, a `Save` befejezése után utófeldolgozással (pl. `System.IO.Compression.ZipArchive`) kell módosítanod a ZIP‑et. + +**Q: Mit tehetek, ha több HTML‑dokumentumot kell egyszerre zip‑elni?** +A: Hozz létre egy külön `HTMLDocument`‑ot minden oldalhoz, és hívd meg a `Save`‑t ugyanazon a `MemoryZipHandler`‑en. A kezelő folytatja az erőforrások hozzáfűzését, így többoldalas ZIP jön létre. + +--- + +## Összegzés + +Most már rendelkezel egy robusztus **hogyan zip‑eljük a HTML‑t** recepttel, amely egy **egyedi erőforráskezelőt** használ a **HTML‑t ZIP‑ként mentéséhez**, a **convert HTML to zip** és a **save HTML to zip** feladatokhoz – mindezt a fájlrendszer érintése nélkül. A megközelítés könnyű, teljesen memória‑alapú, és tökéletesen illeszkedik web‑API‑khoz, háttér‑feladatokhoz vagy bármely .NET szolgáltatáshoz, amelynek futásidőben kell HTML‑csomagokat szállítania. + +Készen állsz a következő lépésre? Próbáld meg a kezelőt tovább tömöríteni a `System.IO.Compression.GZipStream`‑mel, vagy integráld egy ASP.NET Core vezérlőbe, amely közvetlenül a böngészőnek adja vissza a ZIP‑et. A lehetőségek határtalanok, és most már megvan az alap, amire építhetsz. + +Boldog 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/hungarian/net/rendering-html-documents/_index.md b/html/hungarian/net/rendering-html-documents/_index.md index 39529197d..b4e23e20d 100644 --- a/html/hungarian/net/rendering-html-documents/_index.md +++ b/html/hungarian/net/rendering-html-documents/_index.md @@ -44,6 +44,8 @@ Most, hogy be van állítva az Aspose.HTML for .NET, itt az ideje, hogy felfedez Tanulja meg az Aspose.HTML for .NET használatát: Manipuláljon HTML-t, konvertáljon különféle formátumokba stb. Merüljön el ebben az átfogó oktatóanyagban! ### [HTML renderelése PNG-ként – Teljes C# útmutató](./how-to-render-html-as-png-complete-c-guide/) Ismerje meg, hogyan renderelhet HTML-t PNG formátumba C#-ban az Aspose.HTML segítségével, lépésről lépésre útmutató. +### [HTML renderelése PNG-be C#-ban – Teljes lépésről‑lépésre útmutató](./render-html-to-png-in-c-complete-step-by-step-guide/) +Tanulja meg, hogyan renderelhet HTML-t PNG formátumba C#-ban az Aspose.HTML segítségével, részletes, lépésről‑lépésre útmutató. ### [Az EPUB megjelenítése XPS-ként .NET-ben az Aspose.HTML segítségével](./render-epub-as-xps/) Ebben az átfogó oktatóanyagban megtudhatja, hogyan hozhat létre és jeleníthet meg HTML-dokumentumokat az Aspose.HTML for .NET segítségével. Merüljön el a HTML-kezelés, a webkaparás és egyebek világában. ### [Renderelési időtúllépés .NET-ben az Aspose.HTML-lel](./rendering-timeout/) diff --git a/html/hungarian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/hungarian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..e2431cca2 --- /dev/null +++ b/html/hungarian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-02-21 +description: Renderelje a HTML-t gyorsan PNG formátumba az Aspose.HTML segítségével. + Ismerje meg, hogyan konvertálhatja a HTML-t képpé, állíthatja be a kép szélességét + és magasságát, valamint mentheti a HTML-t PNG‑ként néhány C# sorral. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: hu +og_description: HTML renderelése PNG-re az Aspose.HTML segítségével. Ez az útmutató + bemutatja, hogyan konvertálhatja a HTML-t képpé, állíthatja be a kép szélességét + és magasságát, valamint hogyan mentheti a HTML-t PNG formátumban C#-ban. +og_title: HTML renderelése PNG-re C#-ban – Teljes útmutató +tags: +- Aspose.HTML +- C# +- Image Rendering +title: HTML renderelése PNG-be C#-ban – Teljes lépésről‑lépésre útmutató +url: /hu/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG – Complete Step‑by‑Step Guide + +Valaha is szükséged volt **HTML PNG‑re renderelésére**, de nem tudtad, melyik könyvtárat válaszd, vagy hogyan állítsd be a kimenetet? Nem vagy egyedül. Sok fejlesztő ugyanazon a problémán akad el, amikor *HTML‑t képpé* akar konvertálni e‑mail bélyegképekhez, jelentéspillanatokhoz vagy automatizált UI‑tesztekhez. + +Ebben az útmutatóban egy gyakorlati, azonnal futtatható példán keresztül mutatjuk be, hogyan **mentheted el az HTML‑t PNG‑ként**, hogyan szabályozhatod a kép méreteit, és hogyan finomíthatod a renderelés minőségét – mindezt néhány sor kóddal az Aspose.HTML for .NET segítségével. A végére egy újrahasználható kódrészletet kapsz, amelyet bármely C# projektbe beilleszthetsz. + +## What You’ll Need + +Mielőtt belevágnánk, győződj meg róla, hogy rendelkezel a következőkkel: + +- **.NET 6.0 vagy újabb** (az API működik .NET Framework‑kel, .NET Core‑ral és .NET 5+‑tel) +- **Aspose.HTML for .NET** NuGet csomag (`Aspose.Html`) telepítve a projektedben. +- Alapvető C# szintaxis ismeret – semmi különös nem kell. +- Egy kimeneti mappa, ahová a generált PNG‑t írni fogja a program. + +Ennyi. Nincs szükség extra SDK‑ra, külső binárisokra, csak egyetlen NuGet hivatkozásra. + +## Render HTML to PNG – Set Up the Document + +Az első lépés egy `HTMLDocument` objektum létrehozása, amely a rasterizálandó markup‑ot tartalmazza. HTML‑t betölthetsz egy stringből, fájlból vagy akár URL‑ből is. Áttekinthetőség kedvéért egy egyszerű inline string‑gel kezdünk. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![render html to png output example](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Mengapa ini penting:** Dengan menyimpan dokumen di memori kita menghindari latensi disk dan membuat seluruh operasi cocok untuk fungsi cloud atau micro‑service. + +## Langkah 2 – Bangun Custom Resource Handler (Custom Resource Handler) + +Aspose.HTML memanggil `ResourceHandler.HandleResource` untuk setiap aset eksternal yang ditemukannya (gambar, CSS, font). Dengan mengembalikan `MemoryStream` yang sama setiap kali, kita dapat menyalurkan semua sumber daya tersebut ke dalam satu paket ZIP. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Tip profesional:** Jika Anda perlu membatasi ukuran ZIP yang dihasilkan, Anda dapat membungkus `zipStream` dalam `LimitedStream` dan melempar pengecualian ketika batas terlampaui. + +## Langkah 3 – Simpan Dokumen sebagai Paket ZIP (Save HTML as ZIP) + +Sekarang kita mengikat semuanya bersama. Kita menginstansiasi handler kita, meminta Aspose.HTML menyimpan dokumen dalam `SaveFormat.Zip`, dan akhirnya mengambil byte mentahnya. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +Pada titik ini `zipBytes` berisi file ZIP yang sepenuhnya valid yang dapat Anda: + +* Kembalikan dari Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Unggah ke Azure Blob Storage; +* Kirim melalui socket ke layanan lain. + +## Langkah 4 – Verifikasi Output (Convert HTML to ZIP – Quick Test) + +Pemeriksaan cepat adalah menulis byte ke disk (hanya untuk debugging) dan membuka arsip dengan penampil ZIP apa pun. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +Saat Anda membuka `debug_output.zip` Anda akan melihat: + +* `index.html` (markup asli) +* Semua gambar, file CSS, atau font yang direferensikan tersemat di sampingnya. + +> **Mengapa ini berhasil:** Aspose.HTML memperlakukan file HTML utama sebagai sumber daya pertama, kemudian menyalurkan setiap aset yang terhubung dalam urutan yang ditemukannya. Handler kami mengagregasi semuanya ke dalam `MemoryStream` yang sama, yang kemudian diselesaikan oleh perpustakaan menjadi arsip ZIP. + +## Langkah 5 – Menangani Kasus Tepi Umum (Save HTML to ZIP Best Practices) + +### Beberapa File CSS + +Jika halaman Anda menautkan ke beberapa stylesheet, masing‑masing akan ditambahkan sebagai entri terpisah. Tidak diperlukan kode tambahan, tetapi Anda mungkin ingin menerapkan konvensi penamaan (misalnya, `styles/style1.css`) untuk menghindari bentrok. + +### Sumber Daya Biner Besar + +Untuk gambar berukuran besar (>10 MB) pertimbangkan untuk menyalurkannya langsung ke stream berbasis file alih‑alih `MemoryStream` murni. Ganti `MemoryStream` dengan `FileStream` di `MemoryZipHandler` dan sesuaikan `GetResult` sesuai kebutuhan. + +### Masalah Encoding + +Aspose.HTML menghormati charset yang dideklarasikan di header HTML. Jika Anda memerlukan output UTF‑8, pastikan tag `` ada sebelum Anda membuat `HTMLDocument`. + +## Contoh Lengkap yang Berfungsi (Save HTML to ZIP) + +Berikut adalah program lengkap yang dapat Anda tempel ke aplikasi console dan jalankan apa adanya. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Output yang diharapkan:** +``` +ZIP created – 1234 bytes +``` + +Membuka `output.zip` menampilkan `index.html` yang berisi markup `

Hello World

`. Tidak ada file tambahan yang diperlukan. + +--- + +## Pertanyaan yang Sering Diajukan (FAQs) + +**T: Apakah ini bekerja dengan URL eksternal (misalnya, gambar yang dihosting di CDN)?** +J: Ya. Aspose.HTML akan mengunduh sumber daya remote, lalu meneruskannya ke `HandleResource`. Hanya perlu memperhatikan latensi jaringan dan kemungkinan kebutuhan autentikasi. + +**T: Bisakah saya mengatur nama khusus untuk file HTML utama di dalam ZIP?** +J: Secara default namanya `index.html`. Untuk menggantinya, Anda harus memproses ZIP setelah `Save` selesai (misalnya, menggunakan `System.IO.Compression.ZipArchive`). + +**T: Bagaimana jika saya perlu mengompres beberapa dokumen HTML sekaligus?** +J: Buat `HTMLDocument` terpisah untuk setiap halaman dan panggil `Save` pada `MemoryZipHandler` yang sama. Handler akan terus menambahkan sumber daya, menghasilkan ZIP multi‑halaman. + +--- + +## Kesimpulan + +Anda kini memiliki resep solid **cara mengompres HTML** yang memanfaatkan **custom resource handler** untuk **save HTML as zip**, **convert HTML to zip**, dan **save HTML to zip**—semua tanpa menyentuh sistem file. Pendekatan ini ringan, sepenuhnya dalam memori, dan cocok untuk API web, pekerjaan latar belakang, atau layanan .NET apa pun yang perlu mengirim bundel HTML secara langsung. + +Siap untuk langkah selanjutnya? Cobalah memperluas handler untuk mengompres output lebih jauh dengan `System.IO.Compression.GZipStream`, atau integrasikan ke dalam controller ASP.NET Core yang mengembalikan ZIP langsung ke browser. Langit adalah batasnya, dan kini Anda memiliki fondasi untuk membangunnya. + +Selamat coding! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/indonesian/net/rendering-html-documents/_index.md b/html/indonesian/net/rendering-html-documents/_index.md index b7c974319..8200ef3b3 100644 --- a/html/indonesian/net/rendering-html-documents/_index.md +++ b/html/indonesian/net/rendering-html-documents/_index.md @@ -68,6 +68,9 @@ Pelajari cara menggunakan Aspose untuk mengonversi HTML menjadi PNG dengan pandu ### [Cara Merender HTML ke PNG dengan Aspose – Panduan Lengkap](./how-to-render-html-to-png-with-aspose-complete-guide/) Pelajari cara merender HTML menjadi PNG menggunakan Aspose dengan panduan lengkap langkah demi langkah. +### [Render HTML ke PNG dalam C# – Panduan Lengkap Langkah‑demi‑Langkah](./render-html-to-png-in-c-complete-step-by-step-guide/) +Pelajari cara merender HTML menjadi PNG menggunakan C# dengan panduan langkah demi langkah yang lengkap. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/indonesian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/indonesian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3c68574f9 --- /dev/null +++ b/html/indonesian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-02-21 +description: Render HTML ke PNG dengan cepat menggunakan Aspose.HTML. Pelajari cara + mengonversi HTML ke gambar, mengatur lebar dan tinggi gambar, serta menyimpan HTML + sebagai PNG dalam beberapa baris kode C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: id +og_description: Render HTML ke PNG dengan Aspose.HTML. Tutorial ini menunjukkan cara + mengonversi HTML ke gambar, mengatur lebar dan tinggi gambar, serta menyimpan HTML + sebagai PNG dalam C#. +og_title: Render HTML ke PNG di C# – Panduan Lengkap +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Render HTML ke PNG di C# – Panduan Lengkap Langkah demi Langkah +url: /id/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML ke PNG – Panduan Lengkap Langkah‑per‑Langkah + +Pernah perlu **render HTML ke PNG** tapi tidak yakin library mana yang harus dipilih atau bagaimana mengonfigurasi outputnya? Anda tidak sendirian. Banyak pengembang mengalami hal yang sama ketika mencoba *mengonversi HTML ke gambar* untuk thumbnail email, snapshot laporan, atau pengujian UI otomatis. + +Dalam tutorial ini kami akan menelusuri contoh praktis yang siap dijalankan yang menunjukkan cara **menyimpan HTML sebagai PNG**, mengontrol dimensi gambar, dan menyesuaikan kualitas rendering—semua dengan beberapa baris kode menggunakan Aspose.HTML untuk .NET. Pada akhir tutorial Anda akan memiliki potongan kode yang dapat dipakai ulang dan dapat dimasukkan ke proyek C# mana pun. + +## Apa yang Anda Butuhkan + +Sebelum kita mulai, pastikan Anda memiliki: + +- **.NET 6.0 atau lebih baru** (API ini bekerja dengan .NET Framework, .NET Core, dan .NET 5+) +- Paket NuGet **Aspose.HTML untuk .NET** (`Aspose.Html`) yang sudah terpasang di proyek Anda. +- Pemahaman dasar tentang sintaks C#—tidak perlu hal yang rumit. +- Folder output tempat PNG yang dihasilkan akan disimpan. + +Itu saja. Tidak ada SDK tambahan, tidak ada binary eksternal, hanya satu referensi NuGet. + +## Render HTML ke PNG – Siapkan Dokumen + +Hal pertama yang kita lakukan adalah membuat objek `HTMLDocument` yang memuat markup yang ingin kita rasterisasi. Anda dapat memuat HTML dari string, file, atau bahkan URL. Untuk kejelasan kita akan memulai dengan string inline sederhana. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![contoh output render html ke png](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Perché è importante:** Tenendo il documento in memoria evitiamo la latenza del disco e rendiamo l'intera operazione adatta a funzioni cloud o micro‑servizi. + +## Passo 2 – Costruire un gestore di risorse personalizzato (Custom Resource Handler) + +Aspose.HTML chiama `ResourceHandler.HandleResource` per ogni asset esterno che scopre (immagini, CSS, font). Restituendo lo stesso `MemoryStream` ogni volta possiamo convogliare tutte quelle risorse in un unico pacchetto ZIP. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Consiglio esperto:** Se devi limitare la dimensione dello ZIP risultante, puoi avvolgere `zipStream` in un `LimitedStream` e lanciare un'eccezione quando il limite viene superato. + +## Passo 3 – Salvare il documento come pacchetto ZIP (Save HTML as ZIP) + +Ora uniamo tutto. Istanziano il nostro handler, chiediamo ad Aspose.HTML di salvare il documento con `SaveFormat.Zip` e infine estraiamo i byte grezzi. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +A questo punto `zipBytes` contiene un file ZIP perfettamente valido che puoi: + +* Restituire da una Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Caricare su Azure Blob Storage; +* Inviare tramite socket a un altro servizio. + +## Passo 4 – Verificare l'output (Convert HTML to ZIP – Quick Test) + +Un rapido controllo di coerenza consiste nello scrivere i byte su disco (solo per debug) e aprire l'archivio con qualsiasi visualizzatore ZIP. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +Quando apri `debug_output.zip` dovresti vedere: + +* `index.html` (il markup originale) +* Tutte le immagini, i file CSS o i font referenziati incorporati accanto ad esso. + +> **Perché funziona:** Aspose.HTML tratta il file HTML principale come la prima risorsa, poi trasmette ogni asset collegato nell'ordine in cui lo incontra. Il nostro handler li aggrega tutti nello stesso `MemoryStream`, che la libreria finalizza poi come archivio ZIP. + +## Passo 5 – Gestire casi particolari comuni (Save HTML to ZIP Best Practices) + +### Più file CSS + +Se la tua pagina collega diversi fogli di stile, ciascuno verrà aggiunto come voce separata. Non è necessario alcun codice aggiuntivo, ma potresti voler imporre una convenzione di denominazione (es. `styles/style1.css`) per evitare conflitti. + +### Risorse binarie di grandi dimensioni + +Per immagini molto grandi (>10 MB) considera di trasmetterle direttamente a uno stream basato su file invece di un puro `MemoryStream`. Sostituisci `MemoryStream` con un `FileStream` in `MemoryZipHandler` e adatta `GetResult` di conseguenza. + +### Problemi di codifica + +Aspose.HTML rispetta il charset dichiarato nell'header HTML. Se ti serve un output UTF‑8, assicurati che il tag `` sia presente prima di creare il `HTMLDocument`. + +## Esempio completo funzionante (Save HTML to ZIP) + +Di seguito trovi il programma completo da incollare in un'app console e eseguire così com'è. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Output previsto:** +``` +ZIP created – 1234 bytes +``` + +Aprendo `output.zip` vedrai `index.html` contenente il markup `

Hello World

`. Nessun file aggiuntivo è stato richiesto. + +--- + +## Domande frequenti (FAQs) + +**D: Funziona con URL esterne (es. immagini ospitate su un CDN)?** +R: Sì. Aspose.HTML scaricherà la risorsa remota, poi la passerà a `HandleResource`. Tieni presente la latenza di rete e eventuali requisiti di autenticazione. + +**D: Posso impostare un nome personalizzato per il file HTML principale dentro lo ZIP?** +R: Per impostazione predefinita è `index.html`. Per rinominarlo, dovrai post‑processare lo ZIP (ad esempio usando `System.IO.Compression.ZipArchive`) dopo il completamento di `Save`. + +**D: Cosa fare se devo comprimere più documenti HTML insieme?** +R: Crea un `HTMLDocument` separato per ogni pagina e chiama `Save` sullo stesso `MemoryZipHandler`. L'handler continuerà ad aggiungere risorse, producendo uno ZIP multi‑pagina. + +--- + +## Conclusione + +Ora disponi di una ricetta solida, **how to zip HTML**, che sfrutta un **custom resource handler** per **save HTML as zip**, **convert HTML to zip** e **save HTML to zip**—tutto senza toccare il file system. L'approccio è leggero, completamente in‑memory, e si integra perfettamente in Web API, job di background o qualsiasi servizio .NET che deve spedire bundle HTML al volo. + +Pronto per il passo successivo? Prova a estendere il gestore per comprimere ulteriormente l'output con `System.IO.Compression.GZipStream`, o integralo in un controller ASP.NET Core che restituisce lo ZIP direttamente al browser. Il cielo è il limite, e ora hai le basi per costruire sopra. + +Buon coding! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/italian/net/rendering-html-documents/_index.md b/html/italian/net/rendering-html-documents/_index.md index 1239e762f..3053aaabe 100644 --- a/html/italian/net/rendering-html-documents/_index.md +++ b/html/italian/net/rendering-html-documents/_index.md @@ -48,6 +48,8 @@ Scopri come convertire HTML in PNG usando C# con Aspose.HTML. Segui la guida pas Scopri come convertire facilmente file HTML in PNG usando Aspose.HTML con questa guida completa passo‑passo. ### [Come usare Aspose per rendere HTML in PNG – Guida passo‑passo](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) Scopri come convertire facilmente file HTML in PNG usando Aspose.HTML per .NET con questa guida dettagliata. +### [Renderizza HTML in PNG in C# – Guida completa passo‑passo](./render-html-to-png-in-c-complete-step-by-step-guide/) +Scopri come convertire HTML in PNG usando C# con Aspose.HTML, seguendo una guida dettagliata passo‑passo per risultati perfetti. ### [Crea PNG da HTML – Guida completa al rendering C#](./create-png-from-html-full-c-rendering-guide/) Scopri come generare PNG da HTML usando Aspose.HTML per .NET con una guida completa passo passo in C#. ### [Renderizza EPUB come XPS in .NET con Aspose.HTML](./render-epub-as-xps/) diff --git a/html/italian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/italian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..06f050d5b --- /dev/null +++ b/html/italian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-02-21 +description: Renderizza HTML in PNG rapidamente con Aspose.HTML. Scopri come convertire + HTML in immagine, impostare larghezza e altezza dell'immagine e salvare HTML come + PNG in poche righe di C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: it +og_description: Converti HTML in PNG con Aspose.HTML. Questo tutorial mostra come + convertire HTML in immagine, impostare larghezza e altezza dell'immagine e salvare + HTML come PNG in C#. +og_title: Converti HTML in PNG in C# – Guida completa +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Renderizza HTML in PNG con C# – Guida completa passo passo +url: /it/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +Let's craft final output.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG – Guida Completa Passo‑per‑Passo + +Ti è mai capitato di dover **render HTML to PNG** ma non sapevi quale libreria scegliere o come configurare l'output? Non sei solo. Molti sviluppatori si trovano nella stessa situazione quando provano a *convert HTML to image* per miniature di email, snapshot di report o test UI automatizzati. + +In questo tutorial percorreremo un esempio pratico, pronto‑da‑eseguire, che ti mostra come **save HTML as PNG**, controllare le dimensioni dell'immagine e perfezionare la qualità del rendering—tutto con poche righe usando Aspose.HTML for .NET. Alla fine avrai uno snippet riutilizzabile da inserire in qualsiasi progetto C#. + +## What You’ll Need + +Prima di immergerci, assicurati di avere: + +- **.NET 6.0 o successivo** (l'API funziona con .NET Framework, .NET Core e .NET 5+) +- **Aspose.HTML for .NET** pacchetto NuGet (`Aspose.Html`) installato nel tuo progetto. +- Una conoscenza di base della sintassi C#—nulla di complesso. +- Una cartella di output dove verrà scritto il PNG generato. + +That’s it. No extra SDKs, no external binaries, just a single NuGet reference. + +## Render HTML to PNG – Set Up the Document + +La prima cosa che facciamo è creare un oggetto `HTMLDocument` che contiene il markup che vogliamo rasterizzare. Puoi caricare HTML da una stringa, da un file o anche da un URL. Per chiarezza inizieremo con una semplice stringa inline. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![esempio di output render html to png](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **なぜ重要か:** ドキュメントをメモリ上に保持することでディスク遅延を回避でき、クラウド関数やマイクロサービスでも問題なく実行できます。 + +## Step 2 – Build a Custom Resource Handler (Custom Resource Handler) + +Aspose.HTML は外部アセット(画像、CSS、フォント)を検出するたびに `ResourceHandler.HandleResource` を呼び出します。同じ `MemoryStream` を毎回返すことで、すべてのリソースを 1 つの ZIP パッケージに流し込むことができます。 + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **プロのコツ:** 生成される ZIP のサイズを制限したい場合は、`zipStream` を `LimitedStream` でラップし、上限を超えたら例外をスローさせることができます。 + +## Step 3 – Save the Document as a ZIP Package (Save HTML as ZIP) + +ここで全体を結びつけます。ハンドラをインスタンス化し、Aspose.HTML に `SaveFormat.Zip` でドキュメントを保存させ、最終的に生のバイト列を取得します。 + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +この時点で `zipBytes` には有効な ZIP ファイルが格納され、以下のように利用できます。 + +* Web API から返す (`File(zipBytes, "application/zip", "page.zip")`); +* Azure Blob Storage にアップロード; +* ソケット経由で別サービスへ送信。 + +## Step 4 – Verify the Output (Convert HTML to ZIP – Quick Test) + +簡易的な検証として、デバッグ目的でバイト列をディスクに書き出し、任意の ZIP ビューアで開いてみます。 + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +`debug_output.zip` を開くと、以下が確認できるはずです。 + +* `index.html`(元のマークアップ) +* 参照されている画像、CSS ファイル、フォントが同梱されている + +> **なぜ動くのか:** Aspose.HTML はメインの HTML ファイルを最初のリソースとして扱い、検出した順にリンクされたアセットをストリームします。ハンドラがそれらすべてを同一の `MemoryStream` に集約し、ライブラリ側で最終的に ZIP アーカイブとして完結させます。 + +## Step 5 – Handling Common Edge Cases (Save HTML to ZIP Best Practices) + +### Multiple CSS Files + +ページが複数のスタイルシートをリンクしている場合、それぞれが別個のエントリとして追加されます。特別なコードは不要ですが、名前衝突を防ぐために `styles/style1.css` のような命名規則を設けると良いでしょう。 + +### Large Binary Resources + +10 MB 超の大容量画像などは、純粋な `MemoryStream` ではなくファイルベースのストリームに直接ストリーミングすることを検討してください。`MemoryZipHandler` の `MemoryStream` を `FileStream` に置き換え、`GetResult` もそれに合わせて調整します。 + +### Encoding Issues + +Aspose.HTML は HTML ヘッダーで宣言された文字セットを尊重します。UTF‑8 出力が必要な場合は、`HTMLDocument` を作成する前に `` タグが含まれていることを確認してください。 + +## Full Working Example (Save HTML to ZIP) + +以下はコンソールアプリに貼り付けてそのまま実行できる、完全なプログラムです。 + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**期待される出力:** +``` +ZIP created – 1234 bytes +``` + +`output.zip` を開くと、`index.html` に `

Hello World

` のマークアップが含まれていることが確認できます。余分なファイルは不要です。 + +--- + +## Frequently Asked Questions (FAQs) + +**Q: 外部 URL(例: CDN 上の画像)でも動作しますか?** +A: はい。Aspose.HTML がリモートリソースをダウンロードし、`HandleResource` に渡します。ネットワーク遅延や認証が必要な場合があることだけは留意してください。 + +**Q: ZIP 内のメイン HTML ファイル名をカスタムにできますか?** +A: デフォルトは `index.html` です。名前を変更したい場合は、`Save` 完了後に `System.IO.Compression.ZipArchive` などで後処理する必要があります。 + +**Q: 複数の HTML ドキュメントをまとめて ZIP にしたい場合は?** +A: 各ページごとに別々の `HTMLDocument` を作成し、同じ `MemoryZipHandler` に対して `Save` を呼び出します。ハンドラはリソースを順次追加し、マルチページ ZIP が生成されます。 + +--- + +## Conclusion + +これで **HTML を ZIP にする** 方法と、**カスタムリソースハンドラ** を利用して **HTML を ZIP として保存**、**HTML を ZIP に変換**、**HTML を ZIP に保存** するレシピが手に入りました。ファイルシステムに触れず、完全にインメモリで処理できるため、Web API、バックグラウンドジョブ、任意の .NET サービスで HTML バンドルをオンザフライで配布するシナリオに最適です。 + +次のステップに進みませんか? ハンドラに `System.IO.Compression.GZipStream` を組み込んでさらに圧縮したり、ASP.NET Core コントローラで直接 ZIP をブラウザに返す実装に統合したりしてみてください。可能性は無限大です。さあ、基盤は整いましたので、自由に拡張してみましょう。 + +Happy coding! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/japanese/net/rendering-html-documents/_index.md b/html/japanese/net/rendering-html-documents/_index.md index 0d786f01c..b8eca7dc6 100644 --- a/html/japanese/net/rendering-html-documents/_index.md +++ b/html/japanese/net/rendering-html-documents/_index.md @@ -68,6 +68,9 @@ Aspose.HTML for .NET を使い、HTML を高品質な PNG 画像に変換する ### [HTML から PNG を作成 – 完全な C# レンダリング ガイド](./create-png-from-html-full-c-rendering-guide/) Aspose.HTML for .NET を使用して、HTML を PNG 画像に変換する完全な C# ガイドです。ステップバイステップで解説します。 +### [C# で HTML を PNG にレンダリングする完全ステップバイステップガイド](./render-html-to-png-in-c-complete-step-by-step-guide/) +Aspose.HTML for .NET を使用し、C# で HTML を PNG 画像に変換する手順をステップバイステップで完全解説します。 + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/japanese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/japanese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..c06feef53 --- /dev/null +++ b/html/japanese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-02-21 +description: Aspose.HTMLでHTMLを高速にPNGへレンダリング。HTMLを画像に変換し、画像の幅と高さを設定し、C#数行でHTMLをPNGとして保存する方法を学びましょう。 +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: ja +og_description: Aspose.HTML を使用して HTML を PNG にレンダリングします。このチュートリアルでは、HTML を画像に変換し、画像の幅と高さを設定し、C# + で HTML を PNG として保存する方法を示します。 +og_title: C#でHTMLをPNGにレンダリング – 完全ガイド +tags: +- Aspose.HTML +- C# +- Image Rendering +title: C#でHTMLをPNGにレンダリングする – 完全ステップバイステップガイド +url: /ja/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML を PNG にレンダリング – 完全ステップバイステップガイド + +HTML を PNG に **レンダリング** したいけど、どのライブラリを選べばいいか、出力をどう設定すればいいか分からないことはありませんか?同じ壁にぶつかる開発者は多いです。メールのサムネイル、レポートのスナップショット、あるいは自動 UI テストのために *HTML を画像に変換* したいときに特にです。 + +このチュートリアルでは、Aspose.HTML for .NET を使って **HTML を PNG として保存** し、画像サイズを制御し、レンダリング品質を調整する方法を、数行のコードで実演します。最後まで読めば、任意の C# プロジェクトにすぐ組み込める再利用可能なスニペットが手に入ります。 + +## 必要なもの + +始める前に以下を用意してください。 + +- **.NET 6.0 以降**(API は .NET Framework、.NET Core、.NET 5+ でも動作します) +- **Aspose.HTML for .NET** NuGet パッケージ(`Aspose.Html`)をプロジェクトにインストール済み +- 基本的な C# 文法の理解(特別な知識は不要です) +- 生成された PNG を書き出す出力フォルダー + +以上です。余計な SDK や外部バイナリは不要で、NuGet 参照だけで完了します。 + +## Render HTML to PNG – ドキュメントの設定 + +まず最初に、ラスタライズしたいマークアップを保持する `HTMLDocument` オブジェクトを作成します。HTML は文字列、ファイル、あるいは URL からロードできます。ここではシンプルなインライン文字列で始めます。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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 ピクセルの鮮明でアンチエイリアス処理されたテキストが表示されます。 + +![HTML を PNG にレンダリングした出力例](output.png) + +> **期待される出力:** 「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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **왜 중요한가:** 문서를 메모리에 보관함으로써 디스크 지연을 피하고, 클라우드 함수나 마이크로‑서비스에서도 전체 작업을 원활히 수행할 수 있습니다. + +## Step 2 – 커스텀 리소스 핸들러 구축 (Custom Resource Handler) + +Aspose.HTML는 발견한 외부 자산(이미지, CSS, 폰트)마다 `ResourceHandler.HandleResource`를 호출합니다. 매번 같은 `MemoryStream`을 반환하면 모든 리소스를 하나의 ZIP 패키지에 모을 수 있습니다. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **프로 팁:** 결과 ZIP의 크기를 제한하고 싶다면 `zipStream`을 `LimitedStream`으로 감싸고 제한 초과 시 예외를 발생시키면 됩니다. + +## Step 3 – 문서를 ZIP 패키지로 저장 (Save HTML as ZIP) + +이제 모든 것을 연결합니다. 핸들러를 인스턴스화하고 Aspose.HTML에 `SaveFormat.Zip`으로 문서를 저장하도록 요청한 뒤, 최종 바이트 배열을 추출합니다. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +이 시점에서 `zipBytes`는 다음과 같이 활용 가능한 완전한 ZIP 파일을 담고 있습니다: + +* Web API에서 반환 (`File(zipBytes, "application/zip", "page.zip")`); +* Azure Blob Storage에 업로드; +* 다른 서비스로 소켓 전송. + +## Step 4 – 출력 확인 (Convert HTML to ZIP – Quick Test) + +디버깅을 위해 바이트를 디스크에 쓰고 ZIP 뷰어로 열어보는 간단한 검증 단계입니다. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +`debug_output.zip`을 열면 다음이 보여야 합니다: + +* `index.html` (원본 마크업) +* 참조된 이미지, CSS 파일, 폰트 등이 함께 포함됨. + +> **왜 동작하는가:** Aspose.HTML는 메인 HTML 파일을 첫 번째 리소스로 처리하고, 발견 순서대로 각 연결된 자산을 스트리밍합니다. 우리의 핸들러는 이들을 모두 동일 `MemoryStream`에 모아 라이브러리가 최종적으로 ZIP 아카이브를 완성하도록 합니다. + +## Step 5 – 일반적인 엣지 케이스 처리 (Save HTML to ZIP Best Practices) + +### 다중 CSS 파일 + +페이지가 여러 스타일시트를 링크하면 각각 별도 엔트리로 추가됩니다. 추가 코드가 필요 없지만, 충돌을 방지하기 위해 `styles/style1.css`와 같은 네이밍 규칙을 적용하는 것이 좋습니다. + +### 대용량 바이너리 리소스 + +10 MB 이상 대형 이미지의 경우 순수 `MemoryStream` 대신 파일 기반 스트림으로 직접 스트리밍하는 것을 고려하세요. `MemoryZipHandler`에서 `MemoryStream`을 `FileStream`으로 교체하고 `GetResult`를 적절히 수정하면 됩니다. + +### 인코딩 문제 + +Aspose.HTML는 HTML 헤더에 선언된 charset을 따릅니다. UTF‑8 출력을 원한다면 `HTMLDocument`를 만들기 전에 `` 태그가 포함되어 있는지 확인하세요. + +## 전체 작동 예제 (Save HTML to ZIP) + +아래는 콘솔 앱에 그대로 붙여넣어 실행할 수 있는 완전한 프로그램입니다. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**예상 출력:** +``` +ZIP created – 1234 bytes +``` + +`output.zip`을 열면 `

Hello World

` 마크업을 담은 `index.html`이 보이며, 추가 파일은 없습니다. + +--- + +## Frequently Asked Questions (FAQs) + +**Q: 외부 URL(예: CDN에 호스팅된 이미지)도 동작하나요?** +A: 네. Aspose.HTML가 원격 리소스를 다운로드한 뒤 `HandleResource`에 전달합니다. 네트워크 지연 및 인증 요구 사항을 고려하세요. + +**Q: ZIP 내부의 메인 HTML 파일 이름을 커스텀하고 싶어요.** +A: 기본값은 `index.html`입니다. 이름을 바꾸려면 `Save`가 끝난 뒤 `System.IO.Compression.ZipArchive` 등을 사용해 ZIP을 후처리해야 합니다. + +**Q: 여러 HTML 문서를 한 번에 ZIP에 넣고 싶어요.** +A: 각 페이지마다 별도 `HTMLDocument`를 만들고 동일 `MemoryZipHandler`에 `Save`를 호출하면 됩니다. 핸들러가 리소스를 계속 추가해 다중 페이지 ZIP이 생성됩니다. + +--- + +## 결론 + +이제 **HTML을 ZIP으로 압축**하는 확실한 레시피를 갖게 되었습니다. **커스텀 리소스 핸들러**를 활용해 **HTML을 ZIP으로 저장**, **HTML을 ZIP으로 변환**, **HTML을 ZIP에 저장**하는 방법을 파일 시스템에 손대지 않고 구현했습니다. 가볍고 전부 메모리 내에서 동작하므로 웹 API, 백그라운드 작업, 혹은 HTML 번들을 즉시 전송해야 하는 모든 .NET 서비스에 적합합니다. + +다음 단계는? 핸들러에 `System.IO.Compression.GZipStream`을 적용해 압축률을 높이거나, ASP.NET Core 컨트롤러에 통합해 브라우저에 바로 ZIP을 반환해 보세요. 가능성은 무한하며, 이제 그 기반을 갖추었습니다. + +행복한 코딩 되세요! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/korean/net/rendering-html-documents/_index.md b/html/korean/net/rendering-html-documents/_index.md index 7178d36b0..5b911d10a 100644 --- a/html/korean/net/rendering-html-documents/_index.md +++ b/html/korean/net/rendering-html-documents/_index.md @@ -51,6 +51,9 @@ Aspose를 활용해 HTML을 PNG로 변환하는 과정을 단계별로 자세히 ### [Aspose를 사용하여 HTML을 PNG로 렌더링하는 완전 가이드](./how-to-render-html-to-png-with-aspose-complete-guide/) Aspose를 활용해 HTML을 PNG 이미지로 변환하는 전체 단계별 가이드를 확인하세요. +### [C#에서 HTML을 PNG로 렌더링 – 완전 단계별 가이드](./render-html-to-png-in-c-complete-step-by-step-guide/) +Aspose.HTML for .NET을 사용해 C#으로 HTML을 PNG 이미지로 변환하는 전체 과정을 단계별로 안내합니다. + ### [Aspose.HTML을 사용하여 .NET에서 EPUB를 XPS로 렌더링](./render-epub-as-xps/) 이 포괄적인 튜토리얼에서 Aspose.HTML for .NET으로 HTML 문서를 만들고 렌더링하는 방법을 알아보세요. HTML 조작, 웹 스크래핑 등의 세계로 뛰어드세요. ### [Aspose.HTML을 사용한 .NET에서의 렌더링 타임아웃](./rendering-timeout/) diff --git a/html/korean/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/korean/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..55e33aec8 --- /dev/null +++ b/html/korean/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-02-21 +description: Aspose.HTML으로 HTML을 빠르게 PNG로 렌더링하세요. HTML을 이미지로 변환하고, 이미지의 너비와 높이를 설정하며, + C# 몇 줄로 HTML을 PNG로 저장하는 방법을 배워보세요. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: ko +og_description: Aspose.HTML를 사용하여 HTML을 PNG로 렌더링합니다. 이 튜토리얼에서는 HTML을 이미지로 변환하고, 이미지의 + 너비와 높이를 설정하며, C#에서 HTML을 PNG로 저장하는 방법을 보여줍니다. +og_title: C#에서 HTML을 PNG로 렌더링하기 – 완전 가이드 +tags: +- Aspose.HTML +- C# +- Image Rendering +title: C#에서 HTML을 PNG로 렌더링하기 – 완전한 단계별 가이드 +url: /ko/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML을 PNG로 렌더링 – 완전 단계별 가이드 + +HTML을 PNG로 **렌더링**해야 하는데 어떤 라이브러리를 선택하고 출력을 어떻게 구성해야 할지 몰라 고민한 적 있나요? 혼자가 아닙니다. 많은 개발자들이 이메일 썸네일, 보고서 스냅샷, 자동 UI 테스트 등을 위해 *HTML을 이미지로 변환*하려 할 때 같은 장벽에 부딪힙니다. + +이 튜토리얼에서는 Aspose.HTML for .NET을 사용해 **HTML을 PNG로 저장**, 이미지 크기 제어, 렌더링 품질 조정 등을 몇 줄의 코드만으로 구현하는 실용적인 예제를 단계별로 살펴봅니다. 끝까지 따라오면 어떤 C# 프로젝트에도 바로 삽입할 수 있는 재사용 가능한 스니펫을 얻게 됩니다. + +## 준비 사항 + +시작하기 전에 다음을 준비하세요: + +- **.NET 6.0 이상** (API는 .NET Framework, .NET Core, .NET 5+에서도 동작) +- **Aspose.HTML for .NET** NuGet 패키지(`Aspose.Html`)가 프로젝트에 설치되어 있어야 합니다. +- C# 문법에 대한 기본 이해 – 특별한 지식은 필요 없습니다. +- 생성된 PNG가 저장될 출력 폴더. + +이것만 있으면 됩니다. 추가 SDK나 외부 바이너리는 필요 없으며, NuGet 참조 하나만 있으면 됩니다. + +## Render HTML to PNG – Set Up the Document + +먼저 래스터화할 마크업을 담는 `HTMLDocument` 객체를 생성합니다. 문자열, 파일, 혹은 URL에서 HTML을 로드할 수 있습니다. 여기서는 간단한 인라인 문자열을 사용합니다. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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 픽셀 크기로 표시됩니다. + +![render html to png 출력 예시](output.png) + +> **예상 출력:** 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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Dlaczego to ważne:** Trzymając dokument w pamięci, unikamy opóźnień dyskowych i czynimy całą operację odpowiednią dla funkcji chmurowych lub mikro‑serwisów. + +## Krok 2 – Zbuduj niestandardowy obsługiwacz zasobów (Custom Resource Handler) + +Aspose.HTML wywołuje `ResourceHandler.HandleResource` dla każdego zewnętrznego zasobu, który wykryje (obrazy, CSS, czcionki). Zwracając ten sam `MemoryStream` za każdym razem, możemy skierować wszystkie te zasoby do jednego pakietu ZIP. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro tip:** Jeśli musisz ograniczyć rozmiar wynikowego ZIP, możesz owinąć `zipStream` w `LimitedStream` i rzucić wyjątek, gdy limit zostanie przekroczony. + +## Krok 3 – Zapisz dokument jako pakiet ZIP (Save HTML as ZIP) + +Teraz łączymy wszystko razem. Tworzymy nasz obsługiwacz, prosimy Aspose.HTML o zapisanie dokumentu w formacie `SaveFormat.Zip`, a na koniec pobieramy surowe bajty. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +W tym momencie `zipBytes` zawiera w pełni prawidłowy plik ZIP, który możesz: + +* Zwrócić z Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Przesłać do Azure Blob Storage; +* Wysłać przez socket do innej usługi. + +## Krok 4 – Zweryfikuj wynik (Convert HTML to ZIP – Quick Test) + +Szybka kontrola polega na zapisaniu bajtów na dysk (tylko w celach debugowania) i otwarciu archiwum dowolnym przeglądarką ZIP. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +Po otwarciu `debug_output.zip` powinieneś zobaczyć: + +* `index.html` (pierwotny znacznik) +* Wszystkie odwołane obrazy, pliki CSS lub czcionki osadzone obok niego. + +> **Dlaczego to działa:** Aspose.HTML traktuje główny plik HTML jako pierwszy zasób, a następnie strumieniuje każdy połączony zasób w kolejności, w jakiej go napotka. Nasz obsługiwacz agreguje je wszystkie w tym samym `MemoryStream`, który biblioteka finalizuje jako archiwum ZIP. + +## Krok 5 – Obsługa typowych przypadków brzegowych (Save HTML to ZIP Best Practices) + +### Wiele plików CSS + +Jeśli strona odwołuje się do kilku arkuszy stylów, każdy zostanie dodany jako osobny wpis. Nie wymaga to dodatkowego kodu, ale warto wymusić konwencję nazewnictwa (np. `styles/style1.css`), aby uniknąć konfliktów. + +### Duże zasoby binarne + +Dla ogromnych obrazów (>10 MB) rozważ strumieniowanie ich bezpośrednio do strumienia opartego na pliku zamiast czystego `MemoryStream`. Zamień `MemoryStream` na `FileStream` w `MemoryZipHandler` i odpowiednio dostosuj `GetResult`. + +### Problemy z kodowaniem + +Aspose.HTML respektuje zestaw znaków zadeklarowany w nagłówku HTML. Jeśli potrzebujesz wyjścia w UTF‑8, upewnij się, że tag `` znajduje się w dokumencie przed utworzeniem `HTMLDocument`. + +## Pełny działający przykład (Save HTML to ZIP) + +Poniżej znajduje się kompletny program, który możesz wkleić do aplikacji konsolowej i uruchomić bez zmian. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Oczekiwany wynik:** +``` +ZIP created – 1234 bytes +``` + +Po otwarciu `output.zip` zobaczysz `index.html` zawierający znacznik `

Hello World

`. Nie były potrzebne żadne dodatkowe pliki. + +--- + +## Najczęściej zadawane pytania (FAQs) + +**Q: Czy to działa z zewnętrznymi URL‑ami (np. obrazami hostowanymi na CDN)?** +A: Tak. Aspose.HTML pobierze zdalny zasób, a następnie przekaże go do `HandleResource`. Pamiętaj jednak o opóźnieniach sieciowych i ewentualnych wymaganiach uwierzytelniania. + +**Q: Czy mogę ustawić własną nazwę głównego pliku HTML w archiwum ZIP?** +A: Domyślnie jest to `index.html`. Aby zmienić nazwę, musisz po‑procesować ZIP (np. używając `System.IO.Compression.ZipArchive`) po zakończeniu `Save`. + +**Q: Co zrobić, jeśli muszę spakować kilka dokumentów HTML razem?** +A: Utwórz osobny `HTMLDocument` dla każdej strony i wywołaj `Save` na tym samym `MemoryZipHandler`. Obsługiwacz będzie dopisywał zasoby, tworząc wielostronicowy ZIP. + +--- + +## Zakończenie + +Masz teraz solidny przepis **how to zip HTML**, który wykorzystuje **custom resource handler** do **save HTML as zip**, **convert HTML to zip** i **save HTML to zip** — wszystko bez dotykania systemu plików. Podejście jest lekkie, w pełni w pamięci i doskonale pasuje do Web API, zadań w tle lub dowolnej usługi .NET, która musi na bieżąco wysyłać pakiety HTML. + +Gotowy na kolejny krok? Spróbuj rozszerzyć obsługiwacz, aby dodatkowo kompresować wynik przy użyciu `System.IO.Compression.GZipStream`, lub zintegrować go z kontrolerem ASP.NET Core, który zwraca ZIP bezpośrednio do przeglądarki. Nie ma granic, a Ty masz już fundament, na którym możesz budować. + +Miłego 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/polish/net/rendering-html-documents/_index.md b/html/polish/net/rendering-html-documents/_index.md index 41f09366a..4b962530b 100644 --- a/html/polish/net/rendering-html-documents/_index.md +++ b/html/polish/net/rendering-html-documents/_index.md @@ -45,6 +45,7 @@ Naucz się pracować z Aspose.HTML dla .NET: Manipuluj HTML, konwertuj do różn ### [Jak renderować HTML jako PNG – Kompletny przewodnik C#](./how-to-render-html-as-png-complete-c-guide/) Pełny przewodnik C# pokazujący, jak przy użyciu Aspose.HTML renderować HTML jako PNG, krok po kroku. + ### [Jak używać Aspose do renderowania HTML do PNG – przewodnik krok po kroku](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) Naucz się, jak przy użyciu Aspose renderować HTML do formatu PNG w kilku prostych krokach. @@ -58,7 +59,7 @@ Dowiedz się, jak tworzyć i renderować dokumenty HTML za pomocą Aspose.HTML d Dowiedz się, jak skutecznie kontrolować limity czasu renderowania w Aspose.HTML dla .NET. Poznaj opcje renderowania i zapewnij płynne renderowanie dokumentów HTML. ### [Renderuj MHTML jako XPS w .NET za pomocą Aspose.HTML](./render-mhtml-as-xps/) - Naucz się renderować MHTML jako XPS w .NET z Aspose.HTML. Udoskonal swoje umiejętności manipulacji HTML i przyspiesz swoje projekty rozwoju sieci! +Naucz się renderować MHTML jako XPS w .NET z Aspose.HTML. Udoskonal swoje umiejętności manipulacji HTML i przyspiesz swoje projekty rozwoju sieci! Naucz się renderować MHTML jako XPS w .NET z Aspose.HTML. Udoskonal swoje umiejętności manipulacji HTML i przyspiesz swoje projekty rozwoju sieci! ### [Renderowanie wielu dokumentów w .NET za pomocą Aspose.HTML](./render-multiple-documents/) @@ -69,6 +70,9 @@ Odblokuj moc Aspose.HTML dla .NET! Dowiedz się, jak bez wysiłku renderować SV ### [Utwórz PNG z HTML – Pełny przewodnik renderowania w C#](./create-png-from-html-full-c-rendering-guide/) Naucz się, jak przy pomocy Aspose.HTML w C# konwertować HTML do plików PNG w pełnym, krok po kroku przewodniku. +### [Renderuj HTML do PNG w C# – Kompletny przewodnik krok po kroku](./render-html-to-png-in-c-complete-step-by-step-guide/) +Kompletny przewodnik w C# wyjaśniający, jak przy pomocy Aspose.HTML przekształcić HTML w plik PNG, krok po kroku. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/polish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/polish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..7e865f94d --- /dev/null +++ b/html/polish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-02-21 +description: Szybko renderuj HTML do PNG za pomocą Aspose.HTML. Dowiedz się, jak konwertować + HTML na obraz, ustawiać szerokość i wysokość obrazu oraz zapisywać HTML jako PNG + w kilku linijkach C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: pl +og_description: Render HTML do PNG przy użyciu Aspose.HTML. Ten samouczek pokazuje, + jak przekonwertować HTML na obraz, ustawić szerokość i wysokość obrazu oraz zapisać + HTML jako PNG w C#. +og_title: Renderowanie HTML do PNG w C# – Kompletny przewodnik +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Renderowanie HTML do PNG w C# – Kompletny przewodnik krok po kroku +url: /pl/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Renderowanie HTML do PNG – Kompletny przewodnik krok po kroku + +Czy kiedykolwiek potrzebowałeś **renderować HTML do PNG**, ale nie byłeś pewien, którą bibliotekę wybrać lub jak skonfigurować wyjście? Nie jesteś sam. Wielu programistów napotyka ten sam problem, gdy próbują *konwertować HTML na obraz* dla miniatur e‑maili, zrzutów raportów lub automatycznych testów UI. + +W tym samouczku przeprowadzimy Cię przez praktyczny, gotowy do uruchomienia przykład, który pokaże, jak **zapisać HTML jako PNG**, kontrolować wymiary obrazu i dostosować jakość renderowania — wszystko przy użyciu kilku linii kodu Aspose.HTML dla .NET. Po zakończeniu będziesz mieć wielokrotnego użytku fragment, który możesz wstawić do dowolnego projektu C#. + +## Czego będziesz potrzebować + +Zanim zanurkujemy, upewnij się, że masz: + +- **.NET 6.0 lub nowszy** (API działa z .NET Framework, .NET Core i .NET 5+) +- Pakiet NuGet **Aspose.HTML for .NET** (`Aspose.Html`) zainstalowany w projekcie. +- Podstawową znajomość składni C# — nic skomplikowanego nie jest potrzebne. +- Folder wyjściowy, w którym zostanie zapisany wygenerowany PNG. + +To wszystko. Brak dodatkowych SDK, brak zewnętrznych binarek, tylko pojedyncze odniesienie NuGet. + +## Renderowanie HTML do PNG – Przygotowanie dokumentu + +Pierwszą rzeczą, którą robimy, jest stworzenie obiektu `HTMLDocument`, który przechowuje znacznik, który chcemy rasteryzować. HTML można załadować ze stringa, pliku lub nawet z URL. Dla przejrzystości zaczniemy od prostego łańcucha inline. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![przykład wyjścia render html do png](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Por que isso importa:** Ao manter o documento em memória evitamos a latência de disco e tornamos toda a operação adequada para funções em nuvem ou microsserviços. + +## Etapa 2 – Construir um Manipulador de Recursos Personalizado (Custom Resource Handler) + +O Aspose.HTML chama `ResourceHandler.HandleResource` para cada recurso externo que ele descobre (imagens, CSS, fontes). Ao retornar o mesmo `MemoryStream` a cada chamada, podemos canalizar todos esses recursos em um único pacote ZIP. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Dica profissional:** Se precisar limitar o tamanho do ZIP resultante, você pode envolver `zipStream` em um `LimitedStream` e lançar uma exceção quando o limite for excedido. + +## Etapa 3 – Salvar o Documento como um Pacote ZIP (Salvar HTML como ZIP) + +Agora juntamos tudo. Instanciamos nosso manipulador, pedimos ao Aspose.HTML para salvar o documento em `SaveFormat.Zip` e, finalmente, extraímos os bytes brutos. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +Neste ponto, `zipBytes` contém um arquivo ZIP perfeitamente válido que você pode: + +* Retornar de uma Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Fazer upload para o Azure Blob Storage; +* Enviar por um socket para outro serviço. + +## Etapa 4 – Verificar a Saída (Converter HTML para ZIP – Teste Rápido) + +Uma verificação rápida de sanidade é gravar os bytes no disco (apenas para depuração) e abrir o arquivo com qualquer visualizador de ZIP. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +Ao abrir `debug_output.zip` você deverá ver: + +* `index.html` (o markup original) +* Qualquer imagem, arquivo CSS ou fonte referenciado incorporado ao lado dele. + +> **Por que isso funciona:** O Aspose.HTML trata o arquivo HTML principal como o primeiro recurso, depois transmite cada recurso vinculado na ordem em que os encontra. Nosso manipulador agrega todos eles no mesmo `MemoryStream`, que a biblioteca então finaliza como um arquivo ZIP. + +## Etapa 5 – Lidando com Casos Extremes Comuns (Melhores Práticas para Salvar HTML em ZIP) + +### Múltiplos Arquivos CSS + +Se sua página vincular a várias folhas de estilo, cada uma será adicionada como uma entrada separada. Nenhum código extra é necessário, mas você pode querer impor uma convenção de nomes (por exemplo, `styles/style1.css`) para evitar conflitos. + +### Recursos Binários Grandes + +Para imagens muito grandes (>10 MB) considere transmiti‑las diretamente para um stream baseado em arquivo em vez de um puro `MemoryStream`. Substitua `MemoryStream` por um `FileStream` em `MemoryZipHandler` e ajuste `GetResult` adequadamente. + +### Problemas de Codificação + +O Aspose.HTML respeita o charset declarado no cabeçalho HTML. Se precisar de saída UTF‑8, certifique‑se de que a tag `` esteja presente antes de criar o `HTMLDocument`. + +## Exemplo Completo Funcionando (Salvar HTML em ZIP) + +Abaixo está o programa completo que você pode colar em um aplicativo console e executar como está. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Saída esperada:** +``` +ZIP created – 1234 bytes +``` + +Abrindo `output.zip` mostra `index.html` contendo o markup `

Hello World

`. Nenhum arquivo extra foi necessário. + +--- + +## Perguntas Frequentes (FAQs) + +**Q: Isso funciona com URLs externas (por exemplo, imagens hospedadas em um CDN)?** +A: Sim. O Aspose.HTML baixará o recurso remoto e, em seguida, o passará para `HandleResource`. Apenas esteja ciente da latência de rede e de possíveis requisitos de autenticação. + +**Q: Posso definir um nome personalizado para o arquivo HTML principal dentro do ZIP?** +A: Por padrão é `index.html`. Para renomeá‑lo, você precisará pós‑processar o ZIP (por exemplo, usando `System.IO.Compression.ZipArchive`) após a conclusão do `Save`. + +**Q: E se eu precisar compactar vários documentos HTML juntos?** +A: Crie um `HTMLDocument` separado para cada página e chame `Save` no mesmo `MemoryZipHandler`. O manipulador continuará adicionando recursos, resultando em um ZIP multipágina. + +## Conclusão + +Agora você tem uma receita sólida de **como compactar HTML** que utiliza um **manipulador de recursos personalizado** para **salvar HTML como zip**, **converter HTML para zip** e **salvar HTML em zip** — tudo sem tocar no sistema de arquivos. A abordagem é leve, totalmente em memória, e se encaixa perfeitamente em APIs web, jobs em background ou qualquer serviço .NET que precise enviar pacotes HTML em tempo real. + +Pronto para o próximo passo? Tente estender o manipulador para comprimir ainda mais a saída com `System.IO.Compression.GZipStream`, ou integrá‑lo a um controlador ASP.NET Core que retorne o ZIP diretamente ao navegador. O céu é o limite, e agora você tem a base para construir. + +Feliz codificação! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/portuguese/net/rendering-html-documents/_index.md b/html/portuguese/net/rendering-html-documents/_index.md index 3646fe093..5fa256fff 100644 --- a/html/portuguese/net/rendering-html-documents/_index.md +++ b/html/portuguese/net/rendering-html-documents/_index.md @@ -50,6 +50,10 @@ Aprenda passo a passo a converter HTML em PNG usando Aspose.HTML, cobrindo todas ### [Como usar Aspose para renderizar HTML em PNG – Guia passo a passo](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) Aprenda a usar Aspose para converter HTML em PNG com um guia passo a passo detalhado. + +### [Renderizar HTML para PNG em C# – Guia Completo Passo a Passo](./render-html-to-png-in-c-complete-step-by-step-guide/) +Aprenda a converter HTML em PNG usando Aspose.HTML para .NET com um guia completo passo a passo em C#. + ### [Renderizar EPUB como XPS em .NET com Aspose.HTML](./render-epub-as-xps/) Aprenda como criar e renderizar documentos HTML com Aspose.HTML para .NET neste tutorial abrangente. Mergulhe no mundo da manipulação de HTML, web scraping e muito mais. ### [Tempo limite de renderização em .NET com Aspose.HTML](./rendering-timeout/) diff --git a/html/portuguese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/portuguese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..e2c781b79 --- /dev/null +++ b/html/portuguese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-02-21 +description: Renderize HTML para PNG rapidamente com Aspose.HTML. Aprenda como converter + HTML em imagem, definir a largura e a altura da imagem e salvar HTML como PNG em + poucas linhas de C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: pt +og_description: Renderizar HTML para PNG com Aspose.HTML. Este tutorial mostra como + converter HTML em imagem, definir a largura e a altura da imagem e salvar HTML como + PNG em C#. +og_title: Renderizar HTML para PNG em C# – Guia Completo +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Renderizar HTML para PNG em C# – Guia Completo Passo a Passo +url: /pt/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Renderizar HTML para PNG – Guia Completo Passo a Passo + +Já precisou **renderizar HTML para PNG** mas não tinha certeza de qual biblioteca escolher ou como configurar a saída? Você não está sozinho. Muitos desenvolvedores encontram o mesmo obstáculo ao tentar *converter HTML em imagem* para miniaturas de e‑mail, capturas de relatórios ou testes automatizados de UI. + +Neste tutorial vamos percorrer um exemplo prático e pronto‑para‑executar que mostra como **salvar HTML como PNG**, controlar as dimensões da imagem e ajustar a qualidade da renderização — tudo com poucas linhas usando Aspose.HTML for .NET. Ao final, você terá um trecho reutilizável que pode ser inserido em qualquer projeto C#. + +## O que você precisará + +Antes de mergulharmos, certifique‑se de que você tem: + +- **.NET 6.0 ou posterior** (a API funciona com .NET Framework, .NET Core e .NET 5+) +- **Aspose.HTML for .NET** pacote NuGet (`Aspose.Html`) instalado no seu projeto. +- Um entendimento básico da sintaxe C# — nada sofisticado é necessário. +- Uma pasta de saída onde o PNG gerado será gravado. + +É isso. Sem SDKs extras, sem binários externos, apenas uma única referência NuGet. + +## Renderizar HTML para PNG – Configurar o Documento + +A primeira coisa que fazemos é criar um objeto `HTMLDocument` que contém o markup que queremos rasterizar. Você pode carregar HTML a partir de uma string, de um arquivo ou até mesmo de uma URL. Para clareza, começaremos com uma string inline simples. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![render html to png output example](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Почему это важно:** Храня документ в памяти, мы избегаем задержек диска и делаем всю операцию пригодной для облачных функций или микросервисов. + +## Шаг 2 – Создание пользовательского обработчика ресурсов (Custom Resource Handler) + +Aspose.HTML вызывает `ResourceHandler.HandleResource` для каждого внешнего ресурса, который он обнаруживает (изображения, CSS, шрифты). Возвращая один и тот же `MemoryStream` каждый раз, мы можем собрать все эти ресурсы в один ZIP‑пакет. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro tip:** Если нужно ограничить размер получаемого ZIP, оберните `zipStream` в `LimitedStream` и бросайте исключение при превышении лимита. + +## Шаг 3 – Сохранение документа как ZIP‑пакет (Save HTML as ZIP) + +Теперь соединяем всё вместе. Мы создаём наш обработчик, просим Aspose.HTML сохранить документ в `SaveFormat.Zip` и, наконец, получаем необработанные байты. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +На этом этапе `zipBytes` содержит полностью корректный ZIP‑файл, который вы можете: + +* Вернуть из Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Загрузить в Azure Blob Storage; +* Отправить по сокету в другой сервис. + +## Шаг 4 – Проверка результата (Convert HTML to ZIP – Quick Test) + +Быстрая проверка — записать байты на диск (только для отладки) и открыть архив любым ZIP‑просмотрщиком. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +При открытии `debug_output.zip` вы должны увидеть: + +* `index.html` (исходная разметка) +* Все подключённые изображения, CSS‑файлы или шрифты, встроенные рядом с ним. + +> **Почему это работает:** Aspose.HTML рассматривает основной HTML‑файл как первый ресурс, затем последовательно стримит каждый связанный актив в порядке обнаружения. Наш обработчик собирает их все в один `MemoryStream`, который библиотека затем завершает как ZIP‑архив. + +## Шаг 5 – Обработка распространённых граничных случаев (Save HTML to ZIP Best Practices) + +### Несколько CSS‑файлов + +Если ваша страница ссылается на несколько таблиц стилей, каждая будет добавлена как отдельный элемент. Дополнительный код не требуется, но может быть полезно задать соглашение об именовании (например, `styles/style1.css`), чтобы избежать конфликтов. + +### Большие бинарные ресурсы + +Для огромных изображений (>10 МБ) рассмотрите возможность стримить их напрямую в поток, основанный на файле, вместо чистого `MemoryStream`. Замените `MemoryStream` на `FileStream` в `MemoryZipHandler` и скорректируйте `GetResult` соответственно. + +### Проблемы с кодировкой + +Aspose.HTML учитывает charset, объявленный в заголовке HTML. Если нужен вывод в UTF‑8, убедитесь, что тег `` присутствует до создания `HTMLDocument`. + +## Полный рабочий пример (Save HTML to ZIP) + +Ниже полностью готовая программа, которую можно вставить в консольное приложение и запустить без изменений. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Ожидаемый вывод:** +``` +ZIP created – 1234 bytes +``` + +Открытие `output.zip` показывает `index.html` с разметкой `

Hello World

`. Дополнительные файлы не требовались. + +--- + +## Часто задаваемые вопросы (FAQs) + +**Q: Работает ли это с внешними URL (например, изображения на CDN)?** +A: Да. Aspose.HTML скачает удалённый ресурс, затем передаст его в `HandleResource`. Учтите задержки сети и возможные требования аутентификации. + +**Q: Можно ли задать собственное имя главного HTML‑файла внутри ZIP?** +A: По умолчанию это `index.html`. Чтобы переименовать его, потребуется пост‑обработка ZIP (например, с помощью `System.IO.Compression.ZipArchive`) после завершения `Save`. + +**Q: Что делать, если нужно упаковать несколько HTML‑документов в один ZIP?** +A: Создайте отдельный `HTMLDocument` для каждой страницы и вызывайте `Save` на том же `MemoryZipHandler`. Обработчик будет добавлять ресурсы, в результате получится многостраничный ZIP. + +--- + +## Заключение + +Теперь у вас есть надёжный рецепт **how to zip HTML**, использующий **пользовательский обработчик ресурсов** для **save HTML as zip**, **convert HTML to zip** и **save HTML to zip** — всё без обращения к файловой системе. Подход лёгкий, полностью работает в памяти и отлично вписывается в веб‑API, фоновые задачи или любой .NET‑сервис, которому нужно динамически отправлять HTML‑пакеты. + +Готовы к следующему шагу? Попробуйте расширить обработчик, добавив дополнительное сжатие с помощью `System.IO.Compression.GZipStream`, или интегрировать его в контроллер ASP.NET Core, который будет возвращать ZIP напрямую браузеру. Возможности безграничны, а у вас теперь есть фундамент для дальнейшего развития. + +Счастливого кодинга! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/russian/net/rendering-html-documents/_index.md b/html/russian/net/rendering-html-documents/_index.md index 80263a376..dd203dc0f 100644 --- a/html/russian/net/rendering-html-documents/_index.md +++ b/html/russian/net/rendering-html-documents/_index.md @@ -43,6 +43,9 @@ Aspose.HTML для .NET выделяется как лучший выбор дл ### [Рендеринг HTML как PNG в .NET с помощью Aspose.HTML](./render-html-as-png/) Научитесь работать с Aspose.HTML для .NET: манипулируйте HTML, конвертируйте в различные форматы и многое другое. Погрузитесь в этот всеобъемлющий учебник! +### [Рендеринг HTML в PNG на C# – Полное пошаговое руководство](./render-html-to-png-in-c-complete-step-by-step-guide/) +Подробный пошаговый учебник по рендерингу HTML в PNG с использованием Aspose.HTML в C#. + ### [Как отрендерить HTML в PNG – Полное руководство C#](./how-to-render-html-as-png-complete-c-guide/) Полное руководство по рендерингу HTML в PNG с использованием Aspose.HTML и C#. ### [Создание PNG из HTML – Полное руководство по рендерингу на C#](./create-png-from-html-full-c-rendering-guide/) diff --git a/html/russian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/russian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3c411dc22 --- /dev/null +++ b/html/russian/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-02-21 +description: Быстро преобразуйте HTML в PNG с помощью Aspose.HTML. Узнайте, как конвертировать + HTML в изображение, задать ширину и высоту изображения и сохранить HTML как PNG + в несколько строк кода C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: ru +og_description: Отображайте HTML в PNG с помощью Aspose.HTML. Этот учебник показывает, + как преобразовать HTML в изображение, установить ширину и высоту изображения и сохранить + HTML как PNG в C#. +og_title: Рендеринг HTML в PNG на C# – Полное руководство +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Преобразование HTML в PNG в C# – Полное пошаговое руководство +url: /ru/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +output. + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Преобразование HTML в PNG – Полное пошаговое руководство + +Когда‑нибудь вам нужно было **преобразовать HTML в PNG**, но вы не знали, какую библиотеку выбрать или как настроить вывод? Вы не одиноки. Многие разработчики сталкиваются с тем же, когда пытаются *преобразовать HTML в изображение* для миниатюр писем, снимков отчётов или автоматизированного UI‑тестирования. + +В этом руководстве мы пройдём практический, готовый к запуску пример, который покажет, как **сохранить HTML как PNG**, управлять размерами изображения и настраивать качество рендеринга — все это с помощью нескольких строк кода Aspose.HTML для .NET. К концу вы получите переиспользуемый фрагмент, который можно вставить в любой проект на C#. + +## Что вам понадобится + +Прежде чем начать, убедитесь, что у вас есть: + +- **.NET 6.0 или новее** (API работает с .NET Framework, .NET Core и .NET 5+) +- NuGet‑пакет **Aspose.HTML for .NET** (`Aspose.Html`) установлен в вашем проекте. +- Базовое понимание синтаксиса C# — ничего сложного не требуется. +- Папка вывода, куда будет записан сгенерированный PNG. + +И всё. Никаких дополнительных SDK, никаких внешних бинарных файлов, только одна ссылка на NuGet. + +## Преобразование HTML в PNG – Создание документа + +Первое, что мы делаем, — создаём объект `HTMLDocument`, содержащий разметку, которую хотим растеризовать. HTML можно загрузить из строки, файла или даже URL. Для ясности начнём с простой встроенной строки. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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 пикселей. + +![пример вывода render html to png](output.png) + +> **Ожидаемый результат:** 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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Por qué es importante:** Al mantener el documento en memoria evitamos la latencia del disco y hacemos que toda la operación sea adecuada para funciones en la nube o micro‑servicios. + +## Paso 2 – Construir un Custom Resource Handler (Custom Resource Handler) + +Aspose.HTML llama a `ResourceHandler.HandleResource` para cada recurso externo que descubre (imágenes, CSS, fuentes). Al devolver el mismo `MemoryStream` cada vez, podemos canalizar todos esos recursos en un único paquete ZIP. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Consejo profesional:** Si necesitas limitar el tamaño del ZIP resultante, puedes envolver `zipStream` en un `LimitedStream` y lanzar una excepción cuando se supere el límite. + +## Paso 3 – Guardar el documento como paquete ZIP (Guardar HTML como ZIP) + +Ahora unimos todo. Instanciamos nuestro controlador, pedimos a Aspose.HTML que guarde el documento en `SaveFormat.Zip`, y finalmente obtenemos los bytes crudos. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +En este punto `zipBytes` contiene un archivo ZIP perfectamente válido que puedes: + +* Devolverlo desde una Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Subirlo a Azure Blob Storage; +* Enviarlo a través de un socket a otro servicio. + +## Paso 4 – Verificar la salida (Convertir HTML a ZIP – Prueba rápida) + +Una rápida comprobación de consistencia es escribir los bytes en disco (solo para depuración) y abrir el archivo con cualquier visor de ZIP. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +Al abrir `debug_output.zip` deberías ver: + +* `index.html` (el marcado original) +* Cualquier imagen, archivo CSS o fuente referenciada incrustada junto a él. + +> **Por qué funciona:** Aspose.HTML trata el archivo HTML principal como el primer recurso, luego transmite cada activo enlazado en el orden en que los encuentra. Nuestro controlador los agrega todos al mismo `MemoryStream`, que la biblioteca finaliza como un archivo ZIP. + +## Paso 5 – Manejo de casos límite comunes (Mejores prácticas para Guardar HTML a ZIP) + +### Múltiples archivos CSS + +Si tu página enlaza a varias hojas de estilo, cada una se añadirá como una entrada separada. No se necesita código adicional, pero podrías querer imponer una convención de nombres (p.ej., `styles/style1.css`) para evitar colisiones. + +### Recursos binarios grandes + +Para imágenes masivas (>10 MB) considera transmitirlas directamente a un flujo respaldado por archivo en lugar de un puro `MemoryStream`. Reemplaza `MemoryStream` por un `FileStream` en `MemoryZipHandler` y ajusta `GetResult` en consecuencia. + +### Problemas de codificación + +Aspose.HTML respeta el charset declarado en el encabezado HTML. Si necesitas salida UTF‑8, asegúrate de que la etiqueta `` esté presente antes de crear el `HTMLDocument`. + +## Ejemplo completo y funcional (Guardar HTML a ZIP) + +A continuación se muestra el programa completo que puedes pegar en una aplicación de consola y ejecutar tal cual. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Salida esperada:** +``` +ZIP created – 1234 bytes +``` + +Al abrir `output.zip` se muestra `index.html` que contiene el marcado `

Hello World

`. No se requirieron archivos adicionales. + +--- + +## Preguntas frecuentes (FAQs) + +**Q: ¿Esto funciona con URLs externas (p. ej., imágenes alojadas en un CDN)?** +A: Sí. Aspose.HTML descargará el recurso remoto y luego lo pasará a `HandleResource`. Solo ten en cuenta la latencia de la red y posibles requisitos de autenticación. + +**Q: ¿Puedo establecer un nombre personalizado para el archivo HTML principal dentro del ZIP?** +A: Por defecto es `index.html`. Para renombrarlo, deberías post‑procesar el ZIP (p. ej., usando `System.IO.Compression.ZipArchive`) después de que `Save` finalice. + +**Q: ¿Qué pasa si necesito comprimir varios documentos HTML juntos?** +A: Crea un `HTMLDocument` separado para cada página y llama a `Save` en el mismo `MemoryZipHandler`. El controlador seguirá añadiendo recursos, resultando en un ZIP multipágina. + +## Conclusión + +Ahora tienes una receta sólida, **cómo comprimir HTML**, que aprovecha un **custom resource handler** para **guardar HTML como zip**, **convertir HTML a zip** y **guardar HTML a zip**, todo sin tocar el sistema de archivos. El enfoque es liviano, completamente en memoria, y encaja perfectamente en APIs web, trabajos en segundo plano o cualquier servicio .NET que necesite enviar paquetes HTML al instante. + +¿Listo para el siguiente paso? Intenta extender el controlador para comprimir aún más la salida con `System.IO.Compression.GZipStream`, o intégralo en un controlador ASP.NET Core que devuelva el ZIP directamente al navegador. El cielo es el límite, y ahora tienes la base para construir. + +¡Feliz codificación! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/spanish/net/rendering-html-documents/_index.md b/html/spanish/net/rendering-html-documents/_index.md index aa3ec875b..c7f77a24c 100644 --- a/html/spanish/net/rendering-html-documents/_index.md +++ b/html/spanish/net/rendering-html-documents/_index.md @@ -60,6 +60,8 @@ Aprenda a representar múltiples documentos HTML con Aspose.HTML para .NET. Aume Aprenda paso a paso a convertir HTML a PNG usando C# y Aspose.HTML. Guía completa con ejemplos claros. ### [Cómo renderizar HTML a PNG con Aspose – Guía completa](./how-to-render-html-to-png-with-aspose-complete-guide/) Aprenda a convertir HTML a PNG usando Aspose.HTML para .NET con esta guía completa paso a paso. +### [Renderizar HTML a PNG en C# – Guía completa paso a paso](./render-html-to-png-in-c-complete-step-by-step-guide/) +Aprenda paso a paso a convertir HTML a PNG usando C# y Aspose.HTML. Guía completa con ejemplos claros. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/spanish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/spanish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..a685daef0 --- /dev/null +++ b/html/spanish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-02-21 +description: Renderiza HTML a PNG rápidamente con Aspose.HTML. Aprende cómo convertir + HTML a imagen, establecer el ancho y la altura de la imagen, y guardar HTML como + PNG en unas pocas líneas de C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: es +og_description: Renderiza HTML a PNG con Aspose.HTML. Este tutorial muestra cómo convertir + HTML a imagen, establecer el ancho y la altura de la imagen, y guardar HTML como + PNG en C#. +og_title: Renderizar HTML a PNG en C# – Guía completa +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Renderizar HTML a PNG en C# – Guía completa paso a paso +url: /es/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +instruction says preserve all images, but doesn't forbid translating alt text. However alt text is part of content. Safer to keep as is? It says preserve exactly all images, but not that alt text must stay unchanged. However to avoid risk, keep alt text unchanged. We'll leave as is. + +Now produce final content.{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG – Guía completa paso a paso + +¿Alguna vez necesitaste **render HTML to PNG** pero no estabas seguro de qué biblioteca elegir o cómo configurar la salida? No estás solo. Muchos desarrolladores se topan con el mismo obstáculo cuando intentan *convert HTML to image* para miniaturas de correos electrónicos, instantáneas de informes o pruebas automatizadas de UI. + +En este tutorial recorreremos un ejemplo práctico y listo‑para‑ejecutar que te muestra cómo **save HTML as PNG**, controlar las dimensiones de la imagen y ajustar la calidad de renderizado — todo con unas pocas líneas usando Aspose.HTML for .NET. Al final tendrás un fragmento reutilizable que puedes insertar en cualquier proyecto C#. + +## Lo que necesitarás + +- **.NET 6.0 o posterior** (la API funciona con .NET Framework, .NET Core y .NET 5+) +- **Aspose.HTML for .NET** paquete NuGet (`Aspose.Html`) instalado en tu proyecto. +- Un conocimiento básico de la sintaxis de C# — no se requiere nada sofisticado. +- Una carpeta de salida donde se escribirá el PNG generado. + +Eso es todo. Sin SDKs adicionales, sin binarios externos, solo una única referencia NuGet. + +## Render HTML to PNG – Configurar el documento + +Lo primero que hacemos es crear un objeto `HTMLDocument` que contiene el marcado que queremos rasterizar. Puedes cargar HTML desde una cadena, un archivo o incluso una URL. Para mayor claridad, comenzaremos con una simple cadena en línea. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![render html to png output example](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Varför detta är viktigt:** Genom att hålla dokumentet i minnet undviker vi disk‑latens och gör hela operationen lämplig för molnfunktioner eller mikrotjänster. + +## Steg 2 – Bygg en anpassad resurs‑hanterare (Custom Resource Handler) + +Aspose.HTML anropar `ResourceHandler.HandleResource` för varje extern tillgång den upptäcker (bilder, CSS, fonter). Genom att returnera samma `MemoryStream` varje gång kan vi leda alla dessa resurser in i ett enda ZIP‑paket. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro‑tips:** Om du behöver begränsa storleken på den resulterande ZIP‑filen kan du wrappa `zipStream` i en `LimitedStream` och kasta ett undantag när gränsen överskrids. + +## Steg 3 – Spara dokumentet som ett ZIP‑paket (Save HTML as ZIP) + +Nu knyter vi ihop allt. Vi instansierar vår hanterare, ber Aspose.HTML att spara dokumentet i `SaveFormat.Zip`, och drar sedan ut de råa bytena. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +På den här punkten innehåller `zipBytes` en helt giltig ZIP‑fil som du kan: + +* Returnera från ett Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Ladda upp till Azure Blob Storage; +* Skicka över en socket till en annan tjänst. + +## Steg 4 – Verifiera resultatet (Convert HTML to ZIP – Quick Test) + +En snabb kontroll är att skriva bytena till disk (endast för felsökning) och öppna arkivet med någon ZIP‑visare. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +När du öppnar `debug_output.zip` bör du se: + +* `index.html` (den ursprungliga markupen) +* Alla refererade bilder, CSS‑filer eller fonter som är inbäddade bredvid den. + +> **Varför detta fungerar:** Aspose.HTML behandlar huvud‑HTML‑filen som den första resursen, och strömmar sedan varje länkad tillgång i den ordning den möter dem. Vår hanterare samlar dem alla i samma `MemoryStream`, som biblioteket sedan finaliserar som ett ZIP‑arkiv. + +## Steg 5 – Hantera vanliga kantfall (Save HTML to ZIP Best Practices) + +### Flera CSS‑filer + +Om din sida länkar till flera stilark kommer varje att läggas till som en separat post. Ingen extra kod behövs, men du kanske vill införa ett namngivningskonvention (t.ex. `styles/style1.css`) för att undvika krockar. + +### Stora binära resurser + +För massiva bilder (>10 MB) överväg att strömma dem direkt till ett fil‑backat flöde istället för ett rent `MemoryStream`. Byt ut `MemoryStream` mot en `FileStream` i `MemoryZipHandler` och justera `GetResult` därefter. + +### Kodningsproblem + +Aspose.HTML respekterar den charset som deklareras i HTML‑huvudet. Om du behöver UTF‑8‑utdata, se till att ``‑taggen finns innan du skapar `HTMLDocument`. + +## Fullt fungerande exempel (Save HTML to ZIP) + +Nedan är hela programmet som du kan klistra in i en konsolapp och köra som det är. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Förväntad output:** +``` +ZIP created – 1234 bytes +``` + +Att öppna `output.zip` visar `index.html` som innehåller markupen `

Hello World

`. Inga extra filer krävdes. + +--- + +## Vanliga frågor (FAQs) + +**Q: Fungerar detta med externa URL:er (t.ex. bilder som hostas på ett CDN)?** +A: Ja. Aspose.HTML laddar ner den fjärrstyrda resursen och skickar den sedan till `HandleResource`. Tänk bara på nätverkslatens och eventuella autentiseringskrav. + +**Q: Kan jag sätta ett eget namn på huvud‑HTML‑filen i ZIP‑filen?** +A: Som standard är den `index.html`. För att byta namn måste du efterbehandla ZIP‑filen (t.ex. med `System.IO.Compression.ZipArchive`) efter att `Save` är klar. + +**Q: Vad händer om jag behöver zipa flera HTML‑dokument tillsammans?** +A: Skapa ett separat `HTMLDocument` för varje sida och anropa `Save` på samma `MemoryZipHandler`. Hanteraren kommer att fortsätta lägga till resurser, vilket resulterar i ett flersidigt ZIP‑paket. + +--- + +## Slutsats + +Du har nu ett gediget **how to zip HTML**‑recept som utnyttjar en **custom resource handler** för att **save HTML as zip**, **convert HTML to zip** och **save HTML to zip**—allt utan att röra filsystemet. Metoden är lättviktig, helt i minnet, och passar utmärkt i webb‑API:er, bakgrundsjobb eller någon .NET‑tjänst som behöver skicka HTML‑paket i farten. + +Redo för nästa steg? Prova att utöka hanteraren för att komprimera utdata ytterligare med `System.IO.Compression.GZipStream`, eller integrera den i en ASP.NET Core‑controller som returnerar ZIP‑filen direkt till webbläsaren. Himlen är gränsen, och nu har du grunden att bygga vidare på. + +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/swedish/net/rendering-html-documents/_index.md b/html/swedish/net/rendering-html-documents/_index.md index 72cae28c3..13e2c564c 100644 --- a/html/swedish/net/rendering-html-documents/_index.md +++ b/html/swedish/net/rendering-html-documents/_index.md @@ -58,6 +58,8 @@ Lär dig att rendera flera HTML-dokument med Aspose.HTML för .NET. Förbättra Lås upp kraften i Aspose.HTML för .NET! Lär dig hur du renderar SVG-dokument som PNG utan ansträngning. Dyk ner i steg-för-steg-exempel och vanliga frågor. Kom igång nu! ### [Hur man använder Aspose för att rendera HTML till PNG – Steg‑för‑steg‑guide](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) Lär dig hur du med Aspose.HTML för .NET konverterar HTML till PNG i en detaljerad steg‑för‑steg‑handledning. +### [Rendera HTML till PNG i C# – Komplett steg‑för‑steg‑guide](./render-html-to-png-in-c-complete-step-by-step-guide/) +Lär dig steg för steg hur du renderar HTML till PNG i C# med Aspose.HTML i en komplett guide. ### [Hur man renderar HTML till PNG med Aspose – Komplett guide](./how-to-render-html-to-png-with-aspose-complete-guide/) Lär dig hur du med Aspose.HTML för .NET konverterar HTML till PNG i en komplett guide. diff --git a/html/swedish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/swedish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..0bcc9c706 --- /dev/null +++ b/html/swedish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-02-21 +description: Rendera HTML till PNG snabbt med Aspose.HTML. Lär dig hur du konverterar + HTML till bild, anger bildens bredd och höjd och sparar HTML som PNG i några få + rader C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: sv +og_description: Rendera HTML till PNG med Aspose.HTML. Denna handledning visar hur + du konverterar HTML till bild, ställer in bildens bredd och höjd samt sparar HTML + som PNG i C#. +og_title: Rendera HTML till PNG i C# – Komplett guide +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Rendera HTML till PNG i C# – Komplett steg‑för‑steg‑guide +url: /sv/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG – Komplett steg‑för‑steg‑guide + +Har du någonsin behövt **rendera HTML till PNG** men varit osäker på vilket bibliotek du ska välja eller hur du konfigurerar utskriften? Du är inte ensam. Många utvecklare stöter på samma problem när de försöker *konvertera HTML till bild* för e‑post‑miniaturer, rapport‑snapshots eller automatiserad UI‑testning. + +I den här handledningen går vi igenom ett praktiskt, färdigt exempel som visar hur du **sparar HTML som PNG**, styr bildens dimensioner och finjusterar renderingskvaliteten – allt med några få rader kod med Aspose.HTML för .NET. När du är klar har du ett återanvändbart kodsnutt som du kan klistra in i vilket C#‑projekt som helst. + +## Vad du behöver + +Innan vi dyker ner, se till att du har: + +- **.NET 6.0 eller senare** (API:et fungerar med .NET Framework, .NET Core och .NET 5+) +- **Aspose.HTML för .NET** NuGet‑paket (`Aspose.Html`) installerat i ditt projekt. +- Grundläggande kunskap om C#‑syntax – inget avancerat krävs. +- En utdatamapp där den genererade PNG‑filen ska skrivas. + +Det är allt. Inga extra SDK:er, inga externa binärer, bara en enda NuGet‑referens. + +## Rendera HTML till PNG – Skapa dokumentet + +Det första vi gör är att skapa ett `HTMLDocument`‑objekt som innehåller den markup vi vill rasterisera. Du kan läsa in HTML från en sträng, en fil eller till och med en URL. För tydlighetens skull börjar vi med en enkel inline‑sträng. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![exempel på render html till png‑utdata](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Why this matters:** การเก็บเอกสารในหน่วยความจำช่วยหลีกเลี่ยงความล่าช้าจากดิสก์และทำให้การดำเนินการทั้งหมดเหมาะกับฟังก์ชันคลาวด์หรือไมโคร‑เซอร์วิส + +## Step 2 – Build a Custom Resource Handler (Custom Resource Handler) + +Aspose.HTML จะเรียก `ResourceHandler.HandleResource` สำหรับทุกแอสเซ็ตภายนอกที่มันค้นพบ (รูปภาพ, CSS, ฟอนต์) โดยการคืนค่า `MemoryStream` เดียวกันทุกครั้ง เราสามารถรวบรวมทรัพยากรทั้งหมดเหล่านั้นเข้าไปในแพคเกจ ZIP เดียวได้ + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro tip:** หากคุณต้องการจำกัดขนาดของ ZIP ที่สร้างขึ้น คุณสามารถห่อ `zipStream` ด้วย `LimitedStream` และทำการ throw เมื่อเกินขีดจำกัด + +## Step 3 – Save the Document as a ZIP Package (Save HTML as ZIP) + +ตอนนี้เรามาเชื่อมต่อทุกอย่างเข้าด้วยกัน เราจะสร้างอินสแตนซ์ของ handler, ให้ Aspose.HTML บันทึกเอกสารใน `SaveFormat.Zip` และสุดท้ายดึงไบต์ดิบออกมา + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +ในขั้นตอนนี้ `zipBytes` จะเป็นไฟล์ ZIP ที่สมบูรณ์ซึ่งคุณสามารถ: + +* ส่งกลับจาก Web API (`File(zipBytes, "application/zip", "page.zip")`); +* อัปโหลดไปยัง Azure Blob Storage; +* ส่งผ่านซ็อกเก็ตไปยังบริการอื่น + +## Step 4 – Verify the Output (Convert HTML to ZIP – Quick Test) + +การตรวจสอบอย่างรวดเร็วคือการเขียนไบต์ลงดิสก์ (เพื่อดีบักเท่านั้น) แล้วเปิดไฟล์ ZIP ด้วยโปรแกรมดู ZIP ใดก็ได้ + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +เมื่อคุณเปิด `debug_output.zip` คุณควรเห็น: + +* `index.html` (markup ดั้งเดิม) +* รูปภาพ, ไฟล์ CSS หรือฟอนต์ที่อ้างอิงทั้งหมดที่ฝังอยู่ข้างเคียง + +> **Why this works:** Aspose.HTML ถือไฟล์ HTML หลักเป็นทรัพยากรแรก แล้วสตรีมแต่ละแอสเซ็ตที่เชื่อมโยงตามลำดับที่พบ ตัวจัดการของเราจะรวบรวมทั้งหมดเข้าไปใน `MemoryStream` เดียว ซึ่งไลบรารีจะสรุปเป็นไฟล์ ZIP + +## Step 5 – Handling Common Edge Cases (Save HTML to ZIP Best Practices) + +### Multiple CSS Files + +หากหน้าเว็บของคุณลิงก์ไปหลายสไตล์ชีต แต่ละไฟล์จะถูกเพิ่มเป็น entry แยกกัน ไม่ต้องเขียนโค้ดเพิ่ม แต่คุณอาจต้องกำหนดแนวทางการตั้งชื่อ (เช่น `styles/style1.css`) เพื่อหลีกเลี่ยงการชนกันของชื่อไฟล์ + +### Large Binary Resources + +สำหรับรูปภาพขนาดใหญ่ (>10 MB) ควรสตรีมโดยตรงไปยัง `FileStream` แทน `MemoryStream` เพื่อลดการใช้หน่วยความจำ เปลี่ยน `MemoryStream` เป็น `FileStream` ใน `MemoryZipHandler` แล้วปรับ `GetResult` ให้สอดคล้อง + +### Encoding Issues + +Aspose.HTML เคารพ charset ที่ระบุในส่วนหัวของ HTML หากคุณต้องการผลลัพธ์เป็น UTF‑8 ให้ตรวจสอบว่ามีแท็ก `` อยู่ก่อนที่คุณจะสร้าง `HTMLDocument` + +## Full Working Example (Save HTML to ZIP) + +ด้านล่างเป็นโปรแกรมเต็มที่คุณสามารถคัดลอกและวางลงในแอปคอนโซลแล้วรันได้เลย + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Expected output:** +``` +ZIP created – 1234 bytes +``` + +เมื่อเปิด `output.zip` จะเห็น `index.html` ที่มี markup `

Hello World

` ไม่มีไฟล์เพิ่มเติมใด ๆ ที่จำเป็น + +--- + +## Frequently Asked Questions (FAQs) + +**Q: Does this work with external URLs (e.g., images hosted on a CDN)?** +A: ใช่ Aspose.HTML จะดาวน์โหลดทรัพยากรจากระยะไกลแล้วส่งต่อให้ `HandleResource` เพียงต้องระวังความล่าช้าของเครือข่ายและข้อกำหนดการยืนยันตัวตนที่อาจมี + +**Q: Can I set a custom name for the main HTML file inside the ZIP?** +A: ค่าเริ่มต้นคือ `index.html` หากต้องการเปลี่ยนชื่อ คุณต้องทำ post‑process ZIP (เช่นใช้ `System.IO.Compression.ZipArchive`) หลังจาก `Save` เสร็จ + +**Q: What if I need to zip multiple HTML documents together?** +A: สร้าง `HTMLDocument` แยกสำหรับแต่ละหน้าและเรียก `Save` ด้วย `MemoryZipHandler` เดียวกัน ตัวจัดการจะต่อเนื่องเพิ่มทรัพยากร ทำให้ได้ ZIP ที่มีหลายหน้า + +--- + +## Conclusion + +คุณมีสูตร **how to zip HTML** ที่ใช้ **custom resource handler** เพื่อ **save HTML as zip**, **convert HTML to zip**, และ **save HTML to zip**—ทั้งหมดโดยไม่ต้องสัมผัสระบบไฟล์ วิธีนี้เบา, ทำงานในหน่วยความจำเต็มรูปแบบ, และเหมาะกับ Web API, งานเบื้องหลัง, หรือบริการ .NET ใด ๆ ที่ต้องส่ง HTML bundle แบบเรียลไทม์ + +พร้อมก้าวต่อไปหรือยัง? ลองขยาย handler ให้บีบอัดผลลัพธ์เพิ่มเติมด้วย `System.IO.Compression.GZipStream` หรือผสานเข้ากับคอนโทรลเลอร์ ASP.NET Core ที่ส่ง ZIP กลับไปยังเบราว์เซอร์โดยตรง ไม่จำกัดอะไรเลย และตอนนี้คุณมีพื้นฐานที่แข็งแรงสำหรับการต่อยอด + +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/thai/net/rendering-html-documents/_index.md b/html/thai/net/rendering-html-documents/_index.md index 9266aa954..a095b14c9 100644 --- a/html/thai/net/rendering-html-documents/_index.md +++ b/html/thai/net/rendering-html-documents/_index.md @@ -62,6 +62,8 @@ Aspose.HTML สำหรับ .NET ถือเป็นตัวเลือ เรียนรู้วิธีการเรนเดอร์ไฟล์ HTML เป็น PNG ด้วย Aspose.HTML สำหรับ .NET อย่างละเอียดในคู่มือขั้นตอนนี้! ### [วิธีเรนเดอร์ HTML เป็น PNG ด้วย Aspose – คู่มือฉบับสมบูรณ์](./how-to-render-html-to-png-with-aspose-complete-guide/) เรียนรู้วิธีการเรนเดอร์ไฟล์ HTML เป็น PNG อย่างละเอียดด้วย Aspose.HTML สำหรับ .NET ในคู่มือฉบับสมบูรณ์นี้! +### [เรนเดอร์ HTML เป็น PNG ใน C# – คู่มือขั้นตอนเต็มรูปแบบ](./render-html-to-png-in-c-complete-step-by-step-guide/) +เรียนรู้วิธีเรนเดอร์ไฟล์ HTML เป็น PNG ด้วย C# อย่างละเอียดในคู่มือขั้นตอนเต็มรูปแบบนี้! {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/thai/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/thai/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3d5c94e18 --- /dev/null +++ b/html/thai/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-02-21 +description: เรนเดอร์ HTML เป็น PNG อย่างรวดเร็วด้วย Aspose.HTML เรียนรู้วิธีแปลง + HTML เป็นภาพ ตั้งความกว้างและความสูงของภาพ และบันทึก HTML เป็น PNG เพียงไม่กี่บรรทัดของ + C# +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: th +og_description: เรนเดอร์ HTML เป็น PNG ด้วย Aspose.HTML บทเรียนนี้แสดงวิธีแปลง HTML + เป็นภาพ ตั้งค่าความกว้างและความสูงของภาพ และบันทึก HTML เป็น PNG ด้วย C# +og_title: เรนเดอร์ HTML เป็น PNG ใน C# – คู่มือฉบับสมบูรณ์ +tags: +- Aspose.HTML +- C# +- Image Rendering +title: แปลง HTML เป็น PNG ใน C# – คู่มือขั้นตอนเต็มแบบละเอียด +url: /th/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG – Complete Step‑by‑Step Guide + +เคยต้อง **render HTML to PNG** แต่ไม่แน่ใจว่าจะเลือกไลบรารีไหนหรือจะตั้งค่าผลลัพธ์อย่างไรหรือไม่? คุณไม่ได้อยู่คนเดียว นักพัฒนาหลายคนเจออุปสรรคเดียวกันเมื่อต้อง *convert HTML to image* สำหรับภาพย่ออีเมล, ภาพสแนปช็อตของรายงาน, หรือการทดสอบ UI แบบอัตโนมัติ + +ในบทเรียนนี้เราจะเดินผ่านตัวอย่างที่พร้อมรันได้จริง ซึ่งจะแสดงวิธี **save HTML as PNG**, ควบคุมขนาดภาพ, และปรับคุณภาพการเรนเดอร์—ทั้งหมดด้วยไม่กี่บรรทัดโดยใช้ Aspose.HTML for .NET. เมื่อจบคุณจะได้โค้ดสแนปช็อตที่นำไปใช้ซ้ำได้ในโปรเจกต์ C# ใดก็ได้ + +## What You’ll Need + +ก่อนที่เราจะลงมือทำ, ตรวจสอบให้แน่ใจว่าคุณมี: + +- **.NET 6.0 หรือใหม่กว่า** (API ทำงานกับ .NET Framework, .NET Core, และ .NET 5+) +- **Aspose.HTML for .NET** NuGet package (`Aspose.Html`) ที่ติดตั้งในโปรเจกต์ของคุณ +- ความเข้าใจพื้นฐานเกี่ยวกับไวยากรณ์ C#—ไม่ต้องการความรู้ขั้นสูง +- โฟลเดอร์ปลายทางที่ไฟล์ PNG ที่สร้างจะถูกเขียนลงไป + +เท่านี้แค่นั้น ไม่ต้อง SDK เพิ่มเติม ไม่ต้องไบนารีภายนอก เพียงอ้างอิง NuGet เพียงตัวเดียว + +## Render HTML to PNG – Set Up the Document + +สิ่งแรกที่เราทำคือสร้างอ็อบเจ็กต์ `HTMLDocument` ที่เก็บ markup ที่เราต้องการแปลงเป็นภาพ คุณสามารถโหลด HTML จากสตริง, ไฟล์, หรือแม้แต่ URL. เพื่อความชัดเจนเราจะเริ่มด้วยสตริงแบบอินไลน์ง่าย ๆ + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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 พิกเซล + +![render html to png output example](output.png) + +> **ผลลัพธ์ที่คาดหวัง:** ไฟล์ 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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Neden önemli:** Belgeyi bellek içinde tutarak disk gecikmesinden kaçınır ve tüm işlemi bulut fonksiyonları veya mikro‑servisler için uygun hâle getirir. + +## 2. Adım – Özel Kaynak İşleyicisi Oluşturma (Custom Resource Handler) + +Aspose.HTML, keşfettiği her dış varlık (görseller, CSS, fontlar) için `ResourceHandler.HandleResource` metodunu çağırır. Her seferinde aynı `MemoryStream`'i döndürerek tüm bu kaynakları tek bir ZIP paketine yönlendirebiliriz. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Pro ipucu:** Oluşan ZIP'in boyutunu sınırlamanız gerekiyorsa, `zipStream`'i bir `LimitedStream` ile sarabilir ve limit aşıldığında bir istisna fırlatabilirsiniz. + +## 3. Adım – Belgeyi ZIP Paketi Olarak Kaydetme (HTML'i ZIP Olarak Kaydet) + +Şimdi her şeyi birleştiriyoruz. İşleyicimizi örnekliyoruz, Aspose.HTML'den belgeyi `SaveFormat.Zip` formatında kaydetmesini istiyoruz ve sonunda ham baytları alıyoruz. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +Bu noktada `zipBytes` tamamen geçerli bir ZIP dosyası içerir; bunu şunlar için kullanabilirsiniz: + +* Bir Web API'den döndürmek (`File(zipBytes, "application/zip", "page.zip")`); +* Azure Blob Storage'a yüklemek; +* Başka bir servise soket üzerinden göndermek. + +## 4. Adım – Çıktıyı Doğrulama (HTML'i ZIP'e Dönüştür – Hızlı Test) + +Hızlı bir doğrulama, baytları diske (sadece hata ayıklama amacıyla) yazmak ve arşivi herhangi bir ZIP görüntüleyiciyle açmaktır. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +`debug_output.zip` dosyasını açtığınızda şunları görmelisiniz: + +* `index.html` (orijinal işaretleme) +* Referans verilen tüm görseller, CSS dosyaları veya fontlar yanına gömülmüş olarak. + +> **Neden bu şekilde çalışır:** Aspose.HTML, ana HTML dosyasını ilk kaynak olarak kabul eder, ardından bulduğu sırayla her bağlı varlığı akıtır. İşleyicimiz, hepsini aynı `MemoryStream` içinde toplar ve kütüphane bunu bir ZIP arşivi olarak sonlandırır. + +## 5. Adım – Yaygın Uç Durumları Ele Alma (HTML'i ZIP'e Kaydetme En İyi Uygulamaları) + +### Birden Çok CSS Dosyası + +Sayfanız birden fazla stil sayfasına bağlanıyorsa, her biri ayrı bir giriş olarak eklenir. Ek bir koda gerek yok, ancak çakışmaları önlemek için bir adlandırma kuralı (ör. `styles/style1.css`) uygulamak isteyebilirsiniz. + +### Büyük İkili Kaynaklar + +10 MB'den büyük büyük görseller için, saf bir `MemoryStream` yerine dosya tabanlı bir akıma doğrudan akıtmayı düşünün. `MemoryZipHandler` içinde `MemoryStream`'i `FileStream` ile değiştirin ve `GetResult` metodunu buna göre ayarlayın. + +### Kodlama Sorunları + +Aspose.HTML, HTML başlığında bildirilen karakter setine saygı gösterir. UTF‑8 çıktısına ihtiyacınız varsa, `HTMLDocument` oluşturulmadan önce `` etiketinin mevcut olduğundan emin olun. + +## Tam Çalışan Örnek (HTML'i ZIP'e Kaydetme) + +Aşağıda, bir konsol uygulamasına yapıştırıp olduğu gibi çalıştırabileceğiniz tam program yer almaktadır. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Beklenen çıktı:** +``` +ZIP created – 1234 bytes +``` + +`output.zip` dosyasını açtığınızda `

Hello World

` işaretlemesini içeren `index.html` dosyasını görürsünüz. Ek dosyalara gerek yok. + +--- + +## Sıkça Sorulan Sorular (SSS) + +**S:** Bu, harici URL'lerle (ör. bir CDN'de barındırılan görseller) çalışır mı? +**C:** Evet. Aspose.HTML uzaktaki kaynağı indirir ve ardından `HandleResource` metoduna geçirir. Sadece ağ gecikmesi ve olası kimlik doğrulama gereksinimlerine dikkat edin. + +**S:** ZIP içindeki ana HTML dosyasına özel bir ad verebilir miyim? +**C:** Varsayılan olarak `index.html` olur. Yeniden adlandırmak için `Save` tamamlandıktan sonra ZIP'i (ör. `System.IO.Compression.ZipArchive` kullanarak) sonradan işlemek gerekir. + +**S:** Birden fazla HTML belgesini birlikte ziplemem gerekirse? +**C:** Her sayfa için ayrı bir `HTMLDocument` oluşturup aynı `MemoryZipHandler` üzerinde `Save` çağırın. İşleyici kaynakları eklemeye devam eder ve çok sayfalı bir ZIP oluşturur. + +## Sonuç + +Artık **HTML'i zipleme** konusunda sağlam bir tarifiniz var; bu tarif **özel kaynak işleyicisi** kullanarak **HTML'i zip olarak kaydetme**, **HTML'i zip'e dönüştürme** ve **HTML'i zip'e kaydetme** işlemlerini dosya sistemine dokunmadan gerçekleştiriyor. Yaklaşım hafif, tamamen bellek içinde ve web API'leri, arka plan işleri veya anlık HTML paketleri göndermesi gereken herhangi bir .NET hizmetine güzelce uyuyor. + +Bir sonraki adıma hazır mısınız? İşleyiciyi `System.IO.Compression.GZipStream` ile çıktıyı daha da sıkıştıracak şekilde genişletmeyi deneyin ya da ZIP'i doğrudan tarayıcıya döndüren bir ASP.NET Core denetleyicisine entegre edin. Gökyüzü sınırdır ve artık üzerine inşa edebileceğiniz temele sahipsiniz. + +Kodlamaktan keyif alı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/turkish/net/rendering-html-documents/_index.md b/html/turkish/net/rendering-html-documents/_index.md index 6cce1b921..3e8cc9a44 100644 --- a/html/turkish/net/rendering-html-documents/_index.md +++ b/html/turkish/net/rendering-html-documents/_index.md @@ -60,6 +60,8 @@ Aspose.HTML for .NET ile HTML dosyalarını PNG formatına dönüştürmeyi adı Aspose.HTML for .NET kullanarak HTML dosyalarını PNG formatına dönüştürmenin tüm adımlarını öğrenin. ### [HTML'den PNG Oluşturma – Tam C# Render Rehberi](./create-png-from-html-full-c-rendering-guide/) HTML'den PNG oluşturmayı tam C# render rehberiyle adım adım öğrenin. +### [HTML'yi PNG Olarak İşleme – C# Tam Adım‑Adım Kılavuzu](./render-html-to-png-in-c-complete-step-by-step-guide/) +C# kullanarak HTML'yi PNG'ye dönüştürmeyi adım adım öğrenin. Bu kapsamlı kılavuzda örnek kodlar ve ipuçları bulacaksınız. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/turkish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/turkish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..f4ca917d8 --- /dev/null +++ b/html/turkish/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-02-21 +description: Aspose.HTML ile HTML'yi hızlıca PNG'ye dönüştürün. HTML'yi görüntüye + nasıl çevireceğinizi, görüntünün genişlik ve yüksekliğini nasıl ayarlayacağınızı + ve C#'ın birkaç satırıyla HTML'yi PNG olarak nasıl kaydedeceğinizi öğrenin. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: tr +og_description: Aspose.HTML ile HTML'yi PNG'ye dönüştürün. Bu öğreticide HTML'yi görüntüye + nasıl dönüştüreceğiniz, görüntünün genişlik ve yüksekliğini nasıl ayarlayacağınız + ve C#'ta HTML'yi PNG olarak nasıl kaydedeceğiniz gösterilmektedir. +og_title: C#'ta HTML'yi PNG'ye Render Etme – Tam Kılavuz +tags: +- Aspose.HTML +- C# +- Image Rendering +title: C#'de HTML'yi PNG'ye Render Et – Tam Adım Adım Rehber +url: /tr/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML'yi PNG'ye Dönüştür – Tam Adım‑Adım Kılavuz + +Hiç **render HTML to PNG** yapmanız gerekti, ancak hangi kütüphaneyi seçeceğinizi ya da çıktıyı nasıl yapılandıracağınızı bilmiyor muydunuz? Yalnız değilsiniz. Birçok geliştirici, e-posta küçük resimleri, rapor anlık görüntüleri veya otomatik UI testleri için *convert HTML to image* yapmak istediğinde aynı duvara çarpar. + +Bu öğreticide, Aspose.HTML for .NET kullanarak bir avuç satırla **save HTML as PNG** nasıl yapılır, görüntü boyutları nasıl kontrol edilir ve render kalitesi nasıl ayarlanır gösteren pratik, çalıştırmaya hazır bir örnek üzerinden ilerleyeceğiz. Sonunda, herhangi bir C# projesine ekleyebileceğiniz yeniden kullanılabilir bir kod parçacığına sahip olacaksınız. + +## İhtiyacınız Olanlar + +- **.NET 6.0 veya üzeri** (API, .NET Framework, .NET Core ve .NET 5+ ile çalışır) +- **Aspose.HTML for .NET** NuGet paketi (`Aspose.Html`) projenize kurulu. +- C# sözdizimi hakkında temel bir anlayış — ekstra bir şey gerekmez. +- Oluşturulan PNG'nin yazılacağı bir çıktı klasörü. + +Hepsi bu. Ek SDK yok, harici ikili dosya yok, sadece tek bir NuGet referansı. + +## Render HTML to PNG – Belgeyi Oluşturma + +İlk olarak, rasterleştirmek istediğimiz işaretlemeyi tutan bir `HTMLDocument` nesnesi oluşturuyoruz. HTML'yi bir dizeden, bir dosyadan ya da hatta bir URL'den yükleyebilirsiniz. Açıklık getirmek için basit bir satır içi dizeyle başlayacağız. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![render html to png çıktı örneği](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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 = "

Hello World

"; + +// In‑memory document – no file I/O required +HTMLDocument htmlDocument = new HTMLDocument(htmlContent); +``` + +> **Tại sao điều này quan trọng:** Bằng cách giữ tài liệu trong bộ nhớ, chúng ta tránh được độ trễ của đĩa và làm cho toàn bộ thao tác phù hợp cho các hàm cloud hoặc micro‑service. + +## Bước 2 – Xây Dựng Custom Resource Handler (Custom Resource Handler) + +Aspose.HTML gọi `ResourceHandler.HandleResource` cho mỗi tài nguyên bên ngoài mà nó phát hiện (hình ảnh, CSS, font). Bằng cách trả về cùng một `MemoryStream` mỗi lần, chúng ta có thể đưa tất cả các tài nguyên đó vào một gói ZIP duy nhất. + +```csharp +/// +/// Streams every resource (HTML, images, CSS, etc.) into a single ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + // The underlying ZIP stream that will contain everything. + private readonly MemoryStream zipStream = new MemoryStream(); + + /// + /// Called by Aspose.HTML for each resource. We simply return the same stream. + /// + public override Stream HandleResource(string resourceName) + { + // The library appends the resource data to the stream automatically. + return zipStream; + } + + /// + /// Retrieves the finished ZIP as a MemoryStream. + /// + public MemoryStream GetResult() => zipStream; +} +``` + +> **Mẹo chuyên nghiệp:** Nếu bạn cần giới hạn kích thước của file ZIP kết quả, có thể bọc `zipStream` trong một `LimitedStream` và ném ngoại lệ khi vượt quá giới hạn. + +## Bước 3 – Lưu Tài Liệu dưới Dạng Gói ZIP (Save HTML as ZIP) + +Bây giờ chúng ta kết hợp mọi thứ lại. Chúng ta khởi tạo handler, yêu cầu Aspose.HTML lưu tài liệu ở `SaveFormat.Zip`, và cuối cùng lấy mảng byte thô. + +```csharp +// Instantiate the handler +MemoryZipHandler zipHandler = new MemoryZipHandler(); + +// Ask Aspose.HTML to save the document using the handler. +// SaveOptions tells the library to output a ZIP archive. +htmlDocument.Save( + zipHandler, // custom ResourceHandler + new SaveOptions(SaveFormat.Zip) // output format = ZIP +); + +// Extract the in‑memory ZIP bytes for further processing +MemoryStream zipResultStream = zipHandler.GetResult(); +byte[] zipBytes = zipResultStream.ToArray(); +``` + +Tại thời điểm này `zipBytes` chứa một file ZIP hợp lệ mà bạn có thể: + +* Trả về từ một Web API (`File(zipBytes, "application/zip", "page.zip")`); +* Tải lên Azure Blob Storage; +* Gửi qua socket tới một dịch vụ khác. + +## Bước 4 – Kiểm Tra Kết Quả (Convert HTML to ZIP – Quick Test) + +Một kiểm tra nhanh để chắc chắn là ghi các byte ra đĩa (chỉ để debug) và mở archive bằng bất kỳ trình xem ZIP nào. + +```csharp +// Debug‑only: write to a temporary file to inspect the contents +File.WriteAllBytes("debug_output.zip", zipBytes); +``` + +Khi bạn mở `debug_output.zip` bạn sẽ thấy: + +* `index.html` (markup gốc) +* Các hình ảnh, file CSS hoặc font được tham chiếu và nhúng cùng bên cạnh. + +> **Tại sao cách này hoạt động:** Aspose.HTML coi file HTML chính là tài nguyên đầu tiên, sau đó stream từng tài nguyên liên kết theo thứ tự mà nó gặp. Handler của chúng ta tổng hợp chúng lại trong cùng một `MemoryStream`, và thư viện sau đó hoàn thiện thành một archive ZIP. + +## Bước 5 – Xử Lý Các Trường Hợp Đặc Biệt Thông Thường (Save HTML to ZIP Best Practices) + +### Nhiều File CSS + +Nếu trang của bạn liên kết tới nhiều stylesheet, mỗi stylesheet sẽ được thêm như một entry riêng. Không cần code bổ sung, nhưng bạn có thể muốn áp dụng quy tắc đặt tên (ví dụ, `styles/style1.css`) để tránh xung đột. + +### Tài Nguyên Nhị Phân Lớn + +Đối với các hình ảnh khổng lồ (>10 MB) hãy cân nhắc stream chúng trực tiếp tới một `FileStream` thay vì `MemoryStream` thuần. Thay thế `MemoryStream` bằng `FileStream` trong `MemoryZipHandler` và điều chỉnh `GetResult` cho phù hợp. + +### Vấn Đề Mã Hóa + +Aspose.HTML tôn trọng charset được khai báo trong header HTML. Nếu bạn cần output UTF‑8, hãy chắc chắn thẻ `` có mặt trước khi tạo `HTMLDocument`. + +## Ví Dụ Hoàn Chỉnh (Save HTML to ZIP) + +Dưới đây là chương trình đầy đủ mà bạn có thể dán vào một console app và chạy ngay. + +```csharp +using Aspose.Html; +using Aspose.Html.Saving; +using System; +using System.IO; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML document + string html = "Demo

Hello World

"; + HTMLDocument doc = new HTMLDocument(html); + + // 2️⃣ Set up the custom resource handler + MemoryZipHandler handler = new MemoryZipHandler(); + + // 3️⃣ Save as ZIP + doc.Save( + handler, + new SaveOptions(SaveFormat.Zip) + ); + + // 4️⃣ Retrieve the ZIP bytes + MemoryStream zipStream = handler.GetResult(); + byte[] zipBytes = zipStream.ToArray(); + + // 5️⃣ (Optional) Write to disk for verification + File.WriteAllBytes("output.zip", zipBytes); + Console.WriteLine($"ZIP created – {zipBytes.Length} bytes"); + } +} + +/// +/// Streams every resource into a single in‑memory ZIP archive. +/// +class MemoryZipHandler : ResourceHandler +{ + private readonly MemoryStream zipStream = new MemoryStream(); + + public override Stream HandleResource(string resourceName) + { + // All resources are appended to the same stream. + return zipStream; + } + + public MemoryStream GetResult() => zipStream; +} +``` + +**Kết quả mong đợi:** +``` +ZIP created – 1234 bytes +``` + +Mở `output.zip` sẽ hiển thị `index.html` chứa markup `

Hello World

`. Không có file phụ nào được yêu cầu. + +--- + +## Câu Hỏi Thường Gặp (FAQs) + +**H: Điều này có hoạt động với các URL bên ngoài (ví dụ, hình ảnh được lưu trên CDN)?** +Đ: Có. Aspose.HTML sẽ tải tài nguyên từ xa, sau đó truyền nó tới `HandleResource`. Chỉ cần lưu ý độ trễ mạng và các yêu cầu xác thực có thể có. + +**H: Tôi có thể đặt tên tùy chỉnh cho file HTML chính bên trong ZIP không?** +Đ: Mặc định nó là `index.html`. Để đổi tên, bạn cần thực hiện post‑process ZIP (ví dụ, dùng `System.IO.Compression.ZipArchive`) sau khi `Save` hoàn tất. + +**H: Nếu tôi muốn nén nhiều tài liệu HTML vào cùng một ZIP thì sao?** +Đ: Tạo một `HTMLDocument` riêng cho mỗi trang và gọi `Save` trên cùng một `MemoryZipHandler`. Handler sẽ tiếp tục thêm tài nguyên, tạo ra một ZIP đa trang. + +--- + +## Kết Luận + +Bây giờ bạn đã có một công thức vững chắc, **cách nén HTML** bằng cách tận dụng **custom resource handler** để **lưu HTML dưới dạng zip**, **chuyển đổi HTML sang zip**, và **lưu HTML vào zip**—tất cả mà không cần chạm tới hệ thống tệp. Cách tiếp cận này nhẹ, hoàn toàn trong bộ nhớ, và phù hợp cho các Web API, job nền, hoặc bất kỳ dịch vụ .NET nào cần gửi gói HTML ngay lập tức. + +Sẵn sàng cho bước tiếp theo? Hãy thử mở rộng handler để nén đầu ra hơn nữa bằng `System.IO.Compression.GZipStream`, hoặc tích hợp nó vào một controller ASP.NET Core trả về ZIP trực tiếp cho trình duyệt. Bầu trời là giới hạn, và bây giờ bạn đã có nền tảng để xây dựng. + +Chúc lập trình vui! 🚀 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/vietnamese/net/rendering-html-documents/_index.md b/html/vietnamese/net/rendering-html-documents/_index.md index 8ef7cb5b6..3786b03c0 100644 --- a/html/vietnamese/net/rendering-html-documents/_index.md +++ b/html/vietnamese/net/rendering-html-documents/_index.md @@ -60,6 +60,8 @@ Học cách chuyển đổi HTML sang PNG một cách dễ dàng với Aspose.HT Học cách chuyển đổi HTML sang PNG một cách dễ dàng với Aspose.HTML cho .NET. Khám phá hướng dẫn chi tiết từng bước. ### [Tạo PNG từ HTML – Hướng dẫn đầy đủ C# Rendering](./create-png-from-html-full-c-rendering-guide/) Học cách chuyển đổi HTML thành PNG bằng Aspose.HTML cho .NET với hướng dẫn chi tiết bằng C#. +### [Render HTML sang PNG trong C# – Hướng dẫn chi tiết từng bước](./render-html-to-png-in-c-complete-step-by-step-guide/) +Học cách chuyển đổi HTML thành PNG bằng C# với Aspose.HTML, bao gồm các bước chi tiết và hướng dẫn từng bước để đạt kết quả tối ưu. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/vietnamese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md b/html/vietnamese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..24b25e91b --- /dev/null +++ b/html/vietnamese/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-02-21 +description: Kết xuất HTML sang PNG nhanh chóng với Aspose.HTML. Tìm hiểu cách chuyển + đổi HTML thành hình ảnh, thiết lập chiều rộng và chiều cao của hình ảnh, và lưu + HTML dưới dạng PNG chỉ trong vài dòng C#. +draft: false +keywords: +- render html to png +- convert html to image +- save html as png +- set image width height +- generate png from html +language: vi +og_description: Render HTML sang PNG với Aspose.HTML. Hướng dẫn này cho thấy cách + chuyển đổi HTML thành hình ảnh, đặt chiều rộng và chiều cao của hình ảnh, và lưu + HTML dưới dạng PNG trong C#. +og_title: Chuyển đổi HTML sang PNG trong C# – Hướng dẫn đầy đủ +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Chuyển đổi HTML sang PNG trong C# – Hướng dẫn chi tiết từng bước +url: /vi/net/rendering-html-documents/render-html-to-png-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Render HTML to PNG – Hướng Dẫn Toàn Diện Từng Bước + +Bạn đã bao giờ cần **render HTML to PNG** nhưng không chắc nên chọn thư viện nào hoặc cách cấu hình đầu ra như thế nào? Bạn không phải là người duy nhất. Nhiều nhà phát triển gặp cùng một rào cản khi họ cố gắng *convert HTML to image* cho ảnh thu nhỏ email, ảnh chụp báo cáo, hoặc kiểm thử UI tự động. + +Trong tutorial này chúng ta sẽ đi qua một ví dụ thực tế, sẵn sàng chạy, cho bạn thấy cách **save HTML as PNG**, kiểm soát kích thước ảnh, và tinh chỉnh chất lượng render — tất cả chỉ với vài dòng code sử dụng Aspose.HTML for .NET. Khi kết thúc, bạn sẽ có một đoạn mã có thể tái sử dụng và chèn vào bất kỳ dự án C# nào. + +## Những Điều Cần Chuẩn Bị + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +- **.NET 6.0 hoặc mới hơn** (API hoạt động với .NET Framework, .NET Core, và .NET 5+) +- Gói NuGet **Aspose.HTML for .NET** (`Aspose.Html`) đã được cài đặt trong dự án của bạn. +- Kiến thức cơ bản về cú pháp C# — không cần gì phức tạp. +- Một thư mục đầu ra nơi PNG được tạo sẽ được ghi vào. + +Đó là tất cả. Không cần SDK bổ sung, không cần binary bên ngoài, chỉ một tham chiếu NuGet duy nhất. + +## Render HTML to PNG – Thiết Lập Tài Liệu + +Điều đầu tiên chúng ta làm là tạo một đối tượng `HTMLDocument` chứa markup mà chúng ta muốn rasterize. Bạn có thể tải HTML từ chuỗi, tệp, hoặc thậm chí từ URL. Để dễ hiểu, chúng ta sẽ bắt đầu với một chuỗi inline đơn giản. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Drawing; +using System.Drawing; // for Color + +// Step 1: Create an HTML document with sample content +HTMLDocument htmlDoc = new HTMLDocument( + "

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. + +![ví dụ kết quả render html sang png](output.png) + +> **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( + "" + + "

Aspose.HTML Demo

" + + "

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