diff --git a/html/arabic/net/html-extensions-and-conversions/_index.md b/html/arabic/net/html-extensions-and-conversions/_index.md index ef1367d020..15f30e2b34 100644 --- a/html/arabic/net/html-extensions-and-conversions/_index.md +++ b/html/arabic/net/html-extensions-and-conversions/_index.md @@ -126,6 +126,8 @@ url: /ar/net/html-extensions-and-conversions/ تعلم كيفية إنشاء مستند HTML وحفظه كملف ZIP باستخدام C# ومكتبة Aspose.HTML خطوة بخطوة. ### [إنشاء PDF من HTML – دليل كامل مع Aspose.Html](./create-pdf-from-html-complete-guide-with-aspose-html/) +### [كيفية حفظ HTML كملف zip باستخدام Aspose.HTML وتضمين الصور](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) + ## خاتمة في الختام، تعد امتدادات HTML وتحويلاتها عناصر أساسية لتطوير الويب الحديث. يعمل Aspose.HTML for .NET على تبسيط العملية وجعلها في متناول المطورين من جميع المستويات. باتباع دروسنا التعليمية، ستكون على الطريق الصحيح لتصبح مطور ويب ماهرًا يتمتع بمجموعة واسعة من المهارات. diff --git a/html/arabic/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/arabic/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..f531885fc7 --- /dev/null +++ b/html/arabic/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,342 @@ +--- +category: general +date: 2026-10-02 +description: تعلم كيفية حفظ HTML كملف zip باستخدام Aspose.HTML في C#. يوضح هذا الدليل + أيضًا كيفية حفظ HTML مع الصور في أرشيف واحد. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: ar +lastmod: 2026-10-02 +og_description: احفظ HTML كملف zip باستخدام Aspose.HTML في C#. اتبع هذا الدرس الكامل + لتتعلم كيفية حفظ HTML مع الصور في أرشيف واحد. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: حفظ HTML كملف zip باستخدام Aspose.HTML – دليل خطوة بخطوة بلغة C# +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: كيفية حفظ HTML كملف zip باستخدام Aspose.HTML وتضمين الصور +url: /ar/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيف تحفظ HTML كملف zip باستخدام Aspose.HTML وتضمّن الصور + +إذا كنت بحاجة إلى **حفظ HTML كملف zip** لتسهيل التوزيع، يوضح لك هذا الدليل الخطوات الدقيقة باستخدام Aspose.HTML للـ .NET. سواءً كنت تصدر صفحة ثابتة، قالب بريد إلكتروني، أو تقرير يحتوي على صور، ستتعرف على كيفية تجميع ملفات HTML وCSS والصور في أرشيف ZIP واحد دون كتابة ملفات مؤقتة على القرص. + +بالإضافة إلى الهدف الأساسي، سنجيب أيضًا على السؤال المتكرر **كيفية حفظ HTML مع الصور** بحيث يمكن لأي متصفح فتح الأرشيف الناتج دون فقدان الموارد. + +بنهاية هذا الدليل ستحصل على تنفيذ قابل لإعادة الاستخدام لـ `ResourceHandler`، برنامج C# كامل ينتج `output.zip`، ونصائح عملية للتعامل مع الصور الكبيرة أو هياكل المجلدات المخصصة. + +## المتطلبات المسبقة + +- .NET 6.0 أو أحدث (تعمل الواجهة البرمجية أيضًا مع .NET Framework 4.6+) +- حزمة NuGet الخاصة بـ Aspose.HTML للـ .NET (`Aspose.Html`) +- معرفة أساسية بـ C# والتيارات (streams) +- Visual Studio 2022 أو أي بيئة تطوير تدعم .NET + +> **نصيحة احترافية:** قم بتثبيت الحزمة عبر سطر الأوامر للحفاظ على نظافة ملف المشروع: +> `dotnet add package Aspose.Html` + +## الخطوة 1: فهم نموذج الإخراج في Aspose.HTML + +عند حفظ Aspose.HTML لمستند، يعتبر كل مورد خارجي (ملفات CSS، صور، خطوط، إلخ) **موردًا** منفصلًا. بشكل افتراضي تكتب المكتبة تلك الموارد إلى نظام الملفات. للتحكم في الوجهة، تزودها بـ `ResourceHandler` مخصص. يتلقى المعالج كائن `Resource` ويجب أن يُعيد `Stream` قابل للكتابة. ثم يقوم Aspose.HTML بكتابة بيانات المورد إلى ذلك التيار. + +استخدام معالج مخصص يتيح لك: + +- كتابة الموارد مباشرةً إلى `MemoryStream` يصبح لاحقًا إدخالًا في ملف ZIP +- تخزين الموارد في قاعدة بيانات، تخزين سحابي، أو أي وسيلة أخرى +- تعديل أسماء الملفات، مستويات الضغط، أو هياكل المجلدات + +## الخطوة 2: إنشاء `ResourceHandler` يكتب داخل أرشيف ZIP + +فيما يلي معالج كامل الوظيفة يبني `System.IO.Compression.ZipArchive` في الذاكرة. يُضاف كل مورد كإدخال جديد يحمل اسمه مسار URL الأصلي، مما يضمن قدرة المتصفح على حل الروابط النسبية عند استخراج ZIP. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### لماذا يعمل هذا النهج + +- **عملية في الذاكرة**: لا تُنشأ ملفات مؤقتة على القرص، وهو مثالي للخدمات الويب أو البيئات المعزولة. +- **يحافظ على هيكل المجلدات**: باستخدام URI المورد الأصلي، تظل الإشارات النسبية صالحة بعد الاستخراج. +- **قابل للتوسيع**: يمكنك استبدال `MemoryStream` بـ `FileStream` للكتابة مباشرة إلى ملف، أو بـ network stream للتخزين السحابي. + +## الخطوة 3: تحميل أو إنشاء مستند HTML + +للتوضيح سننشئ سلسلة HTML بسيطة تشير إلى صورة خارجية. في مشروع حقيقي ستقوم بتحميل HTML من ملف، قاعدة بيانات، أو استجابة HTTP. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **ملاحظة:** إذا كان لديك ملف HTML فعلي، استخدم `new HTMLDocument("path/to/file.html")` بدلاً من ذلك. + +## الخطوة 4: ربط المعالج بـ `SaveOptions` وحفظ الـ ZIP + +الآن نربط `ZipResourceHandler` بـ `SaveOptions.OutputStorage`. عندما يتم استدعاء `document.Save`، سيستدعي Aspose.HTML `HandleResource` لكل مورد، وسيملأ المعالج أرشيف ZIP. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### النتيجة المتوقعة + +- يحتوي `output.zip` على: + - `index.html` (ملف HTML الرئيسي) + - `images/logo.png` (الصورة المشار إليها في العلامات) + - أي ملفات CSS أو خطوط إضافية يكتشفها Aspose.HTML تلقائيًا + +عند استخراج الأرشيف وفتح `index.html` في المتصفح، تُعرض الصورة بشكل صحيح—مما يوضح **كيفية حفظ HTML مع الصور** داخل ZIP. + +## الخطوة 5: التحقق من الأرشيف ومعالجة المشكلات الشائعة + +### برنامج التحقق السريع + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +يجب أن يعرض البرنامج `index.html` و `images/logo.png`. إذا كان مورد متوقع مفقودًا: + +- **تحقق من عنوان URL للصورة**: يجب أن يكون قابلًا للوصول من مستند HTML. المسارات النسبية هي الأنسب. +- **تأكد من دعم نوع المورد**: Aspose.HTML يتعامل مع صيغ الويب الشائعة (PNG، JPEG، GIF، CSS، JS). الصيغ غير المعتادة قد تتطلب إضافة يدوية. +- **تأكد من استدعاء `HandleResource`**: أضف `Console.WriteLine(resource.Uri)` داخل `HandleResource` لتصحيح الأخطاء. + +## الخطوة 6: تنويعات متقدمة + +### 6.1 حفظ مباشرةً إلى ملف دون مصفوفة بايت وسيطة + +إذا كان استهلاك الذاكرة مصدر قلق للوثائق الكبيرة، استبدل `MemoryStream` بـ `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +ثم استخدمه كالتالي: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 تخصيص أسماء الإدخالات + +إذا كنت تفضّل هيكلًا مسطحًا (جميع الملفات في الجذر)، عدّل `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 إضافة ملف بيان (manifest) + +أحيانًا تتوقع الأدوات اللاحقة وجود `manifest.json`. يمكنك إضافته بعد الحفظ الرئيسي: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## المشكلات الشائعة وكيفية تجنّبها + +| المشكلة | سبب حدوثها | الحل | +|---------|------------|------| +| الصور تظهر معطوبة بعد الاستخراج | مسار الصورة داخل HTML لا يتطابق مع اسم ملف ZIP. | احفظ المسار النسبي الأصلي عند إنشاء `ZipArchiveEntry`. | +| الصور الكبيرة تتسبب في استثناء نفاد الذاكرة | استخدام `MemoryStream` للملفات الكبيرة قد يتجاوز حد الذاكرة للعملية. | تحول إلى معالج يعتمد على `FileStream` (انظر 6.1). | +| روابط CSS مفقودة | ملفات CSS الخارجية المشار إليها عبر `@import` لا يتم اكتشافها تلقائيًا. | أضف تلك ملفات CSS يدويًا إلى ZIP أو دمجها داخل المستند قبل الحفظ. | +| حروف Unicode تظهر مشوهة | قد يختلف الترميز الافتراضي بين مصدر HTML والتيار. | تأكد من أن سلسلة HTML هي UTF‑8؛ Aspose.HTML يحترم مجموعة الأحرف للوثيقة. | + +## مثال كامل جاهز للتنفيذ (انسخه‑الصقه) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة شاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية استخدام المعالج في Aspose.HTML – تحميل HTML، حفظ كملف ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [كيفية حفظ HTML في C# – معالجات موارد مخصصة & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [تحويل HTML إلى PNG وحفظه كملف ZIP باستخدام C# – دليل كامل](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 f08376f4aa..bbe7a4c170 100644 --- a/html/arabic/net/rendering-html-documents/_index.md +++ b/html/arabic/net/rendering-html-documents/_index.md @@ -59,6 +59,9 @@ url: /ar/net/rendering-html-documents/ ### [كيفية استخدام Aspose لعرض HTML كـ PNG في C#](./how-to-use-aspose-to-render-html-to-png-in-c/) تعلم خطوة بخطوة كيفية تحويل HTML إلى PNG باستخدام Aspose في C#. +### [كيفية استخدام Aspose لتصيير HTML إلى صورة PNG في C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +تعلم خطوة بخطوة كيفية تحويل مستندات HTML إلى صور PNG باستخدام Aspose.HTML في C#. + ### [إنشاء مستند HTML C# – تحويل إلى PNG بخط عريض مائل](./create-html-document-c-render-to-png-with-bold-italic-font/) تعلم كيفية إنشاء مستند HTML في C# وعرضه كصورة PNG باستخدام خطوط عريضة ومائلة. diff --git a/html/arabic/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/arabic/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..899d7610f2 --- /dev/null +++ b/html/arabic/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-10-02 +description: كيفية استخدام Aspose لتصوير HTML إلى صورة PNG بسرعة – تعلّم تحويل HTML + إلى PNG مع تنعيم الحواف وتلميحات النص. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: ar +lastmod: 2026-10-02 +og_description: كيفية استخدام Aspose لتحويل HTML إلى صورة PNG. اتبع هذا الدليل الكامل + لتحويل HTML إلى PNG مع عرض عالي الجودة في C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: كيفية استخدام Aspose لتحويل HTML إلى صورة PNG – دليل خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: كيفية استخدام Aspose لتحويل HTML إلى صورة PNG في C# +url: /ar/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية استخدام Aspose لتحويل HTML إلى صورة PNG في C# + +**كيفية استخدام Aspose لتحويل HTML إلى صورة PNG** هو طلب شائع عندما تحتاج إلى معاينة bitmap لصفحة ويب، أو صورة مصغرة للبريد الإلكتروني، أو لقطة صديقة للـ PDF. يوضح هذا الدليل حلاً كاملاً وجاهزًا للتنفيذ يقوم **render html to image** مع مضاد التعرج وتلميحات النص، بحيث يبدو الناتج واضحًا على كل منصة. + +سوف تتعلم كيفية **convert HTML to PNG**، وتكوين خيارات العرض، ومعالجة المشكلات الشائعة مثل عرض الخطوط على Linux وأذونات نظام الملفات. لا تحتاج إلى أدوات خارجية—فقط مكتبة Aspose.HTML لـ .NET وبعض أسطر C#. + +## المتطلبات المسبقة + +* .NET 6.0 SDK أو أحدث مثبت +* Visual Studio 2022 (أو أي بيئة تطوير C#) +* إشارة NuGet إلى **Aspose.HTML** (`Install-Package Aspose.HTML`) +* إلمام أساسي بصياغة C# + +هذه المتطلبات خفيفة؛ يعمل الدليل على Windows وLinux وmacOS لأن Aspose.HTML متعدد المنصات. + +## الخطوة 1: تثبيت Aspose.HTML وإنشاء مشروع وحدة تحكم جديد + +افتح طرفية أو وحدة تحكم مدير الحزم وشغّل: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +إنشاء مشروع مخصص يعزل الاعتمادات ويسهل تشغيل العينة باستخدام `dotnet run`. + +## الخطوة 2: إعداد خيارات عرض الصورة (مضاد التعرج وتلميحات النص) + +مضاد التعرج (Antialiasing) ينعم الحواف، بينما تحسين النص (text hinting) يحسن وضوح الحروف، خاصة على Linux حيث تختلف عملية تمثيل الخطوط عن Windows. تسمح لك فئة `ImageRenderingOptions` بتمكين كلا الميزتين: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**لماذا هذا مهم:** بدون مضاد التعرج، تبدو الخطوط القطرية والمنحنيات متعرجة. بدون تحسين النص، قد تصبح الأحجام الصغيرة للخط غير واضحة، وهو ما يلاحظه عند **save html as png** للصور المصغرة. + +## الخطوة 3: تعريف CSS للخطوط المتسقة وأنماط العناوين + +إدراج CSS مباشرةً في HTML يضمن أن الصورة المرسومة تتطابق مع توقعات التصميم. في هذا المثال نحدد خطًا أساسيًا ونجعل `

` مائلًا: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +يمكنك توسيع ورقة الأنماط بالألوان أو الهوامش أو استعلامات الوسائط. يتم حقن CSS داخل وسم ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**نصيحة:** إذا كنت بحاجة إلى **render html as image** من صفحة بعيدة، استبدل منشئ السلسلة بـ `new HTMLDocument("https://example.com")`. سيقوم Aspose بتحميل الصفحة، حل الموارد، ورسم التخطيط النهائي. + +## الخطوة 5: رسم المستند إلى ملف PNG + +الآن نستدعي `RenderToImage`، مع تمرير مسار الإخراج والخيارات التي قمنا بتكوينها مسبقًا: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +سيحتوي `output.png` المُولد على رسم واضح لعنصر `

` مع نمط مائل، بفضل إعدادات مضاد التعرج وتلميحات النص. + +## قائمة البرنامج الكاملة + +انسخ الشيفرة التالية إلى `Program.cs`. ستُجمع وتُنفّذ كما هي: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### النتيجة المتوقعة + +تشغيل البرنامج ينشئ `output.png` في مجلد المشروع. تُظهر الصورة كلمة **Sample** بخط Arial مائل، مرسومة بحواف ناعمة ونص واضح. افتح الملف بأي عارض صور للتحقق من الجودة. + +## الخطوة 6: التغييرات الشائعة ومعالجة الحالات الطرفية + +| الحالة | ما الذي يجب تعديله | السبب | +|-----------|----------------|--------| +| **صفحات HTML الكبيرة** | حدد `ImageRenderingOptions.Width` / `Height` أو استخدم `PageSize` للتحكم في أبعاد الإخراج | يمنع استهلاك الذاكرة الزائد ويضمن أن PNG يتناسب مع واجهة المستخدم الخاصة بك | +| **خط Linux مفقود** | ثبت الخطوط المطلوبة على المضيف (`apt-get install fonts‑arial` أو استخدم ملف خط مخصص) ووجه Aspose إليه عبر `FontSettings` | بدون الخط، سيعود Aspose إلى خط عام، مما يغيّر المظهر | +| **الخلفية الشفافة مطلوبة** | عيّن `imgOptions.BackgroundColor = Color.Transparent` | مفيد عند دمج PNG في رسومات أخرى | +| **تحويل دفعي** | تكرار عبر قائمة من سلاسل HTML أو مسارات الملفات، وإعادة استخدام نفس كائن `ImageRenderingOptions` | يحسن الأداء ويحافظ على اتساق إعدادات العرض | + +## نصيحة احترافية: تخزين خيارات العرض مؤقتًا + +إنشاء كائن `ImageRenderingOptions` جديد لكل تحويل يضيف عبئًا. أعلن عن نسخة ثابتة إذا كنت تعالج العديد من مقاطع HTML في خدمة: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +أعد استخدام `SharedOptions` عبر الاستدعاءات للحفاظ على انخفاض استهلاك المعالج. + +## الأسئلة المتكررة + +**س: هل يعمل هذا مع .NET Core على macOS؟** +ج: نعم. Aspose.HTML متعدد المنصات بالكامل. تأكد من تثبيت الخطوط المطلوبة، وأن دليل الإخراج قابل للكتابة. + +**س: هل يمكنني الرسم إلى JPEG بدلاً من PNG؟** +ج: استبدل `RenderToImage("output.png", imgOptions)` بـ `RenderToImage("output.jpg", imgOptions)`. يمكنك أيضًا تعيين `imgOptions.ImageFormat = ImageFormat.Jpeg` للتحكم الدقيق في الجودة. + +**س: كيف يمكنني تضمين ملفات CSS خارجية؟** +ج: حمّل محتوى CSS إلى سلسلة نصية وادمجها، أو أشر إلى ورقة أنماط عن بُعد في وسم ``. يقوم Aspose بحل وسوم `` تلقائيًا عندما يتم تحميل المستند من URL. + +## الخلاصة + +أنت الآن تعرف **how to use Aspose** لـ **render HTML to PNG** (أو أي تنسيق نقطي آخر) بإعدادات عالية الجودة. يغطي الدليل تثبيت Aspose.HTML، تكوين مضاد التعرج وتلميحات النص، إدراج CSS، تحميل HTML، وأخيرًا **saving HTML as PNG**. باتباع الخطوات يمكنك بثقة **convert HTML to PNG** في أي تطبيق .NET، سواء كان يعمل على Windows أو Linux أو macOS. + +### الخطوات التالية + +* استكشف صيغ إخراج أخرى مثل **render html as image** JPEG أو BMP بتغيير امتداد الملف. +* اجمع هذا النهج مع **Aspose.PDF** لتضمين PNG في تقرير PDF. +* جرب `ImageRenderingOptions.DpiX` و `DpiY` للحصول على صور مصغرة عالية الدقة. + +لا تتردد في تعديل الشيفرة للمعالجة الدفعية، أو توليد HTML ديناميكيًا، أو دمجها في خدمة ويب تُعيد معاينات PNG عند الطلب. نتمنى لك رسمًا سعيدًا! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة شيفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية استخدام Aspose لتصوير HTML إلى PNG – دليل خطوة بخطوة](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [كيفية تصوير HTML إلى PNG باستخدام Aspose – دليل كامل](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [دروس html إلى صورة – تصوير HTML إلى PNG باستخدام Aspose.HTML في C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 ba75fca312..8e44ed8716 100644 --- a/html/chinese/net/html-extensions-and-conversions/_index.md +++ b/html/chinese/net/html-extensions-and-conversions/_index.md @@ -146,6 +146,9 @@ Aspose.HTML for .NET 不仅仅是一个库;它是 Web 开发领域的变革者 ### [使用 Aspose.HTML 将 HTML 创建为 PDF – 完整指南](./create-pdf-from-html-complete-guide-with-aspose-html/) 使用 Aspose.HTML for .NET 将 HTML 转换为 PDF 的完整指南,提供详细步骤和代码示例。 +### [使用 Aspose.HTML 将 HTML 保存为 ZIP 并包含图像](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +使用 Aspose.HTML for .NET 将 HTML 打包为 ZIP 并保留图像的完整分步指南。 + ## 结论 总之,HTML 扩展和转换是现代 Web 开发的基本要素。Aspose.HTML for .NET 简化了该过程,使各个级别的开发人员都可以使用它。通过学习我们的教程,您将成为一名拥有广泛技能的熟练 Web 开发人员。 diff --git a/html/chinese/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/chinese/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..4db70d3766 --- /dev/null +++ b/html/chinese/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,330 @@ +--- +category: general +date: 2026-10-02 +description: 学习如何在 C# 中使用 Aspose.HTML 将 HTML 保存为 zip。本指南还展示了如何将包含图像的 HTML 保存为单个归档文件。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: zh +lastmod: 2026-10-02 +og_description: 使用 Aspose.HTML 在 C# 中将 HTML 保存为 zip。请跟随本完整教程,了解如何将包含图像的 HTML 保存为单个压缩包。 +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: 使用 Aspose.HTML 将 HTML 保存为 zip – 步骤详解 C# 指南 +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: 如何使用 Aspose.HTML 将 HTML 保存为 zip 并包含图像 +url: /zh/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何使用 Aspose.HTML 将 HTML 保存为 zip 并包含图像 + +如果您需要 **将 HTML 保存为 zip** 以便轻松分发,本教程将展示使用 Aspose.HTML for .NET 的完整步骤。无论您是导出静态页面、电子邮件模板,还是包含图像的报告,您都将看到如何将 HTML、CSS 和图像文件打包成单个 ZIP 存档,而无需将临时文件写入磁盘。 + +除了主要目标外,我们还会回答常见的后续问题 **如何将 HTML 与图像一起保存**,以便生成的存档可以在任何浏览器中打开且资源完整。 + +阅读完本指南后,您将拥有可复用的 `ResourceHandler` 实现、一个完整的 C# 程序可生成 `output.zip`,以及处理大图像或自定义文件夹结构的实用技巧。 + +## 前置条件 + +- .NET 6.0 或更高版本(该 API 也兼容 .NET Framework 4.6+) +- Aspose.HTML for .NET NuGet 包(`Aspose.Html`) +- 基本的 C# 与流(stream)知识 +- Visual Studio 2022 或任何支持 .NET 开发的 IDE + +> **专业提示:** 通过 CLI 安装包可保持项目文件整洁: +> `dotnet add package Aspose.Html` + +## 第 1 步:了解 Aspose.HTML 的输出模型 + +当 Aspose.HTML 保存文档时,它会将每个外部资源(CSS 文件、图像、字体等)视为单独的 **resource**。默认情况下,库会将这些资源写入文件系统。若要控制目标位置,需要提供自定义的 `ResourceHandler`。该处理器接收一个 `Resource` 对象并必须返回一个可写的 `Stream`。随后 Aspose.HTML 会将资源数据写入该流。 + +使用自定义处理器可以: + +- 将资源直接写入 `MemoryStream`,随后成为 ZIP 条目 +- 将资源存储在数据库、云存储或其他介质中 +- 调整文件名、压缩级别或文件夹层级 + +## 第 2 步:创建一个将资源写入 ZIP 存档的 `ResourceHandler` + +下面是一个完整可用的处理器,它在内存中构建 `System.IO.Compression.ZipArchive`。每个资源都会作为新条目添加,条目名称与原始 URL 路径保持一致,确保在解压后浏览器能够解析相对链接。 + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### 为什么这种方式可行 + +- **内存操作**:不在磁盘上创建临时文件,适用于 Web 服务或受限环境。 +- **保留文件夹层级**:使用原始资源 URI,解压后相对引用仍然有效。 +- **可扩展**:可以将 `MemoryStream` 替换为 `FileStream` 直接写入文件,或替换为网络流写入云存储。 + +## 第 3 步:加载或创建 HTML 文档 + +为演示我们将创建一个引用外部图像的简单 HTML 字符串。在实际项目中,您可能会从文件、数据库或 HTTP 响应中加载 HTML。 + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **注意:** 如果您有实体 HTML 文件,请使用 `new HTMLDocument("path/to/file.html")`。 + +## 第 4 步:将处理器绑定到 `SaveOptions` 并保存 ZIP + +现在我们把 `ZipResourceHandler` 连接到 `SaveOptions.OutputStorage`。当 `document.Save` 执行时,Aspose.HTML 会为每个资源调用 `HandleResource`,处理器随后填充 ZIP 存档。 + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### 预期结果 + +- `output.zip` 包含: + - `index.html`(主 HTML 文件) + - `images/logo.png`(标记中引用的图像) + - 任何 Aspose.HTML 自动检测到的额外 CSS 或字体文件 + +解压存档并在浏览器中打开 `index.html`,图像即可正常显示——演示了 **如何将 HTML 与图像一起保存** 到 ZIP 中。 + +## 第 5 步:验证存档并排查常见问题 + +### 快速验证脚本 + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +运行脚本应列出 `index.html` 和 `images/logo.png`。如果发现缺少预期资源: + +- **检查图像 URL**:必须能够从 HTML 文档访问。相对路径效果最佳。 +- **确保资源类型受支持**:Aspose.HTML 处理常见的网络格式(PNG、JPEG、GIF、CSS、JS)。异常格式可能需要手动添加。 +- **确认已调用 `HandleResource`**:在 `HandleResource` 中加入 `Console.WriteLine(resource.Uri)` 进行调试。 + +## 第 6 步:高级变体 + +### 6.1 直接保存到文件而不使用中间字节数组 + +如果文档非常大导致内存使用成为顾虑,可将 `MemoryStream` 替换为 `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +随后按如下方式使用: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 自定义条目名称 + +若希望使用扁平结构(所有文件位于根目录),可调整 `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 添加清单文件 + +有时下游工具需要 `manifest.json`。您可以在主保存完成后添加该文件: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## 常见陷阱及规避方法 + +| 陷阱 | 产生原因 | 解决方案 | +|------|----------|----------| +| 解压后图像显示破碎 | HTML 中的图像路径与 ZIP 条目名称不匹配 | 在创建 `ZipArchiveEntry` 时保留原始相对路径 | +| 大图像导致内存溢出 | 对非常大的文件使用 `MemoryStream` 会超出进程内存限制 | 使用基于 `FileStream` 的处理器(参见 6.1) | +| CSS URL 丢失 | 通过 `@import` 引用的外部 CSS 未被自动检测 | 手动将这些 CSS 文件加入 ZIP,或在保存前将其内联 | +| Unicode 字符乱码 | 默认编码可能与 HTML 源的字符集不一致 | 确保 HTML 字符串为 UTF‑8,Aspose.HTML 会遵循文档的 charset | + +## 完整可运行示例(复制粘贴即用) + + + +## 接下来您应该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助您进一步掌握 API 功能并探索在项目中的替代实现方式。每篇资源均提供完整可运行的代码示例和逐步说明。 + +- [how to use handler in Aspose.HTML – Load HTML, Save as ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [How to Save HTML in C# – Custom Resource Handlers & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Render HTML to PNG and Save to ZIP with C# – Complete Guide](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 60f8f3508d..39bfbb1920 100644 --- a/html/chinese/net/rendering-html-documents/_index.md +++ b/html/chinese/net/rendering-html-documents/_index.md @@ -101,6 +101,8 @@ Aspose.HTML for .NET 凭借其丰富的功能、出色的文档和活跃的社 ### [如何在 C# 中将 HTML 渲染为 PNG – 步骤指南](./how-to-render-html-as-png-in-c-step-by-step-guide/) 本指南详细演示如何使用 Aspose.HTML for .NET 在 C# 中将 HTML 渲染为 PNG,提供分步示例和最佳实践。 +### [如何在 C# 中使用 Aspose 将 HTML 渲染为 PNG 图像](./how-to-use-aspose-to-render-html-to-png-image-in-c/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/chinese/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/chinese/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..abbc7f09b8 --- /dev/null +++ b/html/chinese/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-10-02 +description: 如何使用 Aspose 快速将 HTML 渲染为 PNG 图像——学习使用抗锯齿和文字提示将 HTML 转换为 PNG。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: zh +lastmod: 2026-10-02 +og_description: 如何使用 Aspose 将 HTML 渲染为 PNG 图像。请按照本完整教程,在 C# 中将 HTML 转换为 PNG,并实现高质量渲染。 +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: 如何使用 Aspose 将 HTML 渲染为 PNG 图像——一步步指南 +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: 如何在 C# 中使用 Aspose 将 HTML 渲染为 PNG 图像 +url: /zh/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 C# 中使用 Aspose 将 HTML 渲染为 PNG 图像 + +**如何使用 Aspose 将 HTML 渲染为 PNG 图像** 是在需要网页位图预览、邮件缩略图或 PDF 友好快照时的常见需求。本教程展示了一个完整、可直接运行的解决方案,能够 **render html to image**,并带有抗锯齿和文字 hinting,使得结果在所有平台上都保持清晰锐利。 + +您将学习如何 **convert HTML to PNG**,配置渲染选项,以及处理常见的陷阱,如 Linux 字体渲染和文件系统权限。无需外部工具——只需 Aspose.HTML for .NET 库和几行 C# 代码。 + +## 前置条件 + +开始之前,请确保您拥有: + +* 已安装 .NET 6.0 SDK 或更高版本 +* Visual Studio 2022(或任意 C# IDE) +* 对 **Aspose.HTML** 的 NuGet 引用(`Install-Package Aspose.HTML`) +* 基本的 C# 语法熟悉度 + +这些前置条件非常轻量,教程可在 Windows、Linux 和 macOS 上运行,因为 Aspose.HTML 是跨平台的。 + +## 第 1 步:安装 Aspose.HTML 并创建新控制台项目 + +打开终端或 Package Manager Console,运行: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +创建专用项目可以隔离依赖,并且使用 `dotnet run` 轻松运行示例。 + +## 第 2 步:设置图像渲染选项(抗锯齿和文字 hinting) + +抗锯齿用于平滑边缘,文字 hinting 则提升字形清晰度,尤其在 Linux 上字体光栅化方式与 Windows 不同。`ImageRenderingOptions` 类让您同时启用这两项功能: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**为什么重要:** 没有抗锯齿,斜线和曲线会出现锯齿;没有文字 hinting,较小的字体会模糊,这在 **save html as png** 用于缩略图时尤为明显。 + +## 第 3 步:定义 CSS 以保持字体和标题样式的一致性 + +将 CSS 直接嵌入 HTML 可确保渲染的图像符合设计预期。本例中我们设置基础字体并将 `

` 设置为斜体: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +您可以在样式表中添加颜色、外边距或媒体查询。CSS 会被注入到 HTML 文档的 ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**提示:** 如果需要 **render html as image** 来自远程页面,只需将字符串构造器替换为 `new HTMLDocument("https://example.com")`。Aspose 将下载页面、解析资源并渲染最终布局。 + +## 第 5 步:将文档渲染为 PNG 文件 + +现在调用 `RenderToImage`,传入输出路径以及前面配置的选项: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +生成的 `output.png` 将包含带斜体样式的 `

` 元素的清晰渲染,得益于抗锯齿和 hinting 设置。 + +## 完整程序清单 + +将以下代码复制到 `Program.cs` 中。它可以直接编译运行: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### 预期输出 + +运行程序后会在项目文件夹中生成 `output.png`。图像显示 **Sample** 文字,使用斜体 Arial,边缘平滑、文字清晰。使用任意图像查看器打开即可验证质量。 + +## 第 6 步:常见变体和边缘情况处理 + +| 场景 | 需要调整的内容 | 原因 | +|-----------|----------------|--------| +| **大型 HTML 页面** | 设置 `ImageRenderingOptions.Width` / `Height` 或使用 `PageSize` 来控制输出尺寸 | 防止内存暴涨并确保 PNG 能适配 UI | +| **Linux 缺少字体** | 在主机上安装所需字体(`apt-get install fonts‑arial` 或使用自定义字体文件),并通过 `FontSettings` 将其指向 Aspose | 若缺少字体,Aspose 会回退到通用字体,导致外观改变 | +| **需要透明背景** | 设置 `imgOptions.BackgroundColor = Color.Transparent` | 在将 PNG 嵌入其他图形时非常有用 | +| **批量转换** | 对 HTML 字符串或文件路径列表进行循环,复用同一个 `ImageRenderingOptions` 对象 | 提高性能并保持渲染设置一致 | + +## 专业技巧:缓存渲染选项 + +为每次转换创建新的 `ImageRenderingOptions` 对象会增加开销。如果在服务中处理大量 HTML 片段,建议声明一个静态实例: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +在调用之间复用 `SharedOptions` 可降低 CPU 使用率。 + +## 常见问答 + +**问:这在 macOS 上的 .NET Core 能运行吗?** +答:可以。Aspose.HTML 完全跨平台。确保已安装所需字体,并且输出目录可写。 + +**问:可以渲染为 JPEG 而不是 PNG 吗?** +答:将 `RenderToImage("output.png", imgOptions)` 替换为 `RenderToImage("output.jpg", imgOptions)`。也可以设置 `imgOptions.ImageFormat = ImageFormat.Jpeg` 以更细致地控制质量。 + +**问:如何嵌入外部 CSS 文件?** +答:将 CSS 内容读取为字符串并拼接,或在 `` 中引用远程样式表。Aspose 在从 URL 加载文档时会自动解析 `` 标签。 + +## 结论 + +现在您已经掌握 **如何使用 Aspose** 来 **render HTML to PNG**(或任何其他光栅格式)的高质量设置。教程涵盖了安装 Aspose.HTML、配置抗锯齿和文字 hinting、注入 CSS、加载 HTML,最后 **saving HTML as PNG**。按照这些步骤,您可以在任何 .NET 应用程序中可靠地 **convert HTML to PNG**,无论运行在 Windows、Linux 还是 macOS 上。 + +### 后续步骤 + +* 探索其他输出格式,例如通过更改文件扩展名将 **render html as image** 输出为 JPEG 或 BMP。 +* 将此方法与 **Aspose.PDF** 结合,将 PNG 嵌入 PDF 报告中。 +* 试验 `ImageRenderingOptions.DpiX` 与 `DpiY`,生成高分辨率缩略图。 + +欢迎根据批处理、动态 HTML 生成或在 Web 服务中返回 PNG 预览的需求自行改造代码。祝渲染愉快! + +## 接下来您应该学习什么? + +以下教程涵盖与本指南技术密切相关的主题,帮助您进一步掌握 API 功能并探索替代实现方式: + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 01daa9497e..16700e3ad2 100644 --- a/html/czech/net/html-extensions-and-conversions/_index.md +++ b/html/czech/net/html-extensions-and-conversions/_index.md @@ -129,7 +129,10 @@ Naučte se, jak pomocí Aspose.HTML pro .NET uložit HTML do streamu v C# s podr ### [Jak použít handler v Aspose.HTML – načíst HTML a uložit jako ZIP](./how-to-use-handler-in-aspose-html-load-html-save-as-zip/) Naučte se pomocí Aspose.HTML načíst HTML dokument a uložit jej do ZIP archivu pomocí handleru v C#. ### [Vytvořte HTML dokument a uložte jako ZIP – Kompletní C# průvodce](./create-html-document-and-save-as-zip-complete-c-guide/) -Naučte se vytvořit HTML dokument a uložit jej jako ZIP archiv v kompletním C# průvodci s Aspose.HTML pro .NET. +Naučte se vytvořit HTML dokument a uložit jej do ZIP archivů v kompletním C# průvodci s Aspose.HTML pro .NET. + +### [Uložte HTML jako ZIP s Aspose.HTML a zahrňte obrázky](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Naučte se uložit HTML soubor jako ZIP archiv a zahrnout do něj obrázky pomocí Aspose.HTML v C#. ## Závěr diff --git a/html/czech/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/czech/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..74eb7f482b --- /dev/null +++ b/html/czech/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,349 @@ +--- +category: general +date: 2026-10-02 +description: Naučte se, jak uložit HTML jako zip pomocí Aspose.HTML v C#. Tento průvodce + také ukazuje, jak uložit HTML s obrázky do jednoho archivu. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: cs +lastmod: 2026-10-02 +og_description: Uložte HTML jako zip pomocí Aspose.HTML v C#. Sledujte tento kompletní + tutoriál a naučte se, jak uložit HTML s obrázky do jednoho archivu. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Uložte HTML jako zip pomocí Aspose.HTML – krok za krokem průvodce C# +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Jak uložit HTML jako zip pomocí Aspose.HTML a zahrnout obrázky +url: /cs/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak uložit HTML jako zip pomocí Aspose.HTML a zahrnout obrázky + +Pokud potřebujete **uložit HTML jako zip** pro snadnou distribuci, tento tutoriál vám ukáže přesné kroky pomocí Aspose.HTML pro .NET. Ať už exportujete statickou stránku, e‑mailovou šablonu nebo zprávu, která obsahuje obrázky, uvidíte, jak zabalit soubory HTML, CSS a obrázky do jediného ZIP archivu, aniž byste zapisovali dočasné soubory na disk. + +Kromě hlavního cíle také zodpovíme běžnou doplňkovou otázku **jak uložit HTML s obrázky**, aby výsledný archiv mohl otevřít jakýkoli prohlížeč bez chybějících zdrojů. + +Na konci tohoto průvodce budete mít znovupoužitelnou implementaci `ResourceHandler`, kompletní C# program, který vytvoří `output.zip`, a praktické tipy pro práci s velkými obrázky nebo vlastními strukturami složek. + +## Požadavky + +- .NET 6.0 nebo novější (API funguje také s .NET Framework 4.6+) +- NuGet balíček Aspose.HTML pro .NET (`Aspose.Html`) +- Základní znalosti C# a streamů +- Visual Studio 2022 nebo jakékoli IDE podporující vývoj v .NET + +> **Tip:** Nainstalujte balíček pomocí CLI, aby byl soubor projektu čistý: +> `dotnet add package Aspose.Html` + +## Krok 1: Pochopit výstupní model Aspose.HTML + +Když Aspose.HTML uloží dokument, zachází s každým externím zdrojem (CSS soubory, obrázky, fonty atd.) jako s odděleným **resource**. Ve výchozím nastavení knihovna zapisuje tyto zdroje do souborového systému. Pro kontrolu cíle poskytnete vlastní `ResourceHandler`. Handler přijímá objekt `Resource` a musí vrátit zapisovatelný `Stream`. Aspose.HTML pak zapíše data zdroje do tohoto streamu. + +Použitím vlastního handleru můžete: + +- Zapisovat zdroje přímo do `MemoryStream`, který se později stane položkou ZIP +- Ukládat zdroje do databáze, cloudového úložiště nebo jakéhokoli jiného média +- Upravit názvy souborů, úrovně komprese nebo hierarchii složek + +## Krok 2: Vytvořit `ResourceHandler`, který zapisuje do ZIP archivu + +Níže je plně funkční handler, který v paměti vytváří `System.IO.Compression.ZipArchive`. Každý zdroj je přidán jako nová položka, jejíž název odráží původní cestu URL, což zajišťuje, že prohlížeč může po rozbalení ZIP souboru vyřešit relativní odkazy. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Proč tento přístup funguje + +- **In‑memory operation**: Na disku nejsou vytvářeny žádné dočasné soubory, což je ideální pro webové služby nebo sandboxované prostředí. +- **Preserves folder hierarchy**: Použitím původního URI zdroje zůstávají relativní odkazy po rozbalení platné. +- **Extensible**: Můžete nahradit `MemoryStream` za `FileStream` pro přímý zápis do souboru, nebo za síťový stream pro cloudové úložiště. + +## Krok 3: Načíst nebo vytvořit HTML dokument + +Pro demonstraci vytvoříme jednoduchý HTML řetězec, který odkazuje na externí obrázek. Ve skutečném projektu byste HTML načetli ze souboru, databáze nebo HTTP odpovědi. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Note:** Pokud máte fyzický HTML soubor, použijte místo toho `new HTMLDocument("path/to/file.html")`. + +## Krok 4: Připojit handler k `SaveOptions` a uložit ZIP + +Nyní připojíme `ZipResourceHandler` k `SaveOptions.OutputStorage`. Když se spustí `document.Save`, Aspose.HTML zavolá `HandleResource` pro každý zdroj a handler naplní ZIP archiv. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Očekávaný výsledek + +- `output.zip` obsahuje: + - `index.html` (hlavní HTML soubor) + - `images/logo.png` (obrázek odkazovaný v markupu) + - Jakékoli další CSS nebo font soubory automaticky detekované Aspose.HTML + +Když rozbalíte archiv a otevřete `index.html` v prohlížeči, obrázek se zobrazí správně — což demonstruje **jak uložit HTML s obrázky** uvnitř ZIP. + +## Krok 5: Ověřit archiv a řešit běžné problémy + +### Rychlý ověřovací skript + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Spuštění skriptu by mělo vypsat `index.html` a `images/logo.png`. Pokud chybí očekávaný zdroj: + +- **Zkontrolujte URL obrázku**: Musí být přístupná z HTML dokumentu. Relativní cesty fungují nejlépe. +- **Ujistěte se, že typ zdroje je podporován**: Aspose.HTML zpracovává běžné webové formáty (PNG, JPEG, GIF, CSS, JS). Neobvyklé formáty mohou vyžadovat ruční přidání. +- **Potvrďte, že `HandleResource` je voláno**: Přidejte `Console.WriteLine(resource.Uri)` uvnitř `HandleResource` pro ladění. + +## Krok 6: Pokročilé varianty + +### 6.1 Ukládání přímo do souboru bez mezilehlého pole bajtů + +Pokud je spotřeba paměti problémem u velmi velkých dokumentů, nahraďte `MemoryStream` za `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Pak jej použijte takto: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Přizpůsobení názvů položek + +Pokud dáváte přednost ploché struktuře (všechny soubory v kořenovém adresáři), upravte `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Přidání souboru manifestu + +Někdy downstream nástroje očekávají `manifest.json`. Můžete jej přidat po hlavním uložení: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Běžné úskalí a jak se jim vyhnout + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| Images appear broken after extraction | The image path inside HTML does not match the ZIP entry name. | Preserve the original relative path when creating `ZipArchiveEntry`. | +| Large images cause out‑of‑memory exceptions | Using `MemoryStream` for very large files can exceed the process’s memory limit. | Switch to a `FileStream`‑based handler (see 6.1). | +| CSS URLs are missing | External CSS files referenced via `@import` are not detected automatically. | Manually add those CSS files to the ZIP or embed them inline before saving. | +| Unicode characters become garbled | The default encoding may differ between the HTML source and the stream. | Ensure the HTML string is UTF‑8; Aspose.HTML respects the document’s charset. | + +| Úskalí | Proč se to děje | Řešení | +|---------|----------------|-----| +| Images appear broken after extraction | The image path inside HTML does not match the ZIP entry name. | Preserve the original relative path when creating `ZipArchiveEntry`. | +| Large images cause out‑of‑memory exceptions | Using `MemoryStream` for very large files can exceed the process’s memory limit. | Switch to a `FileStream`‑based handler (see 6.1). | +| CSS URLs are missing | External CSS files referenced via `@import` are not detected automatically. | Manually add those CSS files to the ZIP or embed them inline before saving. | +| Unicode characters become garbled | The default encoding may differ between the HTML source and the stream. | Ensure the HTML string is UTF‑8; Aspose.HTML respects the document’s charset. | + +## Kompletní funkční příklad (připravený ke kopírování a vložení) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, aby vám pomohly zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [jak použít handler v Aspose.HTML – Načíst HTML, uložit jako ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Jak uložit HTML v C# – Vlastní Resource Handlery & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Renderování HTML do PNG a uložení do ZIP pomocí C# – Kompletní průvodce](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 7ceeccf0f5..71f25f0257 100644 --- a/html/czech/net/rendering-html-documents/_index.md +++ b/html/czech/net/rendering-html-documents/_index.md @@ -52,8 +52,10 @@ Kompletní návod v C#, jak pomocí Aspose.HTML převést HTML soubory do formá Naučte se, jak pomocí Aspose.HTML v C# převést HTML do obrázku. Kompletní průvodce krok za krokem. ### [Jak použít Aspose k vykreslení HTML do PNG v C#](./how-to-use-aspose-to-render-html-to-png-in-c/) Naučte se, jak pomocí Aspose.HTML v C# převést HTML soubory do PNG formátu. Praktické ukázky a tipy pro rychlé vykreslení. -### [Jak vykreslit HTML jako PNG v C# – krok za krokem](./how-to-render-html-as-png-in-c-step-by-step-guide/) -Kompletní průvodce v C#, který ukazuje, jak převést HTML do PNG pomocí Aspose.HTML krok po kroku. +### [Jak použít Aspose k vykreslení HTML do PNG obrázku v C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Naučte se, jak pomocí Aspose.HTML v C# převést HTML do PNG obrázku pomocí podrobného průvodce krok za krokem. +### [Jak vykreslit HTML jako PNG – krok‑za‑krokem průvodce C#](./how-to-render-html-as-png-in-c-step-by-step-guide/) +Kompletní návod, jak pomocí Aspose.HTML v .NET převést HTML do PNG v C# s podrobnými kroky a tipy. ### [Renderujte EPUB jako XPS v .NET pomocí Aspose.HTML](./render-epub-as-xps/) V tomto komplexním kurzu se dozvíte, jak vytvářet a vykreslovat dokumenty HTML pomocí Aspose.HTML for .NET. Ponořte se do světa HTML manipulace, web scraping a další. diff --git a/html/czech/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/czech/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..c1368ebe1d --- /dev/null +++ b/html/czech/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-10-02 +description: Jak použít Aspose k rychlému vykreslení HTML do PNG obrázku – naučte + se převádět HTML na PNG s antialiasingem a textovým hintingem. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: cs +lastmod: 2026-10-02 +og_description: Jak použít Aspose k vykreslení HTML do PNG obrázku. Sledujte tento + kompletní tutoriál, jak převést HTML na PNG s vysoce kvalitním vykreslováním v C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Jak použít Aspose k renderování HTML do PNG obrázku – krok za krokem +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Jak použít Aspose k renderování HTML do PNG obrázku v C# +url: /cs/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak použít Aspose k vykreslení HTML do PNG obrázku v C# + +**Jak použít Aspose k vykreslení HTML do PNG obrázku** je častý požadavek, když potřebujete bitmapový náhled webové stránky, miniaturu e‑mailu nebo PDF‑přátelský snímek. Tento tutoriál vám ukáže kompletní, připravené řešení, které **render html to image** s antialiasingem a textovým hintingem, takže výsledek vypadá ostře na každé platformě. + +Naučíte se, jak **convert HTML to PNG**, nakonfigurovat možnosti vykreslování a vyřešit typické problémy, jako je vykreslování fontů na Linuxu a oprávnění souborového systému. Nepotřebujete žádné externí nástroje — pouze knihovnu Aspose.HTML pro .NET a několik řádků C#. + +## Prerequisites + +Než začnete, ujistěte se, že máte: + +* .NET 6.0 SDK nebo novější nainstalovaný +* Visual Studio 2022 (nebo jakékoli C# IDE) +* NuGet referenci na **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Základní znalosti syntaxe C# + +Tyto předpoklady jsou nenáročné; tutoriál funguje na Windows, Linuxu i macOS, protože Aspose.HTML je multiplatformní. + +## Krok 1: Instalace Aspose.HTML a vytvoření nového konzolového projektu + +Otevřete terminál nebo Package Manager Console a spusťte: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Vytvoření samostatného projektu izoluje závislosti a usnadní spuštění ukázky pomocí `dotnet run`. + +## Krok 2: Nastavení možností vykreslování obrázku (antialiasing a text hinting) + +Antialiasing vyhlazuje hrany, zatímco text hinting zlepšuje čitelnost glyfů, zejména na Linuxu, kde se rasterizace fontů liší od Windows. Třída `ImageRenderingOptions` vám umožní povolit obě funkce: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Proč je to důležité:** Bez antialiasingu vypadají úhlopříčné čáry a křivky zubatě. Bez text hintingu mohou malé velikosti fontu být rozmazané, což je patrné, když **save html as png** pro miniatury. + +## Krok 3: Definování CSS pro konzistentní fonty a styly nadpisů + +Vložení CSS přímo do HTML zajišťuje, že vykreslený obrázek odpovídá vašim designovým očekáváním. V tomto příkladu nastavíme základní font a uděláme `

` kurzívou: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Můžete rozšířit stylopis o barvy, okraje nebo media queries. CSS je vloženo do tagu ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Tip:** Pokud potřebujete **render html as image** z vzdálené stránky, nahraďte konstruktor řetězce `new HTMLDocument("https://example.com")`. Aspose stránku stáhne, vyřeší zdroje a vykreslí finální rozvržení. + +## Krok 5: Vykreslení dokumentu do PNG souboru + +Nyní zavoláme `RenderToImage`, předáme cestu k výstupu a předchozí nastavené možnosti: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +Vygenerovaný `output.png` bude obsahovat ostré vykreslení elementu `

` s kurzívním stylem, díky nastavením antialiasingu a hintingu. + +## Kompletní výpis programu + +Zkopírujte následující kód do `Program.cs`. Překompiluje se a spustí tak, jak je: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Očekávaný výstup + +Spuštěním programu se v kořenovém adresáři projektu vytvoří `output.png`. Obrázek zobrazuje slovo **Sample** kurzívním Arial, vykreslené s hladkými hranami a čistým textem. Otevřete soubor v libovolném prohlížeči obrázků a ověřte kvalitu. + +## Krok 6: Běžné varianty a řešení okrajových případů + +| Situace | Co upravit | Důvod | +|-----------|----------------|--------| +| **Velké HTML stránky** | Nastavte `ImageRenderingOptions.Width` / `Height` nebo použijte `PageSize` pro kontrolu rozměrů výstupu | Zabrání přetečení paměti a zajistí, že PNG bude pasovat do vašeho UI | +| **Na Linuxu chybí font** | Nainstalujte požadované fonty na hostiteli (`apt-get install fonts‑arial` nebo použijte vlastní soubor fontu) a nasměrujte Aspose na něj pomocí `FontSettings` | Bez fontu přejde Aspose na generický, což mění vzhled | +| **Potřebné průhledné pozadí** | Nastavte `imgOptions.BackgroundColor = Color.Transparent` | Užitečné při vkládání PNG do jiných grafických prvků | +| **Dávková konverze** | Procházejte seznam HTML řetězců nebo cest k souborům, opakovaně používající stejný objekt `ImageRenderingOptions` | Zlepšuje výkon a udržuje nastavení vykreslování konzistentní | + +## Pro tip: cachování možností vykreslování + +Vytváření nového objektu `ImageRenderingOptions` pro každou konverzi přidává režii. Deklarujte statickou instanci, pokud zpracováváte mnoho HTML úryvků ve službě: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Znovu použijte `SharedOptions` napříč voláními, aby byl CPU zatížení nízké. + +## Často kladené otázky + +**Q: Funguje to s .NET Core na macOS?** +A: Ano. Aspose.HTML je plně multiplatformní. Ujistěte se, že jsou nainstalovány požadované fonty, a že výstupní adresář je zapisovatelný. + +**Q: Můžu renderovat do JPEG místo PNG?** +A: Nahraďte `RenderToImage("output.png", imgOptions)` za `RenderToImage("output.jpg", imgOptions)`. Můžete také nastavit `imgOptions.ImageFormat = ImageFormat.Jpeg` pro jemnější kontrolu kvality. + +**Q: Jak vložit externí CSS soubory?** +A: Načtěte obsah CSS do řetězce a spojte jej, nebo odkažte na vzdálený stylopis v `` tagu. Aspose automaticky řeší `` tagy, když je dokument načten z URL. + +## Závěr + +Nyní víte, **jak použít Aspose** k **render HTML to PNG** (nebo jakýkoli jiný rastrový formát) s nastavením vysoké kvality. Tutoriál pokryl instalaci Aspose.HTML, konfiguraci antialiasingu a text hintingu, vkládání CSS, načítání HTML a nakonec **saving HTML as PNG**. Dodržením kroků můžete spolehlivě **convert HTML to PNG** v jakékoli .NET aplikaci, ať už běží na Windows, Linuxu nebo macOS. + +### Další kroky + +* Prozkoumejte další výstupní formáty, jako **render html as image** JPEG nebo BMP změnou přípony souboru. +* Kombinujte tento přístup s **Aspose.PDF** pro vložení PNG do PDF zprávy. +* Experimentujte s `ImageRenderingOptions.DpiX` a `DpiY` pro vysoce rozlišené miniatury. + +Neváhejte přizpůsobit kód pro dávkové zpracování, dynamické generování HTML nebo integraci do webové služby, která na vyžádání vrací PNG náhledy. Šťastné vykreslování! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vašich projektech. + +- [Jak použít Aspose k vykreslení HTML do PNG – krok za krokem](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Jak renderovat HTML do PNG s Aspose – kompletní průvodce](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 d437dd374d..ae107c99cd 100644 --- a/html/dutch/net/html-extensions-and-conversions/_index.md +++ b/html/dutch/net/html-extensions-and-conversions/_index.md @@ -106,12 +106,12 @@ Leer hoe u PDF's genereert vanuit HTML met Aspose in een duidelijke stap‑voor ### [HTML opslaan als ZIP – Complete gids](./save-html-as-zip-in-c-complete-guide/) ### [HTML opslaan naar ZIP in C# – Volledig In‑Memory voorbeeld](./save-html-to-zip-in-c-complete-in-memory-example/) -Leer hoe u HTML-inhoud in het geheugen comprimeert en opslaat als ZIP-bestand met Aspose.HTML voor .NET in C#. +Leer hoe u HTML-inhoud in het geheugen comprimeert en opslaat als ZIP‑bestand met Aspose.HTML voor .NET in C#. ### [Aspose HTML Opslagopties: HTML opslaan naar stream in C#](./aspose-html-save-options-save-html-to-stream-in-c/) Leer hoe u met Aspose.HTML HTML-documenten direct naar een stream opslaat in C# met behulp van Save Options. ### [Aangepaste resourcehandler in C# – Converteer HTML naar ZIP-archief vanuit geheugen](./custom-resource-handler-in-c-convert-html-to-zip-archive-fro/) -Leer hoe u met een aangepaste resourcehandler HTML in het geheugen omzet naar een ZIP-archief met C# en Aspose.HTML voor .NET. +Leer hoe u met een aangepaste resourcehandler HTML in het geheugen omzet naar een ZIP‑archief met C# en Aspose.HTML voor .NET. ### [Aangepaste resourcehandler in C# – Converteer HTML naar ZIP-tutorial](./custom-resource-handler-in-c-convert-html-to-zip-tutorial/) Leer hoe u een aangepaste resourcehandler implementeert om HTML naar een ZIP‑archief te converteren met Aspose.HTML voor .NET. ### [Converteer HTML naar PDF met Aspose.HTML – Volledige stapsgewijze handleiding](./convert-html-to-pdf-with-aspose-html-full-step-by-step-guide/) @@ -123,17 +123,20 @@ Leer hoe u HTML naar ZIP converteert in C# met Aspose.HTML. Volg onze stap‑voo ### [Hoe HTML te zippen in C# – Complete stapsgewijze handleiding](./how-to-zip-html-in-c-complete-step-by-step-guide/) Leer hoe u HTML-bestanden comprimeert tot een ZIP‑archief met C# en Aspose.HTML. Volg de volledige stap‑voor‑stap‑handleiding. ### [HTML opslaan als ZIP in C# – Complete stapsgewijze handleiding](./save-html-as-zip-in-c-complete-step-by-step-guide/) -Leer hoe u HTML opslaat als ZIP-bestand in C# met Aspose.HTML. Volg onze stapsgewijze handleiding voor eenvoudige implementatie. +Leer hoe u HTML opslaat als ZIP‑bestand in C# met Aspose.HTML. Volg onze stapsgewijze handleiding voor eenvoudige implementatie. ### [HTML opslaan als ZIP in C# – Complete gids](./save-html-to-zip-in-c-complete-guide/) -Leer hoe u HTML naar een ZIP-bestand opslaat met een volledige C#-handleiding en Aspose.HTML voor .NET. +Leer hoe u HTML naar een ZIP‑bestand opslaat met een volledige C#‑handleiding en Aspose.HTML voor .NET. ### [Enkel bestand HTML – Een webpagina opslaan als één HTML-bestand in C#](./single-file-html-save-a-web-page-as-one-html-file-in-c/) ### [Hoe handler te gebruiken in Aspose.HTML – HTML laden, opslaan als ZIP](./how-to-use-handler-in-aspose-html-load-html-save-as-zip/) -Leer hoe u een handler gebruikt om HTML te laden en vervolgens op te slaan als ZIP-bestand met Aspose.HTML voor .NET. +Leer hoe u een handler gebruikt om HTML te laden en vervolgens op te slaan als ZIP‑bestand met Aspose.HTML voor .NET. ### [HTML-document maken en opslaan als zip – Complete C#-gids](./create-html-document-and-save-as-zip-complete-c-guide/) Leer hoe u een HTML-document maakt en dit als zip‑bestand opslaat met een volledige C#‑stappenplan. ### [PDF maken van HTML – Complete gids met Aspose.HTML](./create-pdf-from-html-complete-guide-with-aspose-html/) Leer hoe u PDF's genereert vanuit HTML met Aspose.HTML in een volledige stap‑voor‑stap gids. +### [HTML opslaan als zip met Aspose.HTML en afbeeldingen opnemen](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Leer hoe u HTML opslaat als zip‑bestand inclusief afbeeldingen met Aspose.HTML. + ## Conclusie Concluderend zijn HTML-extensies en conversies essentiële elementen van moderne webontwikkeling. Aspose.HTML voor .NET vereenvoudigt het proces en maakt het toegankelijk voor ontwikkelaars van alle niveaus. Door onze tutorials te volgen, bent u goed op weg om een bekwame webontwikkelaar te worden met een brede vaardighedenset. diff --git a/html/dutch/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/dutch/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..d46a00b066 --- /dev/null +++ b/html/dutch/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,343 @@ +--- +category: general +date: 2026-10-02 +description: Leer hoe je HTML als zip kunt opslaan met Aspose.HTML in C#. Deze gids + laat ook zien hoe je HTML met afbeeldingen in één enkel archief kunt opslaan. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: nl +lastmod: 2026-10-02 +og_description: Sla HTML op als zip met Aspose.HTML in C#. Volg deze volledige tutorial + om te leren hoe je HTML met afbeeldingen in één archief opslaat. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: HTML opslaan als zip met Aspose.HTML – stapsgewijze C#‑handleiding +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Hoe HTML opslaan als zip met Aspose.HTML en afbeeldingen opnemen +url: /nl/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe HTML opslaan als zip met Aspose.HTML en afbeeldingen opnemen + +Als je **HTML als zip wilt opslaan** voor eenvoudige distributie, laat deze tutorial je de exacte stappen zien met Aspose.HTML voor .NET. Of je nu een statische pagina, een e‑mailtemplate of een rapport met afbeeldingen exporteert, je ziet hoe je HTML, CSS en afbeeldingsbestanden in één ZIP‑archief kunt bundelen zonder tijdelijke bestanden op schijf te schrijven. + +Naast het hoofddoel beantwoorden we ook de veelgestelde vervolg‑vraag **hoe HTML met afbeeldingen op te slaan** zodat het resulterende archief door elke browser kan worden geopend zonder ontbrekende bronnen. + +Aan het einde van deze gids heb je een herbruikbare `ResourceHandler`‑implementatie, een compleet C#‑programma dat `output.zip` produceert, en praktische tips voor het omgaan met grote afbeeldingen of aangepaste mapstructuren. + +## Vereisten + +- .NET 6.0 of later (de API werkt ook met .NET Framework 4.6+) +- Aspose.HTML voor .NET NuGet‑pakket (`Aspose.Html`) +- Basiskennis van C# en streams +- Visual Studio 2022 of een andere IDE die .NET‑ontwikkeling ondersteunt + +> **Pro tip:** Installeer het pakket via de CLI om je projectbestand schoon te houden: +> `dotnet add package Aspose.Html` + +## Stap 1: Begrijp het outputmodel van Aspose.HTML + +Wanneer Aspose.HTML een document opslaat, behandelt het elke externe bron (CSS‑bestanden, afbeeldingen, lettertypen, enz.) als een afzonderlijke **resource**. Standaard schrijft de bibliotheek die bronnen naar het bestandssysteem. Om de bestemming te bepalen, lever je een aangepaste `ResourceHandler`. De handler ontvangt een `Resource`‑object en moet een beschrijfbare `Stream` teruggeven. Aspose.HTML schrijft vervolgens de resource‑gegevens naar die stream. + +Met een aangepaste handler kun je: + +- Bronnen direct naar een `MemoryStream` schrijven die later een ZIP‑item wordt +- Bronnen opslaan in een database, cloud‑opslag of een ander medium +- Bestandsnamen, compressieniveaus of maphiërarchieën aanpassen + +## Stap 2: Maak een `ResourceHandler` die naar een ZIP‑archief schrijft + +Hieronder staat een volledig functionele handler die een `System.IO.Compression.ZipArchive` in het geheugen opbouwt. Elke resource wordt toegevoegd als een nieuw item waarvan de naam het oorspronkelijke URL‑pad weerspiegelt, zodat de browser relatieve links kan oplossen wanneer de ZIP wordt uitgepakt. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Waarom deze aanpak werkt + +- **In‑memory bewerking**: Er worden geen tijdelijke bestanden op schijf aangemaakt, wat ideaal is voor webservices of sandbox‑omgevingen. +- **Behoudt maphiërarchie**: Door de originele resource‑URI te gebruiken, blijven relatieve verwijzingen geldig na extractie. +- **Uitbreidbaar**: Je kunt `MemoryStream` vervangen door een `FileStream` om direct naar een bestand te schrijven, of door een netwerkstream voor cloud‑opslag. + +## Stap 3: Laad of maak het HTML‑document + +Voor demonstratie maken we een eenvoudige HTML‑string die naar een externe afbeelding verwijst. In een echt project zou je HTML laden vanuit een bestand, een database of een HTTP‑respons. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Opmerking:** Als je een fysiek HTML‑bestand hebt, gebruik dan `new HTMLDocument("path/to/file.html")` in plaats daarvan. + +## Stap 4: Koppel de handler aan `SaveOptions` en sla de ZIP op + +Nu verbinden we de `ZipResourceHandler` met `SaveOptions.OutputStorage`. Wanneer `document.Save` wordt uitgevoerd, roept Aspose.HTML `HandleResource` aan voor elke resource, en vult de handler het ZIP‑archief. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Verwacht resultaat + +- `output.zip` bevat: + - `index.html` (het hoofd‑HTML‑bestand) + - `images/logo.png` (de afbeelding die in de markup wordt gebruikt) + - Eventuele extra CSS‑ of lettertypebestanden die automatisch door Aspose.HTML worden gedetecteerd + +Wanneer je het archief uitpakt en `index.html` in een browser opent, wordt de afbeelding correct weergegeven — een demonstratie van **hoe HTML met afbeeldingen op te slaan** binnen een ZIP. + +## Stap 5: Verifieer het archief en los veelvoorkomende problemen op + +### Snel‑verificatiescript + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Het uitvoeren van het script zou `index.html` en `images/logo.png` moeten weergeven. Als een verwachte resource ontbreekt: + +- **Controleer de afbeelding‑URL**: Deze moet bereikbaar zijn vanuit het HTML‑document. Relatieve paden werken het beste. +- **Zorg dat het resource‑type wordt ondersteund**: Aspose.HTML verwerkt gangbare webformaten (PNG, JPEG, GIF, CSS, JS). Ongebruikelijke formaten moeten handmatig worden toegevoegd. +- **Bevestig dat `HandleResource` wordt aangeroepen**: Voeg een `Console.WriteLine(resource.Uri)` toe binnen `HandleResource` om te debuggen. + +## Stap 6: Geavanceerde variaties + +### 6.1 Direct naar een bestand opslaan zonder tussenliggende byte‑array + +Als geheugenverbruik een zorg is voor zeer grote documenten, vervang dan `MemoryStream` door een `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Gebruik het vervolgens als: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Aanpassen van itemnamen + +Als je een platte structuur wilt (alle bestanden in de root), pas dan `entryName` aan: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Een manifest‑bestand toevoegen + +Soms verwachten downstream‑tools een `manifest.json`. Je kunt dit toevoegen na de hoofd‑save: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Veelvoorkomende valkuilen en hoe ze te vermijden + +| Valkuil | Waarom het gebeurt | Oplossing | +|---------|-------------------|----------| +| Afbeeldingen zijn kapot na extractie | Het afbeeldingpad in HTML komt niet overeen met de ZIP‑itemnaam. | Behoud het oorspronkelijke relatieve pad bij het maken van `ZipArchiveEntry`. | +| Grote afbeeldingen veroorzaken out‑of‑memory‑exceptions | Het gebruik van `MemoryStream` voor zeer grote bestanden kan de geheugenlimiet van het proces overschrijden. | Schakel over naar een `FileStream`‑gebaseerde handler (zie 6.1). | +| CSS‑URL’s ontbreken | Externe CSS‑bestanden die via `@import` worden aangeroepen, worden niet automatisch gedetecteerd. | Voeg die CSS‑bestanden handmatig toe aan de ZIP of embed ze inline vóór het opslaan. | +| Unicode‑tekens worden vervormd | De standaardcodering kan verschillen tussen de HTML‑bron en de stream. | Zorg dat de HTML‑string UTF‑8 is; Aspose.HTML respecteert de charset van het document. | + +## Volledig werkend voorbeeld (klaar om te kopiëren) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## Wat moet je hierna leren? + + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat complete werkende code‑voorbeelden met stap‑voor‑stap‑uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [hoe handler gebruiken in Aspose.HTML – HTML laden, opslaan als ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Hoe HTML opslaan in C# – Aangepaste resource‑handlers & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [HTML renderen naar PNG en opslaan in ZIP met C# – Complete gids](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 a4efba8841..405b842e18 100644 --- a/html/dutch/net/rendering-html-documents/_index.md +++ b/html/dutch/net/rendering-html-documents/_index.md @@ -89,7 +89,10 @@ Leer hoe u HTML naar PNG kunt renderen in C# met Aspose.HTML voor .NET in deze s Leer hoe u een HTML-document in C# maakt en rendert naar PNG met vet en cursief lettertype. ### [Hoe Aspose te gebruiken om HTML naar PNG te renderen in C#](./how-to-use-aspose-to-render-html-to-png-in-c/) -Leer hoe u Aspose gebruikt om HTML naar PNG te renderen in C# met een stapsgewijze tutorial. +Leer hoe u met Aspose.HTML HTML naar PNG kunt renderen in C# met een duidelijke stap‑voor‑stap handleiding. + +### [Hoe Aspose te gebruiken om HTML naar PNG‑afbeelding te renderen in C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Leer stap voor stap hoe u met Aspose.HTML HTML rendert naar een PNG‑afbeelding in C#. ### [HTML renderen naar PNG en opslaan in ZIP met C# – Complete gids](./render-html-to-png-and-save-to-zip-with-c-complete-guide/) Leer stap voor stap hoe u HTML naar PNG converteert en de resultaten in een ZIP‑archief opslaat met C# en Aspose.HTML. diff --git a/html/dutch/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/dutch/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..5aba56f8bb --- /dev/null +++ b/html/dutch/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-10-02 +description: Hoe Aspose te gebruiken om HTML snel naar PNG-afbeelding te renderen + – leer HTML naar PNG te converteren met anti‑aliasing en tekst‑hinting. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: nl +lastmod: 2026-10-02 +og_description: Hoe gebruik je Aspose om HTML te renderen naar een PNG‑afbeelding. + Volg deze volledige tutorial om HTML naar PNG te converteren met hoogwaardige rendering + in C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Hoe je Aspose gebruikt om HTML naar PNG-afbeelding te renderen – stapsgewijze + handleiding +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Hoe Aspose te gebruiken om HTML naar PNG-afbeelding te renderen in C# +url: /nl/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe Aspose te gebruiken om HTML te renderen naar PNG-afbeelding in C# + +**Hoe Aspose te gebruiken om HTML te renderen naar PNG-afbeelding** is een veelvoorkomende behoefte wanneer je een bitmap‑preview van een webpagina, een e‑mail‑miniatuur of een PDF‑vriendelijke snapshot nodig hebt. Deze tutorial laat je een complete, kant‑klaar oplossing zien die **render html to image** met anti‑aliasing en tekst‑hinting, zodat het resultaat scherp uitziet op elk platform. + +Je leert hoe je **HTML naar PNG kunt converteren**, renderopties kunt configureren en typische valkuilen kunt afhandelen, zoals Linux‑lettertype‑rendering en bestands‑systeem‑rechten. Er zijn geen externe tools nodig—alleen de Aspose.HTML for .NET‑bibliotheek en een paar regels C#. + +## Vereisten + +* .NET 6.0 SDK of later geïnstalleerd +* Visual Studio 2022 (of een andere C#‑IDE) +* Een NuGet‑referentie naar **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Basiskennis van C#‑syntaxis + +Deze vereisten zijn lichtgewicht; de tutorial werkt op Windows, Linux en macOS omdat Aspose.HTML cross‑platform is. + +## Stap 1: Installeer Aspose.HTML en maak een nieuw console‑project + +Open een terminal of de Package Manager Console en voer uit: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Het maken van een dedicated project isoleert de afhankelijkheden en maakt het eenvoudig om het voorbeeld uit te voeren met `dotnet run`. + +## Stap 2: Stel afbeeldings‑renderopties in (anti‑aliasing en tekst‑hinting) + +Anti‑aliasing maakt randen gladder, terwijl tekst‑hinting de duidelijkheid van glyphs verbetert, vooral op Linux waar lettertype‑rasterisatie verschilt van Windows. De `ImageRenderingOptions`‑klasse stelt je in staat beide functies in te schakelen: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Waarom dit belangrijk is:** Zonder anti‑aliasing zien diagonale lijnen en krommen er gekarteld uit. Zonder tekst‑hinting kunnen kleine lettergroottes wazig worden, wat merkbaar is wanneer je **save html as png** voor miniaturen. + +## Stap 3: Definieer CSS voor consistente lettertypen en kop‑stijlen + +CSS direct in de HTML insluiten zorgt ervoor dat de gerenderde afbeelding overeenkomt met je ontwerpverwachtingen. In dit voorbeeld stellen we een basislettertype in en maken `

` cursief: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Je kunt de stylesheet uitbreiden met kleuren, marges of media‑queries. De CSS wordt geïnjecteerd in de ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Tip:** Als je **render html as image** van een externe pagina wilt, vervang dan de string‑constructor door `new HTMLDocument("https://example.com")`. Aspose downloadt de pagina, lost bronnen op en rendert de uiteindelijke lay-out. + +## Stap 5: Render het document naar een PNG‑bestand + +Nu roepen we `RenderToImage` aan, waarbij we het uitvoerpad en de opties die we eerder hebben geconfigureerd doorgeven: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +De gegenereerde `output.png` zal een scherpe weergave bevatten van het `

`‑element met cursieve opmaak, dankzij de anti‑aliasing‑ en hint‑instellingen. + +## Volledige programmalijst + +Kopieer de volgende code naar `Program.cs`. Deze compileert en draait direct: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Verwachte output + +Het uitvoeren van het programma maakt `output.png` aan in de projectmap. De afbeelding toont het woord **Sample** in cursief Arial, gerenderd met gladde randen en duidelijke tekst. Open het bestand met een willekeurige afbeeldingsviewer om de kwaliteit te verifiëren. + +## Stap 6: Veelvoorkomende variaties en edge‑case handling + +| Situatie | Aan te passen | Reden | +|-----------|----------------|--------| +| **Grote HTML‑pagina's** | Stel `ImageRenderingOptions.Width` / `Height` in of gebruik `PageSize` om de uitvoerafmetingen te regelen | Voorkomt geheugen‑overbelasting en zorgt ervoor dat de PNG in je UI past | +| **Linux‑lettertype ontbreekt** | Installeer de vereiste lettertypen op de host (`apt-get install fonts‑arial` of gebruik een aangepast lettertype‑bestand) en wijs Aspose ernaar via `FontSettings` | Zonder het lettertype valt Aspose terug op een generiek lettertype, waardoor het uiterlijk verandert | +| **Transparante achtergrond nodig** | Stel `imgOptions.BackgroundColor = Color.Transparent` in | Handig bij het embedden van de PNG in andere graphics | +| **Batch‑conversie** | Loop over een lijst van HTML‑strings of bestandspaden, en hergebruik hetzelfde `ImageRenderingOptions`‑object | Verbeterde prestaties en houdt renderinstellingen consistent | + +## Pro‑tip: renderopties cachen + +Het aanmaken van een nieuw `ImageRenderingOptions`‑object voor elke conversie voegt overhead toe. Declareer een statische instantie als je veel HTML‑fragmenten verwerkt in een service: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Herbruik `SharedOptions` tussen oproepen om het CPU‑gebruik laag te houden. + +## Veelgestelde vragen + +**Q: Werkt dit met .NET Core op macOS?** +A: Ja. Aspose.HTML is volledig cross‑platform. Zorg ervoor dat de vereiste lettertypen geïnstalleerd zijn en dat de uitvoermap beschrijfbaar is. + +**Q: Kan ik renderen naar JPEG in plaats van PNG?** +A: Vervang `RenderToImage("output.png", imgOptions)` door `RenderToImage("output.jpg", imgOptions)`. Je kunt ook `imgOptions.ImageFormat = ImageFormat.Jpeg` instellen voor fijnere controle over de kwaliteit. + +**Q: Hoe embed ik externe CSS‑bestanden?** +A: Laad de CSS‑inhoud in een string en concateneer deze, of verwijs naar een externe stylesheet in de ``‑tag. Aspose lost ``‑tags automatisch op wanneer het document wordt geladen vanaf een URL. + +## Conclusie + +Je weet nu **hoe je Aspose** kunt **gebruiken om HTML te renderen naar PNG** (of een ander rasterformaat) met instellingen van hoge kwaliteit. De tutorial besprak het installeren van Aspose.HTML, het configureren van anti‑aliasing en tekst‑hinting, het injecteren van CSS, het laden van HTML, en uiteindelijk **HTML opslaan als PNG**. Door de stappen te volgen kun je betrouwbaar **HTML naar PNG converteren** in elke .NET‑applicatie, ongeacht of deze draait op Windows, Linux of macOS. + +### Volgende stappen + +* Verken andere uitvoerformaten zoals **html als afbeelding renderen** JPEG of BMP door de bestandsextensie te wijzigen. +* Combineer deze aanpak met **Aspose.PDF** om de PNG in een PDF‑rapport te embedden. +* Experimenteer met `ImageRenderingOptions.DpiX` en `DpiY` voor hoge‑resolutie miniaturen. + +Voel je vrij om de code aan te passen voor batchverwerking, dynamische HTML‑generatie, of integratie in een webservice die PNG‑previews op aanvraag retourneert. Veel renderplezier! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe Aspose te gebruiken om HTML te renderen naar PNG – Stapsgewijze gids](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Hoe HTML te renderen naar PNG met Aspose – Complete gids](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html naar afbeelding tutorial – HTML renderen naar PNG met Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 00689259b5..b2c7aa060f 100644 --- a/html/english/net/html-extensions-and-conversions/_index.md +++ b/html/english/net/html-extensions-and-conversions/_index.md @@ -89,6 +89,8 @@ Learn how to zip HTML files using a custom resource handler in C# with Aspose.HT 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/) Learn how to save HTML files as a ZIP archive using Aspose.HTML for .NET with a complete C# example. +### [How to save HTML as zip with Aspose.HTML and include images](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Learn how to save an HTML document as a ZIP archive including its images using Aspose.HTML for .NET. ### [Custom Resource Handler in C# – Convert HTML to ZIP Archive from Memory](./custom-resource-handler-in-c-convert-html-to-zip-archive-fro/) Learn how to implement a custom resource handler in C# to convert HTML to a ZIP archive directly from memory using Aspose.HTML. ### [How to Zip HTML in C# – Load HTML & Use Custom Handler](./how-to-zip-html-in-c-load-html-use-custom-handler/) diff --git a/html/english/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/english/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..33f69f3295 --- /dev/null +++ b/html/english/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,343 @@ +--- +category: general +date: 2026-10-02 +description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: en +lastmod: 2026-10-02 +og_description: Save HTML as zip using Aspose.HTML in C#. Follow this complete tutorial + to learn how to save HTML with images into a single archive. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Save HTML as zip with Aspose.HTML – step‑by‑step C# guide +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: How to save HTML as zip with Aspose.HTML and include images +url: /net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to save HTML as zip with Aspose.HTML and include images + +If you need to **save HTML as zip** for easy distribution, this tutorial shows you the exact steps using Aspose.HTML for .NET. Whether you are exporting a static page, an email template, or a report that contains images, you’ll see how to bundle the HTML, CSS, and image files into a single ZIP archive without writing temporary files to disk. + +In addition to the primary goal, we’ll also answer the common follow‑up question **how to save HTML with images** so that the resulting archive can be opened by any browser without missing resources. + +By the end of this guide you will have a reusable `ResourceHandler` implementation, a complete C# program that produces `output.zip`, and practical tips for handling large images or custom folder structures. + +## Prerequisites + +- .NET 6.0 or later (the API works with .NET Framework 4.6+ as well) +- Aspose.HTML for .NET NuGet package (`Aspose.Html`) +- Basic knowledge of C# and streams +- Visual Studio 2022 or any IDE that supports .NET development + +> **Pro tip:** Install the package via the CLI to keep your project file clean: +> `dotnet add package Aspose.Html` + +## Step 1: Understand Aspose.HTML’s output model + +When Aspose.HTML saves a document, it treats every external resource (CSS files, images, fonts, etc.) as a separate **resource**. By default the library writes those resources to the file system. To control the destination you provide a custom `ResourceHandler`. The handler receives a `Resource` object and must return a writable `Stream`. Aspose.HTML then writes the resource data into that stream. + +Using a custom handler lets you: + +- Write resources directly into a `MemoryStream` that later becomes a ZIP entry +- Store resources in a database, cloud storage, or any other medium +- Adjust file names, compression levels, or folder hierarchies + +## Step 2: Create a `ResourceHandler` that writes into a ZIP archive + +Below is a fully functional handler that builds a `System.IO.Compression.ZipArchive` in memory. Each resource is added as a new entry whose name mirrors the original URL path, ensuring the browser can resolve relative links when the ZIP is extracted. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Why this approach works + +- **In‑memory operation**: No temporary files are created on disk, which is ideal for web services or sandboxed environments. +- **Preserves folder hierarchy**: By using the original resource URI, relative references remain valid after extraction. +- **Extensible**: You can replace `MemoryStream` with a `FileStream` to write directly to a file, or with a network stream for cloud storage. + +## Step 3: Load or create the HTML document + +For demonstration we’ll create a simple HTML string that references an external image. In a real project you would load HTML from a file, a database, or an HTTP response. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Note:** If you have a physical HTML file, use `new HTMLDocument("path/to/file.html")` instead. + +## Step 4: Wire the handler to `SaveOptions` and save the ZIP + +Now we connect the `ZipResourceHandler` to `SaveOptions.OutputStorage`. When `document.Save` runs, Aspose.HTML will invoke `HandleResource` for each resource, and the handler will populate the ZIP archive. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Expected result + +- `output.zip` contains: + - `index.html` (the main HTML file) + - `images/logo.png` (the image referenced in the markup) + - Any additional CSS or font files automatically detected by Aspose.HTML + +When you extract the archive and open `index.html` in a browser, the image displays correctly—demonstrating **how to save HTML with images** inside a ZIP. + +## Step 5: Verify the archive and troubleshoot common issues + +### Quick verification script + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Running the script should list `index.html` and `images/logo.png`. If an expected resource is missing: + +- **Check the image URL**: It must be reachable from the HTML document. Relative paths work best. +- **Ensure the resource type is supported**: Aspose.HTML handles common web formats (PNG, JPEG, GIF, CSS, JS). Unusual formats may require manual addition. +- **Confirm `HandleResource` is called**: Add a `Console.WriteLine(resource.Uri)` inside `HandleResource` to debug. + +## Step 6: Advanced variations + +### 6.1 Saving directly to a file without an intermediate byte array + +If memory usage is a concern for very large documents, replace `MemoryStream` with a `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Then use it like: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Customizing entry names + +If you prefer a flat structure (all files at the root), adjust `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Adding a manifest file + +Sometimes downstream tools expect a `manifest.json`. You can add it after the main save: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Common pitfalls and how to avoid them + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| Images appear broken after extraction | The image path inside HTML does not match the ZIP entry name. | Preserve the original relative path when creating `ZipArchiveEntry`. | +| Large images cause out‑of‑memory exceptions | Using `MemoryStream` for very large files can exceed the process’s memory limit. | Switch to a `FileStream`‑based handler (see 6.1). | +| CSS URLs are missing | External CSS files referenced via `@import` are not detected automatically. | Manually add those CSS files to the ZIP or embed them inline before saving. | +| Unicode characters become garbled | The default encoding may differ between the HTML source and the stream. | Ensure the HTML string is UTF‑8; Aspose.HTML respects the document’s charset. | + +## Full working example (copy‑paste ready) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [how to use handler in Aspose.HTML – Load HTML, Save as ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [How to Save HTML in C# – Custom Resource Handlers & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Render HTML to PNG and Save to ZIP with C# – Complete Guide](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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/how-to-save-html-as-zip-with-aspose-html-and-include-images/og-image.png b/html/english/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/og-image.png new file mode 100644 index 0000000000..266b665cb3 Binary files /dev/null and b/html/english/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/og-image.png differ diff --git a/html/english/net/rendering-html-documents/_index.md b/html/english/net/rendering-html-documents/_index.md index 68afbd0d8d..cc70d0e7a2 100644 --- a/html/english/net/rendering-html-documents/_index.md +++ b/html/english/net/rendering-html-documents/_index.md @@ -48,6 +48,8 @@ Step-by-step guide to rendering HTML to PNG using Aspose.HTML for .NET, covering 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/) Step by step guide to render HTML to PNG using Aspose.HTML for .NET. Learn the process, code examples, and best practices. +### [How to use Aspose to render HTML to PNG image in C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Learn how to render HTML pages to PNG images using Aspose.HTML in C#. ### [How to render HTML as PNG in C# – Step‑by‑Step Guide](./how-to-render-html-as-png-in-c-step-by-step-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 Render HTML to PNG with Aspose – Complete Guide](./how-to-render-html-to-png-with-aspose-complete-guide/) diff --git a/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..ef9623661a --- /dev/null +++ b/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-10-02 +description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: en +lastmod: 2026-10-02 +og_description: How to use Aspose to render HTML to PNG image. Follow this complete + tutorial to convert HTML to PNG with high‑quality rendering in C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: How to use Aspose to render HTML to PNG image – step‑by‑step guide +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: How to use Aspose to render HTML to PNG image in C# +url: /net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to use Aspose to render HTML to PNG image in C# + +**How to use Aspose to render HTML to PNG image** is a common requirement when you need a bitmap preview of a web page, an email thumbnail, or a PDF‑friendly snapshot. This tutorial shows you a complete, ready‑to‑run solution that **render html to image** with anti‑aliasing and text hinting, so the result looks sharp on every platform. + +You’ll learn how to **convert HTML to PNG**, configure rendering options, and handle typical pitfalls such as Linux font rendering and file‑system permissions. No external tools are required—just the Aspose.HTML for .NET library and a few lines of C#. + +## Prerequisites + +Before you start, make sure you have: + +* .NET 6.0 SDK or later installed +* Visual Studio 2022 (or any C# IDE) +* A NuGet reference to **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Basic familiarity with C# syntax + +These prerequisites are lightweight; the tutorial works on Windows, Linux, and macOS because Aspose.HTML is cross‑platform. + +## Step 1: Install Aspose.HTML and create a new console project + +Open a terminal or the Package Manager Console and run: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Creating a dedicated project isolates the dependencies and makes it easy to run the sample with `dotnet run`. + +## Step 2: Set up image rendering options (anti‑aliasing and text hinting) + +Antialiasing smooths edges, while text hinting improves glyph clarity, especially on Linux where font rasterization differs from Windows. The `ImageRenderingOptions` class lets you enable both features: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Why this matters:** Without antialiasing, diagonal lines and curves look jagged. Without text hinting, small font sizes can become blurry, which is noticeable when you **save html as png** for thumbnails. + +## Step 3: Define CSS for consistent fonts and heading styles + +Embedding CSS directly in the HTML ensures the rendered image matches your design expectations. In this example we set a base font and make `

` italic: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +You can extend the stylesheet with colors, margins, or media queries. The CSS is injected into the ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Tip:** If you need to **render html as image** from a remote page, replace the string constructor with `new HTMLDocument("https://example.com")`. Aspose will download the page, resolve resources, and render the final layout. + +## Step 5: Render the document to a PNG file + +Now we call `RenderToImage`, passing the output path and the options we configured earlier: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +The generated `output.png` will contain a crisp rendering of the `

` element with italic styling, thanks to the anti‑aliasing and hinting settings. + +## Full program listing + +Copy the following code into `Program.cs`. It compiles and runs as‑is: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Expected output + +Running the program creates `output.png` in the project folder. The image shows the word **Sample** in italic Arial, rendered with smooth edges and clear text. Open the file with any image viewer to verify the quality. + +## Step 6: Common variations and edge‑case handling + +| Situation | What to adjust | Reason | +|-----------|----------------|--------| +| **Large HTML pages** | Set `ImageRenderingOptions.Width` / `Height` or use `PageSize` to control output dimensions | Prevents memory blow‑up and ensures the PNG fits your UI | +| **Linux font missing** | Install the required fonts on the host (`apt-get install fonts‑arial` or use a custom font file) and point Aspose to it via `FontSettings` | Without the font, Aspose falls back to a generic one, altering the appearance | +| **Transparent background needed** | Set `imgOptions.BackgroundColor = Color.Transparent` | Useful when embedding the PNG into other graphics | +| **Batch conversion** | Loop over a list of HTML strings or file paths, reusing the same `ImageRenderingOptions` object | Improves performance and keeps rendering settings consistent | + +## Pro tip: caching rendering options + +Creating a new `ImageRenderingOptions` object for each conversion adds overhead. Declare a static instance if you process many HTML snippets in a service: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Reuse `SharedOptions` across calls to keep CPU usage low. + +## Frequently asked questions + +**Q: Does this work with .NET Core on macOS?** +A: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are installed, and the output directory is writable. + +**Q: Can I render to JPEG instead of PNG?** +A: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for finer control over quality. + +**Q: How do I embed external CSS files?** +A: Load the CSS content into a string and concatenate it, or reference a remote stylesheet in the `` tag. Aspose resolves `` tags automatically when the document is loaded from a URL. + +## Conclusion + +You now know **how to use Aspose** to **render HTML to PNG** (or any other raster format) with high‑quality settings. The tutorial covered installing Aspose.HTML, configuring anti‑aliasing and text hinting, injecting CSS, loading HTML, and finally **saving HTML as PNG**. By following the steps you can reliably **convert HTML to PNG** in any .NET application, whether it runs on Windows, Linux, or macOS. + +### Next steps + +* Explore other output formats such as **render html as image** JPEG or BMP by changing the file extension. +* Combine this approach with **Aspose.PDF** to embed the PNG into a PDF report. +* Experiment with `ImageRenderingOptions.DpiX` and `DpiY` for high‑resolution thumbnails. + +Feel free to adapt the code for batch processing, dynamic HTML generation, or integration into a web service that returns PNG previews on demand. Happy rendering! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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/how-to-use-aspose-to-render-html-to-png-image-in-c/og-image.png b/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/og-image.png new file mode 100644 index 0000000000..b7a93572eb Binary files /dev/null and b/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/og-image.png differ diff --git a/html/french/net/html-extensions-and-conversions/_index.md b/html/french/net/html-extensions-and-conversions/_index.md index ce3459a6b4..6a4e7f5e64 100644 --- a/html/french/net/html-extensions-and-conversions/_index.md +++ b/html/french/net/html-extensions-and-conversions/_index.md @@ -140,6 +140,15 @@ Apprenez à charger un document HTML et à l’enregistrer dans un fichier ZIP e ### [Créer un document HTML et l’enregistrer en zip – Guide complet C#](./create-html-document-and-save-as-zip-complete-c-guide/) Apprenez à créer un document HTML et à le compresser dans un fichier ZIP avec C# grâce à Aspose.HTML, guide complet pas à pas. +### [Enregistrer le HTML en ZIP en C# – Guide complet étape par étape](./save-html-as-zip-in-c-complete-step-by-step-guide/) +Apprenez à sauvegarder un document HTML dans une archive ZIP en C# avec Aspose.HTML, grâce à un guide détaillé pas à pas. + +### [Comment enregistrer le HTML en zip avec Aspose.HTML et inclure les images](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Apprenez à sauvegarder un document HTML en archive ZIP incluant les images avec Aspose.HTML en C#. + +### [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 En conclusion, les extensions et conversions HTML sont des éléments essentiels du développement Web moderne. Aspose.HTML pour .NET simplifie le processus et le rend accessible aux développeurs de tous niveaux. En suivant nos tutoriels, vous serez sur la bonne voie pour devenir un développeur Web compétent doté d'un large éventail de compétences. diff --git a/html/french/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/french/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..bf10d1e75d --- /dev/null +++ b/html/french/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,344 @@ +--- +category: general +date: 2026-10-02 +description: Apprenez à enregistrer du HTML au format zip en utilisant Aspose.HTML + en C#. Ce guide montre également comment enregistrer du HTML avec les images dans + une seule archive. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: fr +lastmod: 2026-10-02 +og_description: Enregistrez le HTML en zip avec Aspose.HTML en C#. Suivez ce tutoriel + complet pour apprendre à enregistrer le HTML avec les images dans une archive unique. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Enregistrer le HTML au format zip avec Aspose.HTML – guide C# étape par + étape +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Comment enregistrer du HTML au format zip avec Aspose.HTML et inclure les images +url: /fr/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment enregistrer du HTML en zip avec Aspose.HTML et inclure les images + +Si vous devez **enregistrer du HTML en zip** pour une distribution facile, ce tutoriel vous montre les étapes exactes en utilisant Aspose.HTML pour .NET. Que vous exportiez une page statique, un modèle d'e‑mail ou un rapport contenant des images, vous verrez comment regrouper les fichiers HTML, CSS et image dans une archive ZIP unique sans écrire de fichiers temporaires sur le disque. + +En plus de l'objectif principal, nous répondrons également à la question fréquente **comment enregistrer du HTML avec des images** afin que l'archive résultante puisse être ouverte par n'importe quel navigateur sans ressources manquantes. + +À la fin de ce guide, vous disposerez d'une implémentation réutilisable de `ResourceHandler`, d'un programme C# complet qui génère `output.zip`, ainsi que de conseils pratiques pour gérer de grandes images ou des structures de dossiers personnalisées. + +## Prérequis + +- .NET 6.0 ou ultérieur (l'API fonctionne également avec .NET Framework 4.6+) +- Package NuGet Aspose.HTML for .NET (`Aspose.Html`) +- Connaissances de base en C# et flux +- Visual Studio 2022 ou tout IDE supportant le développement .NET + +> **Astuce :** Installez le package via la CLI pour garder votre fichier de projet propre : +> `dotnet add package Aspose.Html` + +## Étape 1 : Comprendre le modèle de sortie d’Aspose.HTML + +Lorsque Aspose.HTML enregistre un document, il considère chaque ressource externe (fichiers CSS, images, polices, etc.) comme une **resource** distincte. Par défaut, la bibliothèque écrit ces ressources sur le système de fichiers. Pour contrôler la destination, vous fournissez un `ResourceHandler` personnalisé. Le gestionnaire reçoit un objet `Resource` et doit renvoyer un `Stream` en écriture. Aspose.HTML écrit alors les données de la ressource dans ce flux. + +Utiliser un gestionnaire personnalisé vous permet de : + +- Écrire les ressources directement dans un `MemoryStream` qui devient ensuite une entrée ZIP +- Stocker les ressources dans une base de données, un stockage cloud ou tout autre support +- Ajuster les noms de fichiers, les niveaux de compression ou les hiérarchies de dossiers + +## Étape 2 : Créer un `ResourceHandler` qui écrit dans une archive ZIP + +Voici un gestionnaire entièrement fonctionnel qui construit un `System.IO.Compression.ZipArchive` en mémoire. Chaque ressource est ajoutée comme une nouvelle entrée dont le nom reflète le chemin URL d'origine, garantissant que le navigateur puisse résoudre les liens relatifs lorsque le ZIP est extrait. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Pourquoi cette approche fonctionne + +- **Opération en mémoire** : Aucun fichier temporaire n’est créé sur le disque, ce qui est idéal pour les services web ou les environnements sandboxés. +- **Conserve la hiérarchie des dossiers** : En utilisant l’URI de la ressource d’origine, les références relatives restent valides après extraction. +- **Extensible** : Vous pouvez remplacer `MemoryStream` par un `FileStream` pour écrire directement dans un fichier, ou par un flux réseau pour le stockage cloud. + +## Étape 3 : Charger ou créer le document HTML + +Pour la démonstration, nous créerons une chaîne HTML simple qui référence une image externe. Dans un projet réel, vous chargeriez le HTML depuis un fichier, une base de données ou une réponse HTTP. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Remarque :** Si vous avez un fichier HTML physique, utilisez `new HTMLDocument("path/to/file.html")` à la place. + +## Étape 4 : Connecter le gestionnaire à `SaveOptions` et enregistrer le ZIP + +Nous connectons maintenant le `ZipResourceHandler` à `SaveOptions.OutputStorage`. Lorsque `document.Save` s’exécute, Aspose.HTML invoquera `HandleResource` pour chaque ressource, et le gestionnaire remplira l’archive ZIP. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Résultat attendu + +- `output.zip` contient : + - `index.html` (le fichier HTML principal) + - `images/logo.png` (l'image référencée dans le balisage) + - Tous les fichiers CSS ou de police supplémentaires détectés automatiquement par Aspose.HTML + +Lorsque vous extrayez l'archive et ouvrez `index.html` dans un navigateur, l'image s'affiche correctement—démontrant **comment enregistrer du HTML avec des images** à l'intérieur d'un ZIP. + +## Étape 5 : Vérifier l'archive et résoudre les problèmes courants + +### Script de vérification rapide + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Exécuter le script doit lister `index.html` et `images/logo.png`. Si une ressource attendue est manquante : + +- **Vérifiez l'URL de l'image** : Elle doit être accessible depuis le document HTML. Les chemins relatifs fonctionnent le mieux. +- **Assurez‑vous que le type de ressource est pris en charge** : Aspose.HTML gère les formats web courants (PNG, JPEG, GIF, CSS, JS). Les formats inhabituels peuvent nécessiter une addition manuelle. +- **Confirmez que `HandleResource` est appelé** : Ajoutez un `Console.WriteLine(resource.Uri)` à l'intérieur de `HandleResource` pour déboguer. + +## Étape 6 : Variantes avancées + +### 6.1 Enregistrement direct dans un fichier sans tableau d'octets intermédiaire + +Si l'utilisation de la mémoire est un problème pour des documents très volumineux, remplacez `MemoryStream` par un `FileStream` : + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Puis utilisez‑le ainsi : + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Personnaliser les noms des entrées + +Si vous préférez une structure plate (tous les fichiers à la racine), ajustez `entryName` : + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Ajouter un fichier manifest + +Parfois, les outils en aval attendent un `manifest.json`. Vous pouvez l’ajouter après l’enregistrement principal : + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Pièges courants et comment les éviter + +| Piège | Pourquoi cela se produit | Solution | +|-------|--------------------------|----------| +| Les images apparaissent cassées après extraction | Le chemin de l'image dans le HTML ne correspond pas au nom de l'entrée ZIP. | Conservez le chemin relatif d'origine lors de la création de `ZipArchiveEntry`. | +| Les grandes images provoquent des exceptions de dépassement de mémoire | L'utilisation de `MemoryStream` pour des fichiers très volumineux peut dépasser la limite de mémoire du processus. | Passez à un gestionnaire basé sur `FileStream` (voir 6.1). | +| Les URL CSS sont manquantes | Les fichiers CSS externes référencés via `@import` ne sont pas détectés automatiquement. | Ajoutez manuellement ces fichiers CSS au ZIP ou intégrez‑les en ligne avant l’enregistrement. | +| Les caractères Unicode deviennent corrompus | L'encodage par défaut peut différer entre la source HTML et le flux. | Assurez‑vous que la chaîne HTML est en UTF‑8 ; Aspose.HTML respecte le jeu de caractères du document. | + +## Exemple complet fonctionnel (prêt à copier‑coller) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s'appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités supplémentaires de l'API et à explorer des approches d'implémentation alternatives dans vos propres projets. + +- [comment utiliser le gestionnaire dans Aspose.HTML – Charger HTML, Enregistrer en ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Comment enregistrer du HTML en C# – Gestionnaires de ressources personnalisés & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Rendre le HTML en PNG et enregistrer en ZIP avec C# – Guide complet](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 9204ab2f94..19c466cf20 100644 --- a/html/french/net/rendering-html-documents/_index.md +++ b/html/french/net/rendering-html-documents/_index.md @@ -59,6 +59,9 @@ Apprenez à convertir du HTML en image en C# avec Aspose.HTML, étape par étape ### [Comment utiliser Aspose pour rendre du HTML au format PNG en C#](./how-to-use-aspose-to-render-html-to-png-in-c/) Apprenez à convertir du HTML en images PNG en C# avec Aspose.HTML, étape par étape. +### [Comment utiliser Aspose pour rendre du HTML en image PNG en C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Apprenez à convertir du HTML en image PNG avec Aspose.HTML en C# grâce à ce guide détaillé. + ### [Rendre EPUB en XPS dans .NET avec Aspose.HTML](./render-epub-as-xps/) Découvrez comment créer et restituer des documents HTML avec Aspose.HTML pour .NET dans ce didacticiel complet. Plongez dans le monde de la manipulation HTML, du scraping Web et bien plus encore. diff --git a/html/french/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/french/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..1679f85491 --- /dev/null +++ b/html/french/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-10-02 +description: Comment utiliser Aspose pour rendre rapidement du HTML en image PNG – + apprenez à convertir le HTML en PNG avec anti‑aliasing et hinting du texte. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: fr +lastmod: 2026-10-02 +og_description: Comment utiliser Aspose pour rendre du HTML en image PNG. Suivez ce + tutoriel complet pour convertir du HTML en PNG avec un rendu de haute qualité en + C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Comment utiliser Aspose pour rendre du HTML en image PNG – guide étape par + étape +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Comment utiliser Aspose pour rendre du HTML en image PNG en C# +url: /fr/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment utiliser Aspose pour rendre du HTML en image PNG en C# + +**Comment utiliser Aspose pour rendre du HTML en image PNG** est une exigence courante lorsque vous avez besoin d’un aperçu bitmap d’une page web, d’une vignette d’e‑mail ou d’une capture d’écran adaptée au PDF. Ce tutoriel vous montre une solution complète, prête à l’exécution qui **render html to image** avec anti‑aliasing et text hinting, de sorte que le résultat soit net sur chaque plateforme. + +Vous apprendrez comment **convertir HTML en PNG**, configurer les options de rendu et gérer les pièges typiques tels que le rendu des polices sous Linux et les permissions du système de fichiers. Aucun outil externe n’est requis — seulement la bibliothèque Aspose.HTML pour .NET et quelques lignes de C#. + +## Prérequis + +Avant de commencer, assurez‑vous d’avoir : + +* .NET 6.0 SDK ou version ultérieure installé +* Visual Studio 2022 (ou tout IDE C#) +* Une référence NuGet à **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Une connaissance de base de la syntaxe C# + +Ces prérequis sont légers ; le tutoriel fonctionne sous Windows, Linux et macOS car Aspose.HTML est multiplateforme. + +## Étape 1 : Installer Aspose.HTML et créer un nouveau projet console + +Ouvrez un terminal ou la console du gestionnaire de packages et exécutez : + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Créer un projet dédié isole les dépendances et facilite l’exécution de l’exemple avec `dotnet run`. + +## Étape 2 : Configurer les options de rendu d’image (anti‑aliasing et text hinting) + +L’anti‑aliasing lisse les bords, tandis que le text hinting améliore la clarté des glyphes, surtout sous Linux où la rasterisation des polices diffère de Windows. La classe `ImageRenderingOptions` vous permet d’activer les deux fonctionnalités : + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Pourquoi c’est important :** Sans anti‑aliasing, les lignes diagonales et les courbes apparaissent dentelées. Sans text hinting, les petites tailles de police peuvent devenir floues, ce qui se remarque lorsque vous **save html as png** pour des vignettes. + +## Étape 3 : Définir le CSS pour des polices et des styles de titres cohérents + +Intégrer le CSS directement dans le HTML garantit que l’image rendue correspond à vos attentes de conception. Dans cet exemple, nous définissons une police de base et rendons `

` italique : + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Vous pouvez étendre la feuille de style avec des couleurs, des marges ou des media queries. Le CSS est injecté dans la balise ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Astuce :** Si vous devez **render html as image** depuis une page distante, remplacez le constructeur de chaîne par `new HTMLDocument("https://example.com")`. Aspose téléchargera la page, résoudra les ressources et rendra la mise en page finale. + +## Étape 5 : Rendre le document en fichier PNG + +Nous appelons maintenant `RenderToImage`, en passant le chemin de sortie et les options que nous avons configurées précédemment : + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +Le `output.png` généré contiendra un rendu net de l’élément `

` avec le style italique, grâce aux paramètres d’anti‑aliasing et de hinting. + +## Liste complète du programme + +Copiez le code suivant dans `Program.cs`. Il compile et s’exécute tel quel : + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Résultat attendu + +L’exécution du programme crée `output.png` dans le dossier du projet. L’image montre le mot **Sample** en Arial italique, rendu avec des bords lisses et un texte clair. Ouvrez le fichier avec n’importe quel visualiseur d’images pour vérifier la qualité. + +## Étape 6 : Variantes courantes et gestion des cas limites + +| Situation | Ce qu’il faut ajuster | Raison | +|-----------|-----------------------|--------| +| **Pages HTML volumineuses** | Définir `ImageRenderingOptions.Width` / `Height` ou utiliser `PageSize` pour contrôler les dimensions de sortie | Empêche une explosion de la mémoire et assure que le PNG s’adapte à votre UI | +| **Police manquante sous Linux** | Installer les polices requises sur l’hôte (`apt-get install fonts‑arial` ou utiliser un fichier de police personnalisé) et indiquer le chemin à Aspose via `FontSettings` | Sans la police, Aspose revient à une police générique, modifiant l’apparence | +| **Arrière‑plan transparent nécessaire** | Définir `imgOptions.BackgroundColor = Color.Transparent` | Utile lors de l’intégration du PNG dans d’autres graphiques | +| **Conversion par lots** | Parcourir une liste de chaînes HTML ou de chemins de fichiers, en réutilisant le même objet `ImageRenderingOptions` | Améliore les performances et maintient la cohérence des paramètres de rendu | + +## Astuce pro : mettre en cache les options de rendu + +Créer un nouvel objet `ImageRenderingOptions` pour chaque conversion ajoute une surcharge. Déclarez une instance statique si vous traitez de nombreux extraits HTML dans un service : + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Réutilisez `SharedOptions` entre les appels pour garder une faible utilisation CPU. + +## Questions fréquentes + +**Q : Cela fonctionne-t‑il avec .NET Core sur macOS ?** +R : Oui. Aspose.HTML est entièrement multiplateforme. Assurez‑vous que les polices requises sont installées et que le répertoire de sortie est accessible en écriture. + +**Q : Puis‑je rendre en JPEG au lieu de PNG ?** +R : Remplacez `RenderToImage("output.png", imgOptions)` par `RenderToImage("output.jpg", imgOptions)`. Vous pouvez également définir `imgOptions.ImageFormat = ImageFormat.Jpeg` pour un contrôle plus fin de la qualité. + +**Q : Comment intégrer des fichiers CSS externes ?** +R : Chargez le contenu CSS dans une chaîne et concaténez‑le, ou référencez une feuille de style distante dans la balise ``. Aspose résout automatiquement les balises `` lorsque le document est chargé depuis une URL. + +## Conclusion + +Vous savez maintenant **comment utiliser Aspose** pour **render HTML to PNG** (ou tout autre format raster) avec des paramètres de haute qualité. Le tutoriel a couvert l’installation d’Aspose.HTML, la configuration de l’anti‑aliasing et du text hinting, l’injection de CSS, le chargement du HTML, et enfin **saving HTML as PNG**. En suivant ces étapes, vous pouvez convertir de façon fiable **HTML to PNG** dans n’importe quelle application .NET, qu’elle s’exécute sous Windows, Linux ou macOS. + +### Prochaines étapes + +* Explorez d’autres formats de sortie tels que **render html as image** JPEG ou BMP en modifiant l’extension du fichier. +* Combinez cette approche avec **Aspose.PDF** pour intégrer le PNG dans un rapport PDF. +* Expérimentez `ImageRenderingOptions.DpiX` et `DpiY` pour des vignettes haute résolution. + +N’hésitez pas à adapter le code pour le traitement par lots, la génération dynamique de HTML ou l’intégration dans un service web qui renvoie des aperçus PNG à la demande. Bon rendu ! + + +## Que devez‑vous apprendre ensuite ? + + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource inclut des exemples de code complets avec des explications pas à pas pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 4cc3136df8..b35a8be271 100644 --- a/html/german/net/html-extensions-and-conversions/_index.md +++ b/html/german/net/html-extensions-and-conversions/_index.md @@ -83,27 +83,12 @@ Erfahren Sie, wie Sie mit Aspose.HTML für .NET PDFs direkt aus einer URL generi 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 erstellen und als ZIP speichern – Vollständige C#‑Anleitung](./create-html-document-and-save-as-zip-complete-c-guide/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET ein HTML-Dokument erzeugen und es als ZIP-Datei speichern – komplette Schritt‑für‑Schritt‑Anleitung. +### [HTML als ZIP speichern mit Aspose.HTML und Bilder einbinden](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Erfahren Sie, wie Sie HTML mit Aspose.HTML als ZIP‑Archiv speichern und dabei Bilder einbinden. +### [HTML‑Dokument erstellen und als ZIP speichern – Vollständige C#‑Anleitung](./create-html-document-and-save-as-zip-complete-c-guide/) +Erfahren Sie, wie Sie mit Aspose.HTML für .NET ein HTML‑Dokument erzeugen und es als ZIP‑Datei speichern – komplette Schritt‑für‑Schritt‑Anleitung. ### [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. -### [PDF aus HTML erstellen mit Aspose.HTML – Schritt‑für‑Schritt‑Anleitung](./create-pdf-from-html-with-aspose-html-step-by-step-guide/) -Erstellen Sie PDF aus HTML mit Aspose.HTML für .NET. Folgen Sie unserer Schritt‑für‑Schritt‑Anleitung und nutzen Sie die volle Leistungsfähigkeit. -### [PDF aus HTML mit Aspose in C# erstellen – Vollständiger Leitfaden](./create-pdf-from-html-with-aspose-in-c-full-guide/) -Erfahren Sie, wie Sie mit Aspose in C# PDFs aus HTML generieren – vollständige Schritt‑für‑Schritt‑Anleitung. -### [HTML‑Dokument in C# erstellen – Schritt‑für‑Schritt‑Anleitung](./create-html-document-c-step-by-step-guide/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET ein HTML‑Dokument in C# erstellen – eine detaillierte Schritt‑für‑Schritt‑Anleitung. -### [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. -### [Wie man Handler in Aspose.HTML verwendet – HTML laden, als ZIP speichern](./how-to-use-handler-in-aspose-html-load-html-save-as-zip/) Erfahren Sie, wie Sie mit Aspose.HTML einen Handler nutzen, HTML laden und das Ergebnis als ZIP‑Archiv speichern. ### [Benutzerdefinierter Ressourcen-Handler in C# – HTML in ZIP-Archiv aus dem Speicher konvertieren](./custom-resource-handler-in-c-convert-html-to-zip-archive-fro/) @@ -115,11 +100,11 @@ Erfahren Sie, wie Sie mit einem benutzerdefinierten Ressourcen‑Handler HTML‑ ### [HTML in PDF konvertieren mit Aspose.HTML – Vollständige Schritt‑für‑Schritt‑Anleitung](./convert-html-to-pdf-with-aspose-html-full-step-by-step-guide/) Konvertieren Sie HTML mühelos in PDF mit Aspose.HTML. Folgen Sie unserer vollständigen Schritt‑für‑Schritt‑Anleitung. ### [Erstellen Sie eine ZIP-Datei in C# – Schritt‑für‑Schritt‑Anleitung zum Zippen von HTML im Speicher](./create-zip-file-c-step-by-step-guide-to-zip-html-in-memory/) -Erfahren Sie, wie Sie HTML-Inhalte im Speicher mit C# in eine ZIP-Datei komprimieren – komplette Schritt‑für‑Schritt‑Anleitung. +Erfahren Sie, wie Sie HTML‑Inhalte im Speicher mit C# in eine ZIP‑Datei komprimieren – komplette Schritt‑für‑Schritt‑Anleitung. ### [Konvertieren Sie HTML in ZIP in C# – Komplettanleitung](./convert-html-to-zip-in-c-complete-guide/) Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in ZIP-Archive konvertieren. Schritt-für-Schritt-Anleitung mit Codebeispielen. ### [HTML in C# zippen – Vollständige Schritt‑für‑Schritt‑Anleitung](./how-to-zip-html-in-c-complete-step-by-step-guide/) -Erfahren Sie, wie Sie HTML-Dateien in C# zippen. Eine vollständige Schritt‑für‑Schritt‑Anleitung mit Codebeispielen. +Erfahren Sie, wie Sie HTML‑Dateien in C# zippen. Eine vollständige Schritt‑für‑Schritt‑Anleitung mit Codebeispielen. ### [PDF aus HTML in C# erstellen – Vollständige Schritt‑für‑Schritt‑Anleitung](./create-pdf-from-html-in-c-complete-step-by-step-guide/) Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in PDF konvertieren. Eine vollständige Schritt‑für‑Schritt‑Anleitung mit Codebeispielen. ### [HTML als ZIP in C# speichern – Komplett‑Schritt‑für‑Schritt‑Anleitung](./save-html-as-zip-in-c-complete-step-by-step-guide/) diff --git a/html/german/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/german/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..bd8acaa44e --- /dev/null +++ b/html/german/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,341 @@ +--- +category: general +date: 2026-10-02 +description: Erfahren Sie, wie Sie HTML mit Aspose.HTML in C# als ZIP speichern. Dieser + Leitfaden zeigt außerdem, wie Sie HTML mit Bildern in einem einzigen Archiv speichern. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: de +lastmod: 2026-10-02 +og_description: Speichern Sie HTML als ZIP mit Aspose.HTML in C#. Folgen Sie diesem + vollständigen Tutorial, um zu lernen, wie Sie HTML mit Bildern in ein einziges Archiv + speichern. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: HTML als ZIP mit Aspose.HTML speichern – Schritt‑für‑Schritt C#‑Leitfaden +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Wie man HTML als ZIP mit Aspose.HTML speichert und Bilder einbindet +url: /de/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man HTML als ZIP speichert mit Aspose.HTML und Bilder einbindet + +Wenn Sie **HTML als ZIP speichern** für eine einfache Verteilung benötigen, zeigt Ihnen dieses Tutorial die genauen Schritte mit Aspose.HTML für .NET. Egal, ob Sie eine statische Seite, eine E‑Mail‑Vorlage oder einen Bericht mit Bildern exportieren, Sie sehen, wie Sie HTML, CSS und Bilddateien in ein einziges ZIP‑Archiv bündeln, ohne temporäre Dateien auf die Festplatte zu schreiben. + +Zusätzlich zum Hauptziel beantworten wir die häufig gestellte Anschlussfrage **wie man HTML mit Bildern speichert**, sodass das resultierende Archiv von jedem Browser ohne fehlende Ressourcen geöffnet werden kann. + +Am Ende dieses Leitfadens haben Sie eine wiederverwendbare `ResourceHandler`‑Implementierung, ein komplettes C#‑Programm, das `output.zip` erzeugt, und praktische Tipps zum Umgang mit großen Bildern oder benutzerdefinierten Ordnerstrukturen. + +## Voraussetzungen + +- .NET 6.0 oder höher (die API funktioniert auch mit .NET Framework 4.6+) +- Aspose.HTML für .NET NuGet‑Paket (`Aspose.Html`) +- Grundkenntnisse in C# und Streams +- Visual Studio 2022 oder jede IDE, die .NET‑Entwicklung unterstützt + +> **Pro Tipp:** Installieren Sie das Paket über die CLI, um Ihre Projektdatei sauber zu halten: +> `dotnet add package Aspose.Html` + +## Schritt 1: Das Ausgabemodell von Aspose.HTML verstehen + +Wenn Aspose.HTML ein Dokument speichert, behandelt es jede externe Ressource (CSS‑Dateien, Bilder, Schriftarten usw.) als separate **Ressource**. Standardmäßig schreibt die Bibliothek diese Ressourcen in das Dateisystem. Um das Ziel zu steuern, stellen Sie einen benutzerdefinierten `ResourceHandler` bereit. Der Handler erhält ein `Resource`‑Objekt und muss einen beschreibbaren `Stream` zurückgeben. Aspose.HTML schreibt dann die Ressourcendaten in diesen Stream. + +Ein benutzerdefinierter Handler ermöglicht es Ihnen: + +- Ressourcen direkt in einen `MemoryStream` zu schreiben, der später zu einem ZIP‑Eintrag wird +- Ressourcen in einer Datenbank, Cloud‑Speicherung oder einem anderen Medium zu speichern +- Dateinamen, Komprimierungsstufen oder Ordnerhierarchien anzupassen + +## Schritt 2: Erstellen Sie einen `ResourceHandler`, der in ein ZIP‑Archiv schreibt + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Warum dieser Ansatz funktioniert + +- **In‑Memory‑Operation**: Es werden keine temporären Dateien auf der Festplatte erstellt, was ideal für Web‑Dienste oder sandboxed Umgebungen ist. +- **Erhält Ordnerhierarchie**: Durch die Verwendung der ursprünglichen Ressourcen‑URI bleiben relative Verweise nach dem Extrahieren gültig. +- **Erweiterbar**: Sie können `MemoryStream` durch einen `FileStream` ersetzen, um direkt in eine Datei zu schreiben, oder durch einen Netzwerk‑Stream für Cloud‑Speicher. + +## Schritt 3: Laden oder erstellen Sie das HTML‑Dokument + +Zur Demonstration erstellen wir einen einfachen HTML‑String, der ein externes Bild referenziert. In einem realen Projekt würden Sie HTML aus einer Datei, einer Datenbank oder einer HTTP‑Antwort laden. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Hinweis:** Wenn Sie eine physische HTML‑Datei haben, verwenden Sie stattdessen `new HTMLDocument("path/to/file.html")`. + +## Schritt 4: Verbinden Sie den Handler mit `SaveOptions` und speichern Sie das ZIP + +Jetzt verbinden wir den `ZipResourceHandler` mit `SaveOptions.OutputStorage`. Wenn `document.Save` ausgeführt wird, ruft Aspose.HTML `HandleResource` für jede Ressource auf, und der Handler füllt das ZIP‑Archiv. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Erwartetes Ergebnis + +- `output.zip` enthält: + - `index.html` (die Haupt‑HTML‑Datei) + - `images/logo.png` (das im Markup referenzierte Bild) + - Alle zusätzlichen CSS‑ oder Schriftdateien, die automatisch von Aspose.HTML erkannt werden + +Wenn Sie das Archiv extrahieren und `index.html` in einem Browser öffnen, wird das Bild korrekt angezeigt – das demonstriert **wie man HTML mit Bildern** innerhalb eines ZIP speichert. + +## Schritt 5: Überprüfen Sie das Archiv und beheben Sie häufige Probleme + +### Kurzes Verifizierungsskript + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Das Ausführen des Skripts sollte `index.html` und `images/logo.png` auflisten. Wenn eine erwartete Ressource fehlt: + +- **Überprüfen Sie die Bild‑URL**: Sie muss vom HTML‑Dokument aus erreichbar sein. Relative Pfade funktionieren am besten. +- **Stellen Sie sicher, dass der Ressourcentyp unterstützt wird**: Aspose.HTML verarbeitet gängige Web‑Formate (PNG, JPEG, GIF, CSS, JS). Ungewöhnliche Formate können eine manuelle Ergänzung erfordern. +- **Bestätigen Sie, dass `HandleResource` aufgerufen wird**: Fügen Sie ein `Console.WriteLine(resource.Uri)` innerhalb von `HandleResource` zum Debuggen hinzu. + +## Schritt 6: Erweiterte Varianten + +### 6.1 Direkt in eine Datei speichern ohne ein Zwischenspeicher‑Byte‑Array + +Wenn der Speicherverbrauch bei sehr großen Dokumenten ein Problem darstellt, ersetzen Sie `MemoryStream` durch einen `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Dann verwenden Sie es wie: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Anpassen von Eintragsnamen + +Wenn Sie eine flache Struktur bevorzugen (alle Dateien im Root), passen Sie `entryName` an: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Hinzufügen einer Manifest‑Datei + +Manche nachgelagerten Tools erwarten eine `manifest.json`. Sie können sie nach dem Haupt‑Save hinzufügen: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Häufige Fallstricke und wie man sie vermeidet + +| Problem | Warum es passiert | Lösung | +|---------|-------------------|--------| +| Bilder erscheinen nach dem Extrahieren kaputt | Der Bildpfad im HTML stimmt nicht mit dem ZIP‑Eintrag überein. | Bewahren Sie den ursprünglichen relativen Pfad beim Erstellen von `ZipArchiveEntry` bei. | +| Große Bilder verursachen Out‑of‑Memory‑Ausnahmen | Die Verwendung von `MemoryStream` für sehr große Dateien kann das Speicherlimit des Prozesses überschreiten. | Wechseln Sie zu einem `FileStream`‑basierten Handler (siehe 6.1). | +| CSS‑URLs fehlen | Externe CSS‑Dateien, die über `@import` referenziert werden, werden nicht automatisch erkannt. | Fügen Sie diese CSS‑Dateien manuell zum ZIP hinzu oder betten Sie sie vor dem Speichern inline ein. | +| Unicode‑Zeichen werden verzerrt | Die Standard‑Kodierung kann zwischen der HTML‑Quelle und dem Stream unterschiedlich sein. | Stellen Sie sicher, dass die HTML‑Zeichenkette UTF‑8 ist; Aspose.HTML respektiert das Charset des Dokuments. | + +## Vollständiges funktionierendes Beispiel (zum Kopieren und Einfügen bereit) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Wie man Handler in Aspose.HTML verwendet – HTML laden, als ZIP speichern](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Wie man HTML in C# speichert – Benutzerdefinierte Resource‑Handler & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [HTML zu PNG rendern und mit C# in ZIP speichern – Komplett‑Anleitung](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 d1d1c6c0e5..d1a5ba040b 100644 --- a/html/german/net/rendering-html-documents/_index.md +++ b/html/german/net/rendering-html-documents/_index.md @@ -94,6 +94,9 @@ Erfahren Sie, wie Sie mit C# HTML in PNG konvertieren, Schritt für Schritt, ink ### [Rendern Sie HTML nach PNG in C# mit Aspose](./how-to-use-aspose-to-render-html-to-png-in-c/) Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in C# zu PNG rendern und dabei Optionen optimal nutzen. +### [Wie Sie Aspose verwenden, um HTML in ein PNG‑Bild in C# zu rendern](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Erfahren Sie, wie Sie mit Aspose.HTML HTML in C# zu PNG‑Bildern rendern. + ### [HTML mit C# in ein Bild rendern – Komplettanleitung](./how-to-render-html-to-an-image-with-c-complete-guide/) Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in C# in ein Bild konvertieren und dabei erweiterte Rendering-Optionen nutzen. ### [HTML zu PDF rendern mit Aspose.HTML – Schritt‑für‑Schritt‑Leitfaden](./render-html-to-pdf-with-aspose-html-step-by-step-guide/) diff --git a/html/german/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/german/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..90860e4c70 --- /dev/null +++ b/html/german/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-10-02 +description: Wie man Aspose verwendet, um HTML schnell in ein PNG‑Bild zu rendern + – lernen Sie, HTML mit Anti‑Aliasing und Text‑Hinting in PNG zu konvertieren. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: de +lastmod: 2026-10-02 +og_description: Wie man Aspose verwendet, um HTML in ein PNG‑Bild zu rendern. Folgen + Sie diesem vollständigen Tutorial, um HTML mit hochwertiger Rendering‑Qualität in + PNG zu konvertieren, in C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Wie man Aspose verwendet, um HTML in ein PNG‑Bild zu rendern – Schritt‑für‑Schritt‑Anleitung +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Wie man Aspose verwendet, um HTML in ein PNG‑Bild in C# zu rendern +url: /de/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man Aspose verwendet, um HTML in ein PNG‑Bild in C# zu rendern + +**Wie man Aspose verwendet, um HTML in ein PNG‑Bild zu rendern** ist ein häufiges Bedürfnis, wenn Sie eine Bitmap‑Vorschau einer Webseite, ein E‑Mail‑Thumbnail oder einen PDF‑freundlichen Schnappschuss benötigen. Dieses Tutorial zeigt Ihnen eine komplette, sofort lauffähige Lösung, die **render html to image** mit Anti‑Aliasing und Text‑Hinting verwendet, sodass das Ergebnis auf jeder Plattform scharf aussieht. + +Sie lernen, wie man **convert HTML to PNG** verwendet, Rendering‑Optionen konfiguriert und typische Fallstricke wie Linux‑Font‑Rendering und Dateisystem‑Berechtigungen behandelt. Es werden keine externen Tools benötigt – nur die Aspose.HTML‑für‑.NET‑Bibliothek und ein paar Zeilen C#. + +## Voraussetzungen + +* .NET 6.0 SDK oder neuer installiert +* Visual Studio 2022 (oder jede C#‑IDE) +* Ein NuGet‑Verweis auf **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Grundlegende Kenntnisse der C#‑Syntax + +Diese Voraussetzungen sind leichtgewichtig; das Tutorial funktioniert unter Windows, Linux und macOS, da Aspose.HTML plattformübergreifend ist. + +## Schritt 1: Aspose.HTML installieren und ein neues Konsolenprojekt erstellen + +Öffnen Sie ein Terminal oder die Package‑Manager‑Konsole und führen Sie aus: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Ein dediziertes Projekt isoliert die Abhängigkeiten und erleichtert das Ausführen des Beispiels mit `dotnet run`. + +## Schritt 2: Bild‑Rendering‑Optionen einrichten (Anti‑Aliasing und Text‑Hinting) + +Anti‑Aliasing glättet Kanten, während Text‑Hinting die Glyphen‑Klarheit verbessert, insbesondere unter Linux, wo die Font‑Rasterisierung von Windows abweicht. Die Klasse `ImageRenderingOptions` ermöglicht das Aktivieren beider Funktionen: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Warum das wichtig ist:** Ohne Anti‑Aliasing sehen diagonale Linien und Kurven gezackt aus. Ohne Text‑Hinting können kleine Schriftgrößen unscharf werden, was auffällt, wenn Sie **save html as png** für Thumbnails verwenden. + +## Schritt 3: CSS für konsistente Schriften und Überschriften‑Stile definieren + +Das direkte Einbetten von CSS in das HTML stellt sicher, dass das gerenderte Bild Ihren Design‑Erwartungen entspricht. In diesem Beispiel setzen wir eine Basis‑Schrift und machen `

` kursiv: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Sie können das Stylesheet mit Farben, Abständen oder Media‑Queries erweitern. Das CSS wird in das ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Tipp:** Wenn Sie **render html as image** von einer entfernten Seite benötigen, ersetzen Sie den String‑Konstruktor durch `new HTMLDocument("https://example.com")`. Aspose lädt die Seite herunter, löst Ressourcen auf und rendert das endgültige Layout. + +## Schritt 5: Dokument in eine PNG‑Datei rendern + +Jetzt rufen wir `RenderToImage` auf und übergeben den Ausgabepfad sowie die zuvor konfigurierten Optionen: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +Das erzeugte `output.png` enthält ein klares Rendering des `

`‑Elements mit kursiver Formatierung, dank der Anti‑Aliasing‑ und Hinting‑Einstellungen. + +## Vollständige Programmliste + +Kopieren Sie den folgenden Code in `Program.cs`. Er kompiliert und läuft unverändert: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Erwartete Ausgabe + +Das Ausführen des Programms erzeugt `output.png` im Projektordner. Das Bild zeigt das Wort **Sample** in kursivem Arial, gerendert mit glatten Kanten und klarer Schrift. Öffnen Sie die Datei mit einem beliebigen Bildbetrachter, um die Qualität zu überprüfen. + +## Schritt 6: Häufige Variationen und Edge‑Case‑Behandlung + +| Situation | Was anzupassen ist | Grund | +|-------------------------------|-----------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------| +| **Große HTML‑Seiten** | Setzen Sie `ImageRenderingOptions.Width` / `Height` oder verwenden Sie `PageSize`, um die Ausgabedimensionen zu steuern | Verhindert Speicherüberlauf und stellt sicher, dass das PNG in Ihre UI passt | +| **Linux‑Font fehlt** | Installieren Sie die benötigten Fonts auf dem Host (`apt-get install fonts‑arial` oder verwenden Sie eine benutzerdefinierte Font‑Datei) und verweisen Sie Aspose darauf über `FontSettings` | Ohne den Font greift Aspose auf einen generischen zurück, was das Aussehen verändert | +| **Transparenter Hintergrund benötigt** | Setzen Sie `imgOptions.BackgroundColor = Color.Transparent` | Nützlich, wenn das PNG in andere Grafiken eingebettet wird | +| **Stapelkonvertierung** | Durchlaufen Sie eine Liste von HTML‑Strings oder Dateipfaden und verwenden Sie dasselbe `ImageRenderingOptions`‑Objekt erneut | Verbessert die Leistung und hält die Rendering‑Einstellungen konsistent | + +## Pro‑Tipp: Rendering‑Optionen cachen + +Das Erstellen eines neuen `ImageRenderingOptions`‑Objekts für jede Konvertierung verursacht Overhead. Deklarieren Sie eine statische Instanz, wenn Sie viele HTML‑Snippets in einem Service verarbeiten: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Verwenden Sie `SharedOptions` über Aufrufe hinweg, um die CPU‑Auslastung gering zu halten. + +## Häufig gestellte Fragen + +**Q: Funktioniert das mit .NET Core auf macOS?** +A: Ja. Aspose.HTML ist vollständig plattformübergreifend. Stellen Sie sicher, dass die benötigten Fonts installiert sind und das Ausgabeverzeichnis beschreibbar ist. + +**Q: Kann ich stattdessen zu JPEG rendern?** +A: Ersetzen Sie `RenderToImage("output.png", imgOptions)` durch `RenderToImage("output.jpg", imgOptions)`. Sie können auch `imgOptions.ImageFormat = ImageFormat.Jpeg` setzen, um die Qualität feiner zu steuern. + +**Q: Wie bette ich externe CSS‑Dateien ein?** +A: Laden Sie den CSS‑Inhalt in einen String und verketten Sie ihn, oder verweisen Sie im ``‑Tag auf ein entferntes Stylesheet. Aspose löst ``‑Tags automatisch auf, wenn das Dokument von einer URL geladen wird. + +## Fazit + +Sie wissen jetzt, **wie man Aspose** verwendet, um **HTML in PNG** (oder ein anderes Rasterformat) mit hochwertigen Einstellungen zu **rendern**. Das Tutorial behandelte die Installation von Aspose.HTML, das Konfigurieren von Anti‑Aliasing und Text‑Hinting, das Einfügen von CSS, das Laden von HTML und schließlich das **saving HTML as PNG**. Wenn Sie die Schritte befolgen, können Sie zuverlässig **convert HTML to PNG** in jeder .NET‑Anwendung durchführen, egal ob sie unter Windows, Linux oder macOS läuft. + +### Nächste Schritte + +* Untersuchen Sie weitere Ausgabeformate wie **render html as image** JPEG oder BMP, indem Sie die Dateierweiterung ändern. +* Kombinieren Sie diesen Ansatz mit **Aspose.PDF**, um das PNG in einen PDF‑Bericht einzubetten. +* Experimentieren Sie mit `ImageRenderingOptions.DpiX` und `DpiY` für hochauflösende Thumbnails. + +Passen Sie den Code gern für Stapelverarbeitung, dynamische HTML‑Erzeugung oder die Integration in einen Web‑Service an, der PNG‑Vorschauen auf Abruf zurückgibt. Viel Spaß beim Rendern! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Wie man Aspose verwendet, um HTML zu PNG zu rendern – Schritt‑für‑Schritt‑Anleitung](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Wie man HTML mit Aspose zu PNG rendert – Komplett‑Leitfaden](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [HTML‑zu‑Bild‑Tutorial – Render HTML to PNG mit Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 d3ce73d6ed..839fc76033 100644 --- a/html/greek/net/html-extensions-and-conversions/_index.md +++ b/html/greek/net/html-extensions-and-conversions/_index.md @@ -75,7 +75,7 @@ url: /el/net/html-extensions-and-conversions/ Ανακαλύψτε πώς να χρησιμοποιήσετε το Aspose.HTML για .NET για χειρισμό και μετατροπή εγγράφων HTML. Οδηγός βήμα προς βήμα για αποτελεσματική ανάπτυξη .NET. ### [Μετατροπή HTML σε TIFF στο .NET με Aspose.HTML](./convert-html-to-tiff/) Μάθετε πώς να μετατρέπετε HTML σε TIFF με το Aspose.HTML για .NET. Ακολουθήστε τον βήμα προς βήμα οδηγό μας για αποτελεσματική βελτιστοποίηση περιεχομένου ιστού. -### [Μετατροπή HTML σε XPS σε .NET με Aspose.HTML](./convert-html-to-xps/) +### [Μετατροπή HTML σε XPS στο .NET με Aspose.HTML](./convert-html-to-xps/) Ανακαλύψτε τη δύναμη του Aspose.HTML για .NET: Μετατρέψτε HTML σε XPS χωρίς κόπο. Περιλαμβάνονται προαπαιτούμενα, οδηγός βήμα προς βήμα και συχνές ερωτήσεις. ### [Δημιουργία PDF από URL – Πλήρης Οδηγός C#](./create-pdf-from-url-complete-c-guide/) Μάθετε πώς να δημιουργήσετε PDF από μια διεύθυνση URL χρησιμοποιώντας το Aspose.HTML για .NET με πλήρη οδηγό C#. @@ -91,7 +91,6 @@ url: /el/net/html-extensions-and-conversions/ Μάθετε πώς να αποθηκεύετε HTML σε αρχείο ZIP με C# και Aspose.HTML. ### [Δημιουργία εγγράφου HTML και αποθήκευση ως zip – Πλήρης οδηγός C#](./create-html-document-and-save-as-zip-complete-c-guide/) Μάθετε πώς να δημιουργήσετε έγγραφο HTML και να το αποθηκεύσετε σε αρχείο ZIP με C# χρησιμοποιώντας Aspose.HTML. - ### [Αποθήκευση HTML σε ZIP σε C# – Πλήρες Παράδειγμα Εντός Μνήμης](./save-html-to-zip-in-c-complete-in-memory-example/) Μάθετε πώς να αποθηκεύετε HTML σε αρχείο ZIP με C# χρησιμοποιώντας πλήρες παράδειγμα εντός μνήμης. ### [Προσαρμοσμένος Διαχειριστής Πόρων σε C# – Μετατροπή HTML σε Αρχείο ZIP από Μνήμη](./custom-resource-handler-in-c-convert-html-to-zip-archive-fro/) @@ -111,7 +110,7 @@ url: /el/net/html-extensions-and-conversions/ ### [Aspose HTML σε PDF με C# – Πλήρης οδηγός με αρχείο ZIP](./aspose-html-to-pdf-in-c-complete-guide-with-zip-archive/) Δημιουργήστε PDF από HTML σε C# και αποθηκεύστε το σε αρχείο ZIP με τον πλήρη οδηγό του Aspose.HTML. ### [Αποθήκευση HTML σε ZIP σε C# – Πλήρης Οδηγός](./save-html-to-zip-in-c-complete-guide/) -Μάθετε πώς να αποθηκεύετε αρχεία HTML σε αρχείο ZIP χρησιμοποιώντας C# και Aspose.HTML με πλήρη παράδειγμα. +Μάθετε πώς να αποθηκεύετε HTML σε αρχείο ZIP με C# χρησιμοποιώντας πλήρη παράδειγμα. ### [single file html – Αποθήκευση ιστοσελίδας ως ένα αρχείο HTML σε C#](./single-file-html-save-a-web-page-as-one-html-file-in-c/) Μάθετε πώς να αποθηκεύσετε μια ιστοσελίδα ως ένα ενιαίο αρχείο HTML χρησιμοποιώντας C# και Aspose.HTML. ### [Πώς να χρησιμοποιήσετε το handler στο Aspose.HTML – Φόρτωση HTML, αποθήκευση ως ZIP](./how-to-use-handler-in-aspose-html-load-html-save-as-zip/) @@ -124,29 +123,26 @@ url: /el/net/html-extensions-and-conversions/ Ορίστε το μέγεθος της σελίδας PDF σε C# κατά τη μετατροπή HTML σε PDF με το Aspose.HTML. ### [Αποθήκευση HTML ως ZIP σε C# – Πλήρης Οδηγός](./save-html-as-zip-in-c-complete-guide/) -Μάθετε πώς να αποθηκεύετε HTML σε αρχείο ZIP με C# χρησιμοποιώντας πλήρη οδηγό βήμα‑βήμα. - - - +Μάθετε πώς να αποθηκεύετε HTML σε αρχείο ZIP με C# χρησιμοποιώντας πλήρη οδηγό βήμα‑βήμα. +### [Πώς να αποθηκεύσετε HTML ως zip με Aspose.HTML και να συμπεριλάβετε εικόνες](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Μάθετε πώς να αποθηκεύσετε HTML σε αρχείο ZIP μαζί με τις εικόνες χρησιμοποιώντας το Aspose.HTML. - -## Σύναψη - -Συμπερασματικά, οι επεκτάσεις και οι μετατροπές HTML είναι βασικά στοιχεία της σύγχρονης ανάπτυξης ιστού. Το Aspose.HTML για .NET απλοποιεί τη διαδικασία και το καθιστά προσβάσιμο σε προγραμματιστές όλων των επιπέδων. Ακολουθώντας τα σεμινάρια μας, θα είστε σε καλό δρόμο για να γίνετε ικανός προγραμματιστής ιστού με ευρύ σύνολο δεξιοτήτων. - -Λοιπόν, τι περιμένετε; Ας ξεκινήσουμε αυτό το συναρπαστικό ταξίδι για να εξερευνήσουμε επεκτάσεις και μετατροπές HTML χρησιμοποιώντας το Aspose.HTML για .NET. Τα έργα ανάπτυξης Ιστού σας δεν θα είναι ποτέ τα ίδια! -### [Μετατροπή HTML σε PDF σε C# – Πλήρης Οδηγός Aspose](./convert-html-to-pdf-in-c-full-aspose-guide/) -Μάθετε πώς να μετατρέπετε HTML σε PDF χρησιμοποιώντας C# με τον πλήρη οδηγό Aspose. -### [Δημιουργία PDF από HTML με Aspose σε C# – Πλήρης Οδηγός](./create-pdf-from-html-with-aspose-in-c-full-guide/) -Μάθετε πώς να δημιουργήσετε PDF από HTML χρησιμοποιώντας Aspose σε C# με αυτόν τον πλήρη οδηγό. -### [Aspose HTML Επιλογές Αποθήκευσης: Αποθήκευση HTML σε Ροή σε C#](./aspose-html-save-options-save-html-to-stream-in-c/) -Μάθετε πώς να αποθηκεύετε HTML σε ροή χρησιμοποιώντας τις επιλογές αποθήκευσης του Aspose.HTML σε C#. +### [single file html – Αποθήκευση ιστοσελίδας ως ένα αρχείο HTML σε C#](./single-file-html-save-a-web-page-as-one-html-file-in-c/) +Μάθετε πώς να αποθηκεύσετε μια ιστοσελίδα ως ένα ενιαίο αρχείο HTML χρησιμοποιώντας C# και Aspose.HTML. +### [Πώς να χρησιμοποιήσετε το handler στο Aspose.HTML – Φόρτωση HTML, αποθήκευση ως ZIP](./how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +Μάθετε πώς να φορτώνετε HTML με handler και να το αποθηκεύετε σε αρχείο ZIP χρησιμοποιώντας το Aspose.HTML για .NET. +### [Αποθήκευση HTML σε PDF σε C# – Πλήρης Οδηγός με Γραμματοσειρές](./save-html-as-pdf-in-c-complete-guide-with-fonts/) +Μάθετε πώς να αποθηκεύετε HTML ως PDF σε C# με πλήρη υποστήριξη γραμματοσειρών, βήμα‑βήμα οδηγίες και παραδείγματα κώδικα. +### [Δημιουργία εγγράφου HTML C# – Οδηγός βήμα‑βήμα](./create-html-document-c-step-by-step-guide/) +Μάθετε πώς να δημιουργήσετε ένα έγγραφο HTML χρησιμοποιώντας C# βήμα‑βήμα με το Aspose.HTML. +### [Ορισμός μεγέθους σελίδας PDF σε C# – Μετατροπή HTML σε PDF](./set-pdf-page-size-in-c-convert-html-to-pdf/) +Ορίστε το μέγεθος της σελίδας PDF σε C# κατά τη μετατροπή HTML σε PDF με το Aspose.HTML. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/greek/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/greek/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..185c3f1814 --- /dev/null +++ b/html/greek/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,344 @@ +--- +category: general +date: 2026-10-02 +description: Μάθετε πώς να αποθηκεύετε HTML ως zip χρησιμοποιώντας το Aspose.HTML + σε C#. Αυτός ο οδηγός δείχνει επίσης πώς να αποθηκεύετε HTML με εικόνες σε ένα ενιαίο + αρχείο. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: el +lastmod: 2026-10-02 +og_description: Αποθηκεύστε HTML ως zip χρησιμοποιώντας το Aspose.HTML σε C#. Ακολουθήστε + αυτό το πλήρες σεμινάριο για να μάθετε πώς να αποθηκεύετε HTML με εικόνες σε ένα + ενιαίο αρχείο. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Αποθήκευση HTML ως zip με το Aspose.HTML – βήμα‑βήμα οδηγός C# +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Πώς να αποθηκεύσετε το HTML ως zip με το Aspose.HTML και να συμπεριλάβετε εικόνες +url: /el/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να αποθηκεύσετε HTML ως zip με Aspose.HTML και να συμπεριλάβετε εικόνες + +Αν χρειάζεστε **αποθήκευση HTML ως zip** για εύκολη διανομή, αυτό το tutorial σας δείχνει τα ακριβή βήματα χρησιμοποιώντας το Aspose.HTML για .NET. Είτε εξάγετε μια στατική σελίδα, ένα πρότυπο email, είτε μια αναφορά που περιέχει εικόνες, θα δείτε πώς να συσσωρεύσετε τα αρχεία HTML, CSS και εικόνων σε ένα ενιαίο αρχείο ZIP χωρίς να γράψετε προσωρινά αρχεία στο δίσκο. + +Επιπλέον του κύριου στόχου, θα απαντήσουμε επίσης στην κοινή επακόλουθη ερώτηση **πώς να αποθηκεύσετε HTML με εικόνες** ώστε το παραγόμενο αρχείο να μπορεί να ανοίξει από οποιονδήποτε φυλλομετρητή χωρίς ελλιπή πόρους. + +Στο τέλος αυτού του οδηγού θα έχετε μια επαναχρησιμοποιήσιμη υλοποίηση `ResourceHandler`, ένα πλήρες πρόγραμμα C# που παράγει το `output.zip`, και πρακτικές συμβουλές για τη διαχείριση μεγάλων εικόνων ή προσαρμοσμένων δομών φακέλων. + +## Προαπαιτούμενα + +- .NET 6.0 ή νεότερο (το API λειτουργεί επίσης με .NET Framework 4.6+) +- Πακέτο NuGet Aspose.HTML για .NET (`Aspose.Html`) +- Βασικές γνώσεις C# και ροών (streams) +- Visual Studio 2022 ή οποιοδήποτε IDE που υποστηρίζει ανάπτυξη .NET + +> **Pro tip:** Εγκαταστήστε το πακέτο μέσω του CLI για να διατηρήσετε το αρχείο του έργου σας καθαρό: +> `dotnet add package Aspose.Html` + +## Βήμα 1: Κατανόηση του μοντέλου εξόδου του Aspose.HTML + +Όταν το Aspose.HTML αποθηκεύει ένα έγγραφο, αντιμετωπίζει κάθε εξωτερικό πόρο (αρχεία CSS, εικόνες, γραμματοσειρές κ.λπ.) ως ξεχωριστό **πόρο**. Από προεπιλογή η βιβλιοθήκη γράφει αυτούς τους πόρους στο σύστημα αρχείων. Για να ελέγξετε τον προορισμό, παρέχετε έναν προσαρμοσμένο `ResourceHandler`. Ο χειριστής λαμβάνει ένα αντικείμενο `Resource` και πρέπει να επιστρέψει ένα εγγράψιμο `Stream`. Το Aspose.HTML στη συνέχεια γράφει τα δεδομένα του πόρου σε αυτό το stream. + +Με τη χρήση προσαρμοσμένου χειριστή μπορείτε να: + +- Γράψετε πόρους απευθείας σε ένα `MemoryStream` που αργότερα γίνεται καταχώρηση ZIP +- Αποθηκεύσετε πόρους σε βάση δεδομένων, αποθήκευση στο cloud ή οποιοδήποτε άλλο μέσο +- Προσαρμόσετε ονόματα αρχείων, επίπεδα συμπίεσης ή ιεραρχίες φακέλων + +## Βήμα 2: Δημιουργία ενός `ResourceHandler` που γράφει σε αρχείο ZIP + +Παρακάτω υπάρχει ένας πλήρως λειτουργικός χειριστής που δημιουργεί ένα `System.IO.Compression.ZipArchive` στη μνήμη. Κάθε πόρος προστίθεται ως νέα καταχώρηση της οποίας το όνομα αντικατοπτρίζει την αρχική διαδρομή URL, εξασφαλίζοντας ότι ο φυλλομετρητής μπορεί να επιλύσει τις σχετικές συνδέσεις όταν το ZIP εξάγεται. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Γιατί αυτή η προσέγγιση λειτουργεί + +- **Λειτουργία στη μνήμη**: Δεν δημιουργούνται προσωρινά αρχεία στο δίσκο, κάτι που είναι ιδανικό για web services ή περιβάλλοντα sandbox. +- **Διατηρεί την ιεραρχία φακέλων**: Χρησιμοποιώντας το αρχικό URI του πόρου, οι σχετικές αναφορές παραμένουν έγκυρες μετά την εξαγωγή. +- **Επεκτάσιμο**: Μπορείτε να αντικαταστήσετε το `MemoryStream` με ένα `FileStream` για άμεση εγγραφή σε αρχείο, ή με ένα network stream για αποθήκευση στο cloud. + +## Βήμα 3: Φόρτωση ή δημιουργία του εγγράφου HTML + +Για επίδειξη, θα δημιουργήσουμε μια απλή συμβολοσειρά HTML που αναφέρεται σε εξωτερική εικόνα. Σε ένα πραγματικό έργο θα φορτώνετε HTML από αρχείο, βάση δεδομένων ή από HTTP response. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Σημείωση:** Εάν έχετε ένα φυσικό αρχείο HTML, χρησιμοποιήστε `new HTMLDocument("path/to/file.html")` αντί αυτού. + +## Βήμα 4: Σύνδεση του χειριστή με `SaveOptions` και αποθήκευση του ZIP + +Τώρα συνδέουμε το `ZipResourceHandler` με το `SaveOptions.OutputStorage`. Όταν εκτελεστεί το `document.Save`, το Aspose.HTML θα καλέσει το `HandleResource` για κάθε πόρο, και ο χειριστής θα γεμίσει το αρχείο ZIP. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Αναμενόμενο αποτέλεσμα + +- Το `output.zip` περιέχει: + - `index.html` (το κύριο αρχείο HTML) + - `images/logo.png` (η εικόνα που αναφέρεται στο markup) + - Οποιαδήποτε επιπλέον αρχεία CSS ή γραμματοσειρών ανιχνεύονται αυτόματα από το Aspose.HTML + +Όταν εξάγετε το αρχείο και ανοίξετε το `index.html` σε έναν φυλλομετρητή, η εικόνα εμφανίζεται σωστά—δείχνοντας **πώς να αποθηκεύσετε HTML με εικόνες** μέσα σε ZIP. + +## Βήμα 5: Επαλήθευση του αρχείου και αντιμετώπιση κοινών προβλημάτων + +### Σύντομο script επαλήθευσης + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Η εκτέλεση του script θα πρέπει να εμφανίσει τα `index.html` και `images/logo.png`. Εάν λείπει κάποιο αναμενόμενο πόρο: + +- **Ελέγξτε το URL της εικόνας**: Πρέπει να είναι προσβάσιμο από το έγγραφο HTML. Οι σχετικές διαδρομές λειτουργούν καλύτερα. +- **Βεβαιωθείτε ότι ο τύπος πόρου υποστηρίζεται**: Το Aspose.HTML διαχειρίζεται κοινές μορφές web (PNG, JPEG, GIF, CSS, JS). Ασυνήθιστες μορφές μπορεί να απαιτούν χειροκίνητη προσθήκη. +- **Επιβεβαιώστε ότι καλείται το `HandleResource`**: Προσθέστε ένα `Console.WriteLine(resource.Uri)` μέσα στο `HandleResource` για εντοπισμό σφαλμάτων. + +## Βήμα 6: Προχωρημένες παραλλαγές + +### 6.1 Αποθήκευση απευθείας σε αρχείο χωρίς ενδιάμεσο byte array + +Εάν η χρήση μνήμης αποτελεί πρόβλημα για πολύ μεγάλα έγγραφα, αντικαταστήστε το `MemoryStream` με ένα `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Στη συνέχεια χρησιμοποιήστε το ως εξής: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Προσαρμογή ονομάτων καταχωρήσεων + +Εάν προτιμάτε μια επίπεδη δομή (όλα τα αρχεία στη ρίζα), προσαρμόστε το `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Προσθήκη αρχείου manifest + +Μερικές φορές τα εργαλεία downstream αναμένουν ένα `manifest.json`. Μπορείτε να το προσθέσετε μετά την κύρια αποθήκευση: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Συνηθισμένα προβλήματα και πώς να τα αποφύγετε + +| Πρόβλημα | Γιατί συμβαίνει | Διόρθωση | +|----------|------------------|----------| +| Οι εικόνες εμφανίζονται σπασμένες μετά την εξαγωγή | Η διαδρομή της εικόνας στο HTML δεν ταιριάζει με το όνομα της καταχώρησης ZIP. | Διατηρήστε την αρχική σχετική διαδρομή κατά τη δημιουργία του `ZipArchiveEntry`. | +| Μεγάλες εικόνες προκαλούν εξαιρέσεις έλλειψης μνήμης | Η χρήση του `MemoryStream` για πολύ μεγάλα αρχεία μπορεί να υπερβεί το όριο μνήμης της διεργασίας. | Αλλάξτε σε χειριστή βασισμένο σε `FileStream` (δείτε 6.1). | +| Τα URLs του CSS λείπουν | Τα εξωτερικά αρχεία CSS που αναφέρονται μέσω `@import` δεν ανιχνεύονται αυτόματα. | Προσθέστε χειροκίνητα αυτά τα αρχεία CSS στο ZIP ή ενσωματώστε τα εντός του HTML πριν την αποθήκευση. | +| Οι χαρακτήρες Unicode εμφανίζονται παραμορφωμένοι | Η προεπιλεγμένη κωδικοποίηση μπορεί να διαφέρει μεταξύ της πηγής HTML και του stream. | Βεβαιωθείτε ότι η συμβολοσειρά HTML είναι UTF‑8· το Aspose.HTML σέβεται το charset του εγγράφου. | + +## Πλήρες λειτουργικό παράδειγμα (έτοιμο για αντιγραφή‑επικόλληση) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που βασίζονται στις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [πώς να χρησιμοποιήσετε τον χειριστή στο Aspose.HTML – Φόρτωση HTML, Αποθήκευση ως ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Πώς να αποθηκεύσετε HTML σε C# – Προσαρμοσμένοι Χειριστές Πόρων & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Απόδοση HTML σε PNG και αποθήκευση σε ZIP με C# – Πλήρης Οδηγός](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 2359f98407..77d42db597 100644 --- a/html/greek/net/rendering-html-documents/_index.md +++ b/html/greek/net/rendering-html-documents/_index.md @@ -85,10 +85,10 @@ url: /el/net/rendering-html-documents/ Μάθετε πώς να δημιουργήσετε ένα έγγραφο HTML σε C# και να το αποδώσετε σε PNG με έντονη πλάγια γραμματοσειρά. ### [Πώς να χρησιμοποιήσετε το Aspose για απόδοση HTML σε PNG σε C#](./how-to-use-aspose-to-render-html-to-png-in-c/) -Μάθετε πώς να αποδίδετε HTML σε PNG χρησιμοποιώντας το Aspose σε C# με βήμα-βήμα οδηγίες. +Μάθετε πώς να αποδίδετε HTML σε PNG χρησιμοποιώντας το Aspose σε C# με βήμα‑βήμα οδηγίες. ### [Πώς να αποδώσετε HTML σε εικόνα με C# – Πλήρης Οδηγός](./how-to-render-html-to-an-image-with-c-complete-guide/) -Μάθετε πώς να αποδίδετε HTML σε εικόνα χρησιμοποιώντας C# με έναν πλήρη οδηγό βήμα-βήμα. +Μάθετε πώς να αποδίδετε HTML σε εικόνα χρησιμοποιώντας C# με έναν πλήρη οδηγό βήμα‑βήμα. ### [Απόδοση HTML σε PNG και αποθήκευση σε ZIP με C# – Πλήρης Οδηγός](./render-html-to-png-and-save-to-zip-with-c-complete-guide/) Μάθετε πώς να μετατρέψετε HTML σε PNG και να το συμπιέσετε σε αρχείο ZIP χρησιμοποιώντας C# και Aspose.HTML. ### [Δημιουργία εικόνας από HTML σε C# – Πλήρης Οδηγός Βήμα‑βήμα](./create-image-from-html-in-c-complete-step-by-step-guide/) @@ -96,6 +96,9 @@ url: /el/net/rendering-html-documents/ ### [Απόδοση HTML σε PDF με Aspose.HTML – Οδηγός βήμα‑βήμα](./render-html-to-pdf-with-aspose-html-step-by-step-guide/) Μάθετε πώς να μετατρέψετε HTML σε PDF χρησιμοποιώντας το Aspose.HTML για .NET σε αυτόν τον πλήρη οδηγό βήμα‑βήμα. +### [Πώς να χρησιμοποιήσετε το Aspose για απόδοση HTML σε εικόνα PNG σε C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Μάθετε πώς να αποδίδετε HTML σε εικόνα PNG χρησιμοποιώντας το Aspose σε C# με βήμα‑βήμα οδηγίες. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/greek/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/greek/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..bdd8f6b65e --- /dev/null +++ b/html/greek/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-10-02 +description: Πώς να χρησιμοποιήσετε το Aspose για γρήγορη απόδοση HTML σε εικόνα PNG + – μάθετε πώς να μετατρέπετε HTML σε PNG με εξομάλυνση και υπόδειξη κειμένου. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: el +lastmod: 2026-10-02 +og_description: Πώς να χρησιμοποιήσετε το Aspose για απόδοση HTML σε εικόνα PNG. Ακολουθήστε + αυτό το πλήρες σεμινάριο για να μετατρέψετε HTML σε PNG με υψηλής ποιότητας απόδοση + σε C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Πώς να χρησιμοποιήσετε το Aspose για τη μετατροπή HTML σε εικόνα PNG – οδηγός + βήμα‑προς‑βήμα +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Πώς να χρησιμοποιήσετε το Aspose για την απόδοση HTML σε εικόνα PNG σε C# +url: /el/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να χρησιμοποιήσετε το Aspose για απόδοση HTML σε εικόνα PNG σε C# + +**How to use Aspose to render HTML to PNG image** είναι μια κοινή απαίτηση όταν χρειάζεστε μια προεπισκόπηση bitmap μιας ιστοσελίδας, μια μικρογραφία email ή ένα στιγμιότυπο φιλικό προς PDF. Αυτό το tutorial σας παρουσιάζει μια πλήρη, έτοιμη προς εκτέλεση λύση που **render html to image** με anti‑aliasing και text hinting, ώστε το αποτέλεσμα να φαίνεται καθαρό σε κάθε πλατφόρμα. + +Θα μάθετε πώς να **convert HTML to PNG**, να διαμορφώσετε τις επιλογές απόδοσης και να αντιμετωπίσετε τυπικά προβλήματα όπως η απόδοση γραμματοσειρών σε Linux και τα δικαιώματα του συστήματος αρχείων. Δεν απαιτούνται εξωτερικά εργαλεία — μόνο η βιβλιοθήκη Aspose.HTML για .NET και μερικές γραμμές C#. + +## Προαπαιτούμενα + +* .NET 6.0 SDK ή νεότερο εγκατεστημένο +* Visual Studio 2022 (ή οποιοδήποτε IDE C#) +* Μια αναφορά NuGet στο **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Βασική εξοικείωση με τη σύνταξη C# + +Αυτές οι προαπαιτήσεις είναι ελαφριές· το tutorial λειτουργεί σε Windows, Linux και macOS επειδή το Aspose.HTML είναι cross‑platform. + +## Βήμα 1: Εγκατάσταση Aspose.HTML και δημιουργία νέου έργου console + +Ανοίξτε ένα τερματικό ή το Package Manager Console και εκτελέστε: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Η δημιουργία ενός αφιερωμένου έργου απομονώνει τις εξαρτήσεις και καθιστά εύκολο το εκτέλεση του δείγματος με `dotnet run`. + +## Βήμα 2: Ρύθμιση επιλογών απόδοσης εικόνας (anti‑aliasing και text hinting) + +Το antialiasing λειαίνει τις άκρες, ενώ το text hinting βελτιώνει την καθαρότητα των γλυφών, ειδικά σε Linux όπου η rasterization των γραμματοσειρών διαφέρει από τα Windows. Η κλάση `ImageRenderingOptions` σας επιτρέπει να ενεργοποιήσετε και τις δύο λειτουργίες: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Why this matters:** Χωρίς antialiasing, οι διαγώνιες γραμμές και οι καμπύλες φαίνονται σκαλισμένες. Χωρίς text hinting, τα μικρά μεγέθη γραμματοσειράς μπορεί να γίνουν θολά, κάτι που γίνεται εμφανές όταν **save html as png** για μικρογραφίες. + +## Βήμα 3: Ορισμός CSS για συνεπείς γραμματοσειρές και στυλ επικεφαλίδων + +Η ενσωμάτωση CSS απευθείας στο HTML εξασφαλίζει ότι η παραγόμενη εικόνα ταιριάζει με τις προσδοκίες του σχεδίου σας. Σε αυτό το παράδειγμα ορίζουμε μια βασική γραμματοσειρά και κάνουμε το `

` πλάγιο: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Μπορείτε να επεκτείνετε το stylesheet με χρώματα, περιθώρια ή media queries. Το CSS εισάγεται στην ετικέτα ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Tip:** Εάν χρειάζεστε **render html as image** από απομακρυσμένη σελίδα, αντικαταστήστε τον κατασκευαστή string με `new HTMLDocument("https://example.com")`. Το Aspose θα κατεβάσει τη σελίδα, θα επιλύσει τους πόρους και θα αποδώσει την τελική διάταξη. + +## Βήμα 5: Απόδοση του εγγράφου σε αρχείο PNG + +Τώρα καλούμε τη `RenderToImage`, περνώντας τη διαδρομή εξόδου και τις επιλογές που διαμορφώσαμε νωρίτερα: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +Το παραγόμενο `output.png` θα περιέχει μια καθαρή απόδοση του στοιχείου `

` με πλάγιο στυλ, χάρη στις ρυθμίσεις anti‑aliasing και hinting. + +## Πλήρης λίστα προγράμματος + +Αντιγράψτε τον παρακάτω κώδικα στο `Program.cs`. Συγκεντρώνεται και εκτελείται όπως είναι: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Αναμενόμενο αποτέλεσμα + +Η εκτέλεση του προγράμματος δημιουργεί το `output.png` στο φάκελο του έργου. Η εικόνα εμφανίζει τη λέξη **Sample** σε πλάγιο Arial, αποδομένη με λειασμένες άκρες και καθαρό κείμενο. Ανοίξτε το αρχείο με οποιονδήποτε προβολέα εικόνων για να επαληθεύσετε την ποιότητα. + +## Βήμα 6: Συνηθισμένες παραλλαγές και διαχείριση ειδικών περιπτώσεων + +| Κατάσταση | Τι να προσαρμόσετε | Αιτία | +|-----------|--------------------|-------| +| **Large HTML pages** | Ορίστε `ImageRenderingOptions.Width` / `Height` ή χρησιμοποιήστε `PageSize` για να ελέγξετε τις διαστάσεις εξόδου | Αποτρέπει την υπερβολική χρήση μνήμης και εξασφαλίζει ότι το PNG ταιριάζει στο UI σας | +| **Linux font missing** | Εγκαταστήστε τις απαιτούμενες γραμματοσειρές στον κεντρικό υπολογιστή (`apt-get install fonts‑arial` ή χρησιμοποιήστε ένα προσαρμοσμένο αρχείο γραμματοσειράς) και κατευθύνετε το Aspose σε αυτήν μέσω `FontSettings` | Χωρίς τη γραμματοσειρά, το Aspose επιστρέφει σε μια γενική, αλλάζοντας την εμφάνιση | +| **Transparent background needed** | Ορίστε `imgOptions.BackgroundColor = Color.Transparent` | Χρήσιμο όταν ενσωματώνετε το PNG σε άλλα γραφικά | +| **Batch conversion** | Κάντε βρόχο πάνω σε μια λίστα HTML strings ή διαδρομές αρχείων, επαναχρησιμοποιώντας το ίδιο αντικείμενο `ImageRenderingOptions` | Βελτιώνει την απόδοση και διατηρεί τις ρυθμίσεις απόδοσης συνεπείς | + +## Pro tip: caching rendering options + +Η δημιουργία ενός νέου αντικειμένου `ImageRenderingOptions` για κάθε μετατροπή προσθέτει επιπλέον φόρτο. Δηλώστε μια στατική παρουσία εάν επεξεργάζεστε πολλά αποσπάσματα HTML σε μια υπηρεσία: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Επαναχρησιμοποιήστε το `SharedOptions` σε κλήσεις για να διατηρήσετε τη χρήση CPU χαμηλή. + +## Συχνές ερωτήσεις + +**Q: Λειτουργεί αυτό με .NET Core σε macOS;** +A: Ναι. Το Aspose.HTML είναι πλήρως cross‑platform. Βεβαιωθείτε ότι οι απαιτούμενες γραμματοσειρές είναι εγκατεστημένες και ότι ο φάκελος εξόδου είναι εγγράψιμος. + +**Q: Μπορώ να αποδώσω σε JPEG αντί για PNG;** +A: Αντικαταστήστε το `RenderToImage("output.png", imgOptions)` με `RenderToImage("output.jpg", imgOptions)`. Μπορείτε επίσης να ορίσετε `imgOptions.ImageFormat = ImageFormat.Jpeg` για πιο ακριβή έλεγχο της ποιότητας. + +**Q: Πώς ενσωματώνω εξωτερικά αρχεία CSS;** +A: Φορτώστε το περιεχόμενο του CSS σε μια string και συνδέστε το, ή αναφέρετε ένα απομακρυσμένο stylesheet στην ετικέτα ``. Το Aspose επιλύει αυτόματα τις ετικέτες `` όταν το έγγραφο φορτώνεται από URL. + +## Συμπέρασμα + +Τώρα γνωρίζετε **πώς να χρησιμοποιήσετε το Aspose** για **render HTML to PNG** (ή οποιαδήποτε άλλη μορφή raster) με ρυθμίσεις υψηλής ποιότητας. Το tutorial κάλυψε την εγκατάσταση του Aspose.HTML, τη διαμόρφωση antialiasing και text hinting, την ενσωμάτωση CSS, τη φόρτωση HTML, και τελικά **saving HTML as PNG**. Ακολουθώντας τα βήματα μπορείτε αξιόπιστα **convert HTML to PNG** σε οποιαδήποτε εφαρμογή .NET, είτε τρέχει σε Windows, Linux ή macOS. + +### Επόμενα βήματα + +* Εξερευνήστε άλλες μορφές εξόδου όπως **render html as image** JPEG ή BMP αλλάζοντας την επέκταση του αρχείου. +* Συνδυάστε αυτήν την προσέγγιση με **Aspose.PDF** για να ενσωματώσετε το PNG σε μια αναφορά PDF. +* Πειραματιστείτε με `ImageRenderingOptions.DpiX` και `DpiY` για μικρογραφίες υψηλής ανάλυσης. + +Νιώστε ελεύθεροι να προσαρμόσετε τον κώδικα για επεξεργασία παρτίδας, δυναμική δημιουργία HTML ή ενσωμάτωση σε μια υπηρεσία web που επιστρέφει προεπισκοπήσεις PNG κατ' απαίτηση. Καλή απόδοση! + +## Τι θα πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 0176d28192..fbcf001b2a 100644 --- a/html/hindi/net/html-extensions-and-conversions/_index.md +++ b/html/hindi/net/html-extensions-and-conversions/_index.md @@ -40,7 +40,7 @@ Aspose.HTML for .NET सिर्फ़ एक लाइब्रेरी न ### [Aspose.HTML के साथ .NET में HTML को PDF में बदलें](./convert-html-to-pdf/) -.NET के लिए Aspose.HTML के साथ HTML को PDF में आसानी से बदलें। हमारे चरण-दर-चरण गाइड का पालन करें और HTML-से-PDF रूपांतरण की शक्ति को प्राप्त करें। +.NET के लिए Aspose.HTML के साथ HTML को PDF में आसानी से बदलें। हमारे चरण-दर-स्टेप गाइड का पालन करें और HTML-से-PDF रूपांतरण की शक्ति को प्राप्त करें। ### [C# में PDF पेज आकार सेट करें – HTML को PDF में बदलें](./set-pdf-page-size-in-c-convert-html-to-pdf/) HTML को PDF में बदलते समय PDF पेज आकार को कस्टमाइज़ करने के लिए चरण‑दर‑चरण मार्गदर्शन। @@ -48,14 +48,14 @@ HTML को PDF में बदलते समय PDF पेज आकार .NET के लिए Aspose.HTML का उपयोग करके C# में HTML को PDF में बदलने की पूरी गाइड। चरण‑दर‑स्टेप निर्देश और कोड उदाहरण। ### [URL से PDF बनाएं – पूर्ण C# गाइड](./create-pdf-from-url-complete-c-guide/) -C# में URL से PDF बनाने की पूरी प्रक्रिया सीखें, चरण-दर-चरण मार्गदर्शिका। +C# में URL से PDF बनाने की पूरी प्रक्रिया सीखें, चरण-दर-स्टेप मार्गदर्शिका। ### [HTML से PDF बनाएं – C# चरण‑दर‑चरण गाइड](./create-pdf-from-html-c-step-by-step-guide/) C# में Aspose.HTML का उपयोग करके HTML को PDF में बदलने का चरण‑दर‑चरण मार्गदर्शन। ### [Aspose के साथ HTML से PDF बनाएं – चरण‑दर‑चरण गाइड](./create-pdf-from-html-with-aspose-step-by-step-guide/) C# में Aspose.HTML का उपयोग करके HTML को PDF में बदलने के विस्तृत चरण‑दर‑चरण मार्गदर्शन। ### [HTML से PDF बनाएं – Aspose.HTML के साथ पूर्ण गाइड](./create-pdf-from-html-complete-guide-with-aspose-html/) -Aspose.HTML के साथ HTML को PDF में बदलने की पूरी गाइड। चरण‑दर‑चरण मार्गदर्शन और कोड उदाहरण। +Aspose.HTML के साथ HTML को PDF में बदलने की पूरी गाइड। चरण‑दर‑स्टेप मार्गदर्शन और कोड उदाहरण। ### [C# में Aspose के साथ HTML से PDF बनाएं – पूर्ण गाइड](./create-pdf-from-html-with-aspose-in-c-full-guide/) .NET के लिए Aspose.HTML का उपयोग करके C# में HTML से PDF बनाने की विस्तृत चरण‑दर‑स्टेप गाइड। कोड उदाहरण और अनुकूलन विकल्प। @@ -76,16 +76,16 @@ C# में Aspose.HTML का उपयोग करके HTML को PDF म .NET के लिए Aspose.HTML का उपयोग करके EPUB को छवियों में परिवर्तित करना सीखें। कोड उदाहरणों और अनुकूलन योग्य विकल्पों के साथ चरण‑दर‑चरण ट्यूटोरियल। ### [Aspose.HTML के साथ .NET में EPUB को PDF में बदलें](./convert-epub-to-pdf/) -जानें कि .NET के लिए Aspose.HTML का उपयोग करके EPUB को PDF में कैसे बदलें। यह चरण-दर-चरण मार्गदर्शिका सहज दस्तावेज़ रूपांतरण के लिए अनुकूलन विकल्प, FAQ और बहुत कुछ शामिल करती है। +जानें कि .NET के लिए Aspose.HTML का उपयोग करके EPUB को PDF में कैसे बदलें। यह चरण‑दर‑चरण मार्गदर्शिका सहज दस्तावेज़ रूपांतरण के लिए अनुकूलन विकल्प, FAQ और बहुत कुछ शामिल करती है। ### [Aspose.HTML के साथ .NET में EPUB को XPS में बदलें](./convert-epub-to-xps/) -.NET के लिए Aspose.HTML का उपयोग करके .NET में EPUB को XPS में कैसे बदलें, यह जानें। सरल रूपांतरण के लिए हमारे चरण-दर-चरण मार्गदर्शिका का पालन करें। +.NET के लिए Aspose.HTML का उपयोग करके .NET में EPUB को XPS में कैसे बदलें, यह जानें। सरल रूपांतरण के लिए हमारे चरण‑दर‑चरण मार्गदर्शिका का पालन करें। ### [Aspose.HTML के साथ .NET में HTML को BMP में बदलें](./convert-html-to-bmp/) .NET के लिए Aspose.HTML का उपयोग करके .NET में HTML को BMP में कैसे बदलें, यह जानें। .NET के लिए Aspose.HTML का लाभ उठाने के लिए वेब डेवलपर्स के लिए व्यापक गाइड। ### [Aspose.HTML के साथ .NET में HTML को DOC और DOCX में बदलें](./convert-html-to-doc-docx/) -इस चरण-दर-स्टेप मार्गदर्शिका में .NET के लिए Aspose.HTML की शक्ति का उपयोग करना सीखें। HTML को DOCX में आसानी से बदलें और अपने .NET प्रोजेक्ट को बेहतर बनाएँ। आज ही शुरू करें! +इस चरण‑दर‑स्टेप मार्गदर्शिका में .NET के लिए Aspose.HTML की शक्ति का उपयोग करना सीखें। HTML को DOCX में आसानी से बदलें और अपने .NET प्रोजेक्ट को बेहतर बनाएँ। आज ही शुरू करें! ### [Aspose.HTML के साथ .NET में HTML को GIF में बदलें](./convert-html-to-gif/) .NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को GIF में बदलने के लिए चरण‑दर‑चरण मार्गदर्शिका। पूर्वापेक्षाएँ, कोड उदाहरण, FAQ, और बहुत कुछ! Aspose.HTML के साथ अपने HTML हेरफेर को अनुकूलित करें। @@ -115,20 +115,20 @@ Aspose.HTML के साथ .NET में HTML को MHTML में बद .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 शामिल हैं। +.NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को XPS में आसानी से बदलें। पूर्वापेक्षाएँ, चरण‑दर‑स्टेप मार्गदर्शिका और FAQ शामिल हैं। ### [C# में HTML को ZIP में सहेजें – पूर्ण इन‑मेमोरी उदाहरण](./save-html-to-zip-in-c-complete-in-memory-example/) C# में इन‑मेमोरी में HTML को ZIP फ़ाइल में सहेजने का पूरा उदाहरण देखें। ### [C# में HTML दस्तावेज़ बनाएं – चरण‑दर‑चरण गाइड](./create-html-document-c-step-by-step-guide/) C# का उपयोग करके Aspose.HTML के साथ HTML दस्तावेज़ बनाने के चरण‑दर‑चरण मार्गदर्शन। ### [Aspose.HTML में हैंडलर का उपयोग कैसे करें – HTML लोड करें, ZIP के रूप में सहेजें](./how-to-use-handler-in-aspose-html-load-html-save-as-zip/) -Aspose.HTML के हैंडलर का उपयोग करके HTML लोड करें और उसे ZIP फ़ाइल में सहेजने के चरण‑दर‑चरण मार्गदर्शन। +Aspose.HTML के हैंडलर का उपयोग करके HTML लोड करें और उसे ZIP फ़ाइल में सहेजने के चरण‑दर‑स्टेप मार्गदर्शन। ### [Aspose HTML सेव विकल्प: C# में HTML को स्ट्रीम में सहेजें](./aspose-html-save-options-save-html-to-stream-in-c/) -C# में Aspose.HTML का उपयोग करके HTML को स्ट्रीम में सहेजने के चरण‑दर‑स्टेप गाइड। +C# में Aspose.HTML का उपयोग करके HTML को स्ट्रीम में सहेजने का चरण‑दर‑स्टेप गाइड। ### [C# में HTML को ज़िप कैसे करें – कस्टम रिसोर्स हैंडलर ट्यूटोरियल](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) -C# में Aspose.HTML का उपयोग करके कस्टम रिसोर्स हैंडलर के साथ HTML को ZIP फ़ाइल में सहेजने का चरण‑दर‑चरण मार्गदर्शन। +C# में Aspose.HTML का उपयोग करके कस्टम रिसोर्स हैंडलर के साथ HTML को ZIP फ़ाइल में सहेजने का चरण‑दर‑स्टेप मार्गदर्शन। ### [C# में HTML को ZIP में सहेजें – पूर्ण गाइड](./save-html-to-zip-in-c-complete-guide/) @@ -136,13 +136,13 @@ C# में Aspose.HTML का उपयोग करके कस्टम र C# का उपयोग करके वेब पेज को एकल HTML फ़ाइल में सहेजने के चरण‑दर‑स्टेप मार्गदर्शन। ### [C# में कस्टम रिसोर्स हैंडलर – HTML को ZIP में बदलें ट्यूटोरियल](./custom-resource-handler-in-c-convert-html-to-zip-tutorial/) -C# में कस्टम रिसोर्स हैंडलर का उपयोग करके HTML को ZIP फ़ाइल में बदलने के चरण‑दर‑चरण मार्गदर्शन। +C# में कस्टम रिसोर्स हैंडलर का उपयोग करके HTML को ZIP फ़ाइल में बदलने का चरण‑दर‑चरण मार्गदर्शन। ### [Aspose.HTML के साथ HTML को PDF में बदलें – पूर्ण चरण‑दर‑चरण गाइड](./convert-html-to-pdf-with-aspose-html-full-step-by-step-guide/) Aspose.HTML के साथ HTML को PDF में आसानी से बदलें। इस पूर्ण चरण‑दर‑चरण गाइड में सभी आवश्यक चरणों को देखें। ### [C# में ज़िप फ़ाइल बनाएं – मेमोरी में HTML को ज़िप करने के लिए चरण-दर-चरण गाइड](./create-zip-file-c-step-by-step-guide-to-zip-html-in-memory/) -.NET के लिए C# में मेमोरी में HTML को ज़िप करने की चरण-दर-चरण प्रक्रिया सीखें। +.NET के लिए C# में मेमोरी में HTML को ज़िप करने की चरण‑दर‑चरण प्रक्रिया सीखें। ### [C# में HTML को ZIP में बदलें – पूर्ण गाइड](./convert-html-to-zip-in-c-complete-guide/) -C# के लिए Aspose.HTML का उपयोग करके HTML को ZIP फ़ाइल में बदलने के चरण-दर-स्टेप मार्गदर्शन। +C# के लिए Aspose.HTML का उपयोग करके HTML को ZIP फ़ाइल में बदलने के चरण‑दर‑स्टेप मार्गदर्शन। ### [C# में HTML को ज़िप करने का पूरा चरण‑दर‑चरण गाइड](./how-to-zip-html-in-c-complete-step-by-step-guide/) C# में Aspose.HTML का उपयोग करके HTML फ़ाइलों को ज़िप करने के चरण‑दर‑चरण निर्देश। सरल और तेज़ प्रक्रिया। ### [C# में HTML को ZIP के रूप में सहेजें – पूर्ण चरण‑दर‑चरण गाइड](./save-html-as-zip-in-c-complete-step-by-step-guide/) @@ -158,7 +158,10 @@ C# में कस्टम रिसोर्स हैंडलर का उ C# में Aspose.HTML का उपयोग करके HTML को ZIP फ़ाइल में सहेजने की पूरी मार्गदर्शिका। चरण‑दर‑चरण कोड उदाहरण और सेटिंग्स। ### [C# में HTML को PDF के रूप में सहेजें – फ़ॉन्ट्स के साथ पूर्ण गाइड](./save-html-as-pdf-in-c-complete-guide-with-fonts/) -C# में Aspose.HTML का उपयोग करके फ़ॉन्ट्स को नियंत्रित करते हुए HTML को PDF में बदलने की पूरी मार्गदर्शिका। +C# में Aspose.HTML का उपयोग करके फ़ॉन्ट्स को नियंत्रित करते हुए HTML को PDF में बदलने की पूरी गाइड। + +### [Aspose.HTML के साथ HTML को ज़िप में सहेजें और छवियों को शामिल करें](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +C# में Aspose.HTML का उपयोग करके HTML को ज़िप फ़ाइल में सहेजें और सभी छवियों को एम्बेड करें। ## निष्कर्ष diff --git a/html/hindi/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/hindi/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..5177c3f471 --- /dev/null +++ b/html/hindi/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,334 @@ +--- +category: general +date: 2026-10-02 +description: Aspose.HTML का उपयोग करके C# में HTML को zip के रूप में कैसे सहेजें, + सीखें। यह गाइड यह भी दिखाता है कि कैसे HTML को इमेजेस के साथ एक ही आर्काइव में सहेजा + जाए। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: hi +lastmod: 2026-10-02 +og_description: Aspose.HTML का उपयोग करके C# में HTML को ज़िप के रूप में सहेजें। इस + पूर्ण ट्यूटोरियल का पालन करके जानें कि कैसे HTML को चित्रों सहित एक ही आर्काइव में + सहेजा जाए। +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Aspose.HTML के साथ HTML को ज़िप के रूप में सहेजें – चरण‑दर‑चरण C# गाइड +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Aspose.HTML के साथ HTML को ज़िप के रूप में सहेजें और छवियों को शामिल करें +url: /hi/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.HTML के साथ HTML को zip के रूप में सहेजें और छवियों को शामिल करें + +यदि आपको आसान वितरण के लिए **HTML को zip के रूप में सहेजना** है, तो यह ट्यूटोरियल Aspose.HTML for .NET का उपयोग करके सटीक कदम दिखाता है। चाहे आप एक स्थिर पेज, ईमेल टेम्पलेट, या छवियों वाले रिपोर्ट को निर्यात कर रहे हों, आप देखेंगे कि कैसे HTML, CSS, और इमेज फ़ाइलों को एक ही ZIP आर्काइव में बंडल किया जाए बिना डिस्क पर अस्थायी फ़ाइलें लिखे। + +मुख्य लक्ष्य के अतिरिक्त, हम सामान्य फॉलो‑अप प्रश्न **HTML को छवियों के साथ कैसे सहेजें** का भी उत्तर देंगे ताकि परिणामी आर्काइव को कोई भी ब्राउज़र बिना किसी रिसोर्स के मिसिंग हुए खोल सके। + +इस गाइड के अंत तक आपके पास एक पुन: उपयोग योग्य `ResourceHandler` इम्प्लीमेंटेशन, एक पूर्ण C# प्रोग्राम जो `output.zip` उत्पन्न करता है, और बड़े इमेज या कस्टम फ़ोल्डर संरचनाओं को संभालने के लिए व्यावहारिक टिप्स होंगी। + +## आवश्यकताएँ + +- .NET 6.0 या बाद का (API .NET Framework 4.6+ के साथ भी काम करता है) +- Aspose.HTML for .NET NuGet पैकेज (`Aspose.Html`) +- C# और स्ट्रीम्स का बेसिक ज्ञान +- Visual Studio 2022 या कोई भी IDE जो .NET विकास को सपोर्ट करता है + +> **Pro tip:** पैकेज को CLI के माध्यम से इंस्टॉल करें ताकि आपका प्रोजेक्ट फ़ाइल साफ़ रहे: +> `dotnet add package Aspose.Html` + +## चरण 1: Aspose.HTML के आउटपुट मॉडल को समझें + +जब Aspose.HTML कोई दस्तावेज़ सहेजता है, तो यह हर बाहरी रिसोर्स (CSS फ़ाइलें, इमेज, फ़ॉन्ट आदि) को एक अलग **resource** के रूप में मानता है। डिफ़ॉल्ट रूप से लाइब्रेरी उन रिसोर्सेज़ को फ़ाइल सिस्टम पर लिखती है। गंतव्य को नियंत्रित करने के लिए आप एक कस्टम `ResourceHandler` प्रदान करते हैं। हैंडलर को एक `Resource` ऑब्जेक्ट मिलता है और उसे एक लिखने योग्य `Stream` लौटाना होता है। फिर Aspose.HTML उस स्ट्रीम में रिसोर्स डेटा लिखता है। + +Using a custom handler lets you: + +- रिसोर्सेज़ को सीधे एक `MemoryStream` में लिखें जो बाद में एक ZIP एंट्री बन जाता है +- रिसोर्सेज़ को डेटाबेस, क्लाउड स्टोरेज, या किसी अन्य माध्यम में स्टोर करें +- फ़ाइल नाम, कंप्रेशन लेवल, या फ़ोल्डर हाइरार्की को समायोजित करें + +## चरण 2: एक `ResourceHandler` बनाएं जो ZIP आर्काइव में लिखता है + +नीचे एक पूरी तरह कार्यात्मक हैंडलर दिया गया है जो मेमोरी में `System.IO.Compression.ZipArchive` बनाता है। प्रत्येक रिसोर्स को एक नई एंट्री के रूप में जोड़ा जाता है जिसका नाम मूल URL पाथ को दर्शाता है, जिससे ZIP निकालने पर ब्राउज़र रिलेटिव लिंक को हल कर सके। + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### यह तरीका क्यों काम करता है + +- **In‑memory operation**: डिस्क पर कोई अस्थायी फ़ाइल नहीं बनाई जाती, जो वेब सर्विसेज़ या सैंडबॉक्स्ड एनवायरनमेंट्स के लिए आदर्श है। +- **Preserves folder hierarchy**: मूल रिसोर्स URI का उपयोग करके, एक्सट्रैक्शन के बाद रिलेटिव रेफ़रेंसेज़ वैध रहती हैं। +- **Extensible**: आप `MemoryStream` को `FileStream` से बदल सकते हैं ताकि सीधे फ़ाइल में लिखा जा सके, या क्लाउड स्टोरेज के लिए नेटवर्क स्ट्रीम से। + +## चरण 3: HTML दस्तावेज़ लोड या बनाएं + +प्रदर्शन के लिए हम एक साधारण HTML स्ट्रिंग बनाएंगे जो एक बाहरी इमेज को रेफ़रेंस करती है। वास्तविक प्रोजेक्ट में आप HTML को फ़ाइल, डेटाबेस, या HTTP रिस्पॉन्स से लोड करेंगे। + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Note:** यदि आपके पास एक वास्तविक HTML फ़ाइल है, तो इसके बजाय `new HTMLDocument("path/to/file.html")` का उपयोग करें। + +## चरण 4: हैंडलर को `SaveOptions` से जोड़ें और ZIP सहेजें + +अब हम `ZipResourceHandler` को `SaveOptions.OutputStorage` से जोड़ते हैं। जब `document.Save` चलता है, तो Aspose.HTML प्रत्येक रिसोर्स के लिए `HandleResource` को कॉल करेगा, और हैंडलर ZIP आर्काइव को भर देगा। + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### अपेक्षित परिणाम + +- `output.zip` में शामिल है: + - `index.html` (मुख्य HTML फ़ाइल) + - `images/logo.png` (मार्कअप में रेफ़रेंस की गई इमेज) + - Aspose.HTML द्वारा स्वचालित रूप से पहचानी गए कोई भी अतिरिक्त CSS या फ़ॉन्ट फ़ाइलें + +जब आप आर्काइव को एक्सट्रैक्ट करके ब्राउज़र में `index.html` खोलते हैं, तो इमेज सही ढंग से दिखती है—जो **HTML को छवियों के साथ ZIP में कैसे सहेजें** को दर्शाता है। + +## चरण 5: आर्काइव को सत्यापित करें और सामान्य समस्याओं का निवारण करें + +### त्वरित सत्यापन स्क्रिप्ट + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +स्क्रिप्ट चलाने पर `index.html` और `images/logo.png` सूचीबद्ध होना चाहिए। यदि कोई अपेक्षित रिसोर्स गायब है: + +- **Check the image URL**: यह HTML दस्तावेज़ से पहुंच योग्य होना चाहिए। रिलेटिव पाथ सबसे बेहतर काम करते हैं। +- **Ensure the resource type is supported**: Aspose.HTML सामान्य वेब फ़ॉर्मैट (PNG, JPEG, GIF, CSS, JS) को संभालता है। असामान्य फ़ॉर्मैट को मैन्युअल रूप से जोड़ना पड़ सकता है। +- **Confirm `HandleResource` is called**: डिबग करने के लिए `HandleResource` के अंदर `Console.WriteLine(resource.Uri)` जोड़ें। + +## चरण 6: उन्नत विविधताएँ + +### 6.1 बाइट एरे के बिना सीधे फ़ाइल में सहेजना + +यदि बहुत बड़े दस्तावेज़ों के लिए मेमोरी उपयोग चिंता का विषय है, तो `MemoryStream` को `FileStream` से बदलें: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +फिर इसे इस तरह उपयोग करें: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 एंट्री नामों को कस्टमाइज़ करना + +यदि आप फ्लैट स्ट्रक्चर (सभी फ़ाइलें रूट पर) पसंद करते हैं, तो `entryName` को समायोजित करें: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 मैनिफेस्ट फ़ाइल जोड़ना + +कभी-कभी डाउनस्ट्रीम टूल्स `manifest.json` की अपेक्षा करते हैं। आप इसे मुख्य सहेजने के बाद जोड़ सकते हैं: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## सामान्य समस्याएँ और उन्हें कैसे टालें + +| समस्या | क्यों होता है | समाधान | +|---------|----------------|-----| +| एक्सट्रैक्शन के बाद छवियाँ टूटी हुई दिखती हैं | HTML के भीतर इमेज पाथ ZIP एंट्री नाम से मेल नहीं खाता। | `ZipArchiveEntry` बनाते समय मूल रिलेटिव पाथ को संरक्षित रखें। | +| बड़ी छवियों से मेमोरी समाप्ति अपवाद होते हैं | बहुत बड़ी फ़ाइलों के लिए `MemoryStream` का उपयोग प्रक्रिया की मेमोरी सीमा से अधिक हो सकता है। | `FileStream`‑आधारित हैंडलर पर स्विच करें (देखें 6.1)। | +| CSS URLs गायब हैं | `@import` द्वारा रेफ़रेंस किए गए बाहरी CSS फ़ाइलें स्वचालित रूप से नहीं पहचानी जातीं। | इन CSS फ़ाइलों को मैन्युअल रूप से ZIP में जोड़ें या सहेजने से पहले इनलाइन एम्बेड करें। | +| Unicode अक्षर गड़बड़ हो जाते हैं | डिफ़ॉल्ट एन्कोडिंग HTML स्रोत और स्ट्रीम के बीच अलग हो सकती है। | सुनिश्चित करें कि HTML स्ट्रिंग UTF‑8 है; Aspose.HTML दस्तावेज़ की charset का सम्मान करता है। | + +## पूर्ण कार्यशील उदाहरण (कॉपी‑पेस्ट तैयार) + + + +## अब आप आगे क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स निकट संबंधित विषयों को कवर करते हैं जो इस गाइड में प्रदर्शित तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण-दर-चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन दृष्टिकोणों की खोज करने में मदद करेंगे। + +- [Aspose.HTML में हैंडलर का उपयोग कैसे करें – HTML लोड करें, ZIP के रूप में सहेजें](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [C# में HTML कैसे सहेजें – कस्टम रिसोर्स हैंडलर्स और ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [C# के साथ HTML को PNG में रेंडर करें और ZIP में सहेजें – पूर्ण गाइड](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 c59af08e48..46d2294c70 100644 --- a/html/hindi/net/rendering-html-documents/_index.md +++ b/html/hindi/net/rendering-html-documents/_index.md @@ -66,7 +66,7 @@ C# में Aspose.HTML का उपयोग करके HTML पैरा ### [HTML को रेंडर करने का तरीका – कस्टम रिसोर्स हैंडलर के साथ पूर्ण गाइड](./how-to-render-html-complete-guide-with-custom-resource-handl/) कस्टम रिसोर्स हैंडलर के साथ HTML रेंडर करने की पूरी प्रक्रिया सीखें। ### [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 फ़ॉर्मेट में बदलने की पूरी प्रक्रिया सीखें, कोड उदाहरण और टिप्स के साथ। @@ -84,6 +84,9 @@ C# में HTML दस्तावेज़ बनाकर, बोल्ड ### [C# में Aspose का उपयोग करके HTML को PNG में रेंडर करने का तरीका](./how-to-use-aspose-to-render-html-to-png-in-c/) C# में Aspose.HTML का उपयोग करके HTML को PNG इमेज में बदलने की प्रक्रिया सीखें। +### [C# में Aspose का उपयोग करके HTML को PNG इमेज में रेंडर करने का तरीका](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +C# में Aspose.HTML का उपयोग करके HTML को PNG इमेज में बदलने की पूरी प्रक्रिया सीखें। + ### [C# के साथ HTML को इमेज में रेंडर करने का तरीका – पूर्ण गाइड](./how-to-render-html-to-an-image-with-c-complete-guide/) C# में Aspose.HTML का उपयोग करके HTML को इमेज में बदलने की पूरी प्रक्रिया सीखें। diff --git a/html/hindi/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/hindi/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..f474ca5cfa --- /dev/null +++ b/html/hindi/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-10-02 +description: Aspose का उपयोग करके HTML को PNG छवि में तेज़ी से रेंडर करना – एंटी‑एलियासिंग + और टेक्स्ट हिन्टिंग के साथ HTML को PNG में बदलना सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: hi +lastmod: 2026-10-02 +og_description: Aspose का उपयोग करके HTML को PNG इमेज में रेंडर करने का तरीका। C# + में उच्च‑गुणवत्ता वाले रेंडरिंग के साथ HTML को PNG में बदलने के लिए इस पूर्ण ट्यूटोरियल + का पालन करें। +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Aspose का उपयोग करके HTML को PNG छवि में रेंडर करने की चरण-दर-चरण गाइड +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: C# में Aspose का उपयोग करके HTML को PNG इमेज में रेंडर कैसे करें +url: /hi/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose का उपयोग करके C# में HTML को PNG इमेज में रेंडर करना + +**Aspose का उपयोग करके HTML को PNG इमेज में रेंडर करने का तरीका** एक सामान्य आवश्यकता है जब आपको वेब पेज का बिटमैप प्रीव्यू, ईमेल थंबनेल, या PDF‑फ्रेंडली स्नैपशॉट चाहिए। यह ट्यूटोरियल आपको एक पूर्ण, तैयार‑चलाने योग्य समाधान दिखाता है जो **HTML को इमेज में रेंडर** करता है, एंटी‑एलियासिंग और टेक्स्ट हिन्टिंग के साथ, ताकि परिणाम हर प्लेटफ़ॉर्म पर तेज़ दिखे। + +आप सीखेंगे कि **HTML को PNG में कैसे बदलें**, रेंडरिंग विकल्प कैसे कॉन्फ़िगर करें, और लिनक्स फ़ॉन्ट रेंडरिंग और फ़ाइल‑सिस्टम अनुमतियों जैसे सामान्य समस्याओं को कैसे संभालें। कोई बाहरी टूल आवश्यक नहीं—सिर्फ Aspose.HTML for .NET लाइब्रेरी और कुछ ही C# लाइनों की ज़रूरत है। + +## Prerequisites + +शुरू करने से पहले सुनिश्चित करें कि आपके पास है: + +* .NET 6.0 SDK या बाद का संस्करण स्थापित +* Visual Studio 2022 (या कोई भी C# IDE) +* **Aspose.HTML** का NuGet रेफ़रेंस (`Install-Package Aspose.HTML`) +* C# सिंटैक्स की बुनियादी जानकारी + +ये प्री‑रिक्विज़िट हल्के हैं; ट्यूटोरियल Windows, Linux, और macOS पर काम करता है क्योंकि Aspose.HTML क्रॉस‑प्लेटफ़ॉर्म है। + +## Step 1: Install Aspose.HTML and create a new console project + +टर्मिनल या पैकेज मैनेजर कंसोल खोलें और चलाएँ: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +एक समर्पित प्रोजेक्ट बनाने से डिपेंडेंसीज़ अलग रहती हैं और `dotnet run` के साथ सैंपल चलाना आसान हो जाता है। + +## Step 2: Set up image rendering options (anti‑aliasing and text hinting) + +एंटी‑एलियासिंग किनारों को स्मूद करता है, जबकि टेक्स्ट हिन्टिंग glyph की स्पष्टता बढ़ाता है, विशेषकर लिनक्स पर जहाँ फ़ॉन्ट रास्टराइज़ेशन विंडोज़ से अलग होता है। `ImageRenderingOptions` क्लास दोनों फीचर को सक्षम करने की अनुमति देती है: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**यह क्यों महत्वपूर्ण है:** एंटी‑एलियासिंग के बिना, तिरछी लाइनों और कर्व्स में जगरड दिखेगा। टेक्स्ट हिन्टिंग के बिना, छोटे फ़ॉन्ट साइज ब्लरी हो सकते हैं, जो थंबनेल के लिए **HTML को PNG के रूप में सेव** करते समय स्पष्ट दिखता है। + +## Step 3: Define CSS for consistent fonts and heading styles + +HTML में सीधे CSS एम्बेड करने से रेंडर की गई इमेज आपके डिज़ाइन अपेक्षाओं से मेल खाती है। इस उदाहरण में हम बेस फ़ॉन्ट सेट करते हैं और `

` को इटैलिक बनाते हैं: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +आप स्टाइलशीट में रंग, मार्जिन, या मीडिया क्वेरीज़ जोड़ सकते हैं। CSS को HTML दस्तावेज़ के ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**टिप:** यदि आपको रिमोट पेज से **HTML को इमेज के रूप में रेंडर** करना है, तो स्ट्रिंग कंस्ट्रक्टर को `new HTMLDocument("https://example.com")` से बदलें। Aspose पेज डाउनलोड करेगा, रिसोर्सेज़ को रिज़ॉल्व करेगा, और अंतिम लेआउट रेंडर करेगा। + +## Step 5: Render the document to a PNG file + +अब हम `RenderToImage` को कॉल करते हैं, आउटपुट पाथ और पहले कॉन्फ़िगर किए गए विकल्प पास करते हैं: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +जनरेट किया गया `output.png` `

` एलिमेंट को इटैलिक स्टाइलिंग के साथ एक स्पष्ट रेंडरिंग रखेगा, एंटी‑एलियासिंग और हिन्टिंग सेटिंग्स के कारण। + +## Full program listing + +निम्न कोड को `Program.cs` में कॉपी करें। यह जैसा है वैसा ही कंपाइल और रन होगा: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Expected output + +प्रोग्राम चलाने से प्रोजेक्ट फ़ोल्डर में `output.png` बनता है। इमेज में **Sample** शब्द इटैलिक Arial में, स्मूद एजेज़ और स्पष्ट टेक्स्ट के साथ दिखता है। गुणवत्ता की जाँच के लिए किसी भी इमेज व्यूअर से फ़ाइल खोलें। + +## Step 6: Common variations and edge‑case handling + +| Situation | What to adjust | Reason | +|-----------|----------------|--------| +| **Large HTML pages** | `ImageRenderingOptions.Width` / `Height` सेट करें या `PageSize` का उपयोग करके आउटपुट डाइमेंशन नियंत्रित करें | मेमोरी ओवरफ़्लो से बचाता है और PNG आपके UI में फिट बैठता है | +| **Linux font missing** | होस्ट पर आवश्यक फ़ॉन्ट इंस्टॉल करें (`apt-get install fonts‑arial` या कस्टम फ़ॉन्ट फ़ाइल उपयोग करें) और `FontSettings` के माध्यम से Aspose को बताएं | फ़ॉन्ट न मिलने पर Aspose जनरिक फ़ॉन्ट पर फ़ॉलबैक करता है, जिससे लुक बदल जाता है | +| **Transparent background needed** | `imgOptions.BackgroundColor = Color.Transparent` सेट करें | PNG को अन्य ग्राफ़िक्स में एम्बेड करने के समय उपयोगी | +| **Batch conversion** | HTML स्ट्रिंग्स या फ़ाइल पाथ्स की लिस्ट पर लूप चलाएँ, वही `ImageRenderingOptions` ऑब्जेक्ट पुन: उपयोग करें | परफ़ॉर्मेंस बढ़ाता है और रेंडरिंग सेटिंग्स को स्थिर रखता है | + +## Pro tip: caching rendering options + +हर कन्वर्ज़न के लिए नया `ImageRenderingOptions` ऑब्जेक्ट बनाना ओवरहेड जोड़ता है। यदि आप सर्विस में कई HTML स्निपेट्स प्रोसेस करते हैं तो एक static इंस्टेंस डिक्लेयर करें: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +कॉल्स के बीच `SharedOptions` को री‑यूज़ करने से CPU उपयोग कम रहता है। + +## Frequently asked questions + +**Q: क्या यह macOS पर .NET Core के साथ काम करता है?** +A: हाँ। Aspose.HTML पूरी तरह से क्रॉस‑प्लेटफ़ॉर्म है। आवश्यक फ़ॉन्ट्स इंस्टॉल करें, और आउटपुट डायरेक्टरी लिखने योग्य होनी चाहिए। + +**Q: क्या मैं PNG की बजाय JPEG रेंडर कर सकता हूँ?** +A: `RenderToImage("output.png", imgOptions)` को `RenderToImage("output.jpg", imgOptions)` से बदलें। आप `imgOptions.ImageFormat = ImageFormat.Jpeg` भी सेट कर सकते हैं ताकि क्वालिटी पर बेहतर नियंत्रण मिले। + +**Q: मैं बाहरी CSS फ़ाइलें कैसे एम्बेड करूँ?** +A: CSS कंटेंट को स्ट्रिंग में लोड करके कंकैटनेट करें, या `` टैग में रिमोट स्टाइलशीट रेफ़रेंस दें। Aspose URL से डॉक्यूमेंट लोड होने पर `` टैग को ऑटोमैटिकली रिज़ॉल्व करता है। + +## Conclusion + +अब आप जानते हैं **Aspose का उपयोग करके** **HTML को PNG** (या किसी भी अन्य रास्टर फ़ॉर्मेट) में हाई‑क्वालिटी सेटिंग्स के साथ कैसे रेंडर करें। ट्यूटोरियल ने Aspose.HTML को इंस्टॉल करना, एंटी‑एलियासिंग और टेक्स्ट हिन्टिंग कॉन्फ़िगर करना, CSS इन्जेक्ट करना, HTML लोड करना, और अंत में **HTML को PNG के रूप में सेव** करना कवर किया। इन स्टेप्स को फॉलो करके आप किसी भी .NET एप्लिकेशन में, चाहे वह Windows, Linux, या macOS पर चल रहा हो, भरोसेमंद **HTML को PNG में बदल** सकते हैं। + +### Next steps + +* **render html as image** JPEG या BMP जैसे अन्य आउटपुट फ़ॉर्मेट को फ़ाइल एक्सटेंशन बदलकर एक्सप्लोर करें। +* इस एप्रोच को **Aspose.PDF** के साथ मिलाकर PNG को PDF रिपोर्ट में एम्बेड करें। +* हाई‑रेज़ोल्यूशन थंबनेल्स के लिए `ImageRenderingOptions.DpiX` और `DpiY` के साथ प्रयोग करें। + +कोड को बैच प्रोसेसिंग, डायनामिक HTML जनरेशन, या वेब सर्विस में इंटीग्रेट करने के लिए एडेप्ट करने में संकोच न करें जो ऑन‑डिमांड PNG प्रीव्यू रिटर्न करता है। Happy rendering! + +## What Should You Learn Next? + +नीचे दिए गए ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक रिसोर्स में पूर्ण कार्यशील कोड उदाहरण और स्टेप‑बाय‑स्टेप व्याख्याएँ हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकते हैं और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोचेज़ को एक्सप्लोर कर सकते हैं। + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 adef586419..69eaae4323 100644 --- a/html/hongkong/net/html-extensions-and-conversions/_index.md +++ b/html/hongkong/net/html-extensions-and-conversions/_index.md @@ -132,6 +132,9 @@ Aspose.HTML for .NET 不只是一個函式庫;它還是一個函式庫。它 ### [在 C# 中將 HTML 儲存為 ZIP – 完整指南](./save-html-as-zip-in-c-complete-guide/) 使用 Aspose.HTML for .NET 在 C# 中將 HTML 儲存為 ZIP,提供完整步驟與範例說明。 +### [如何使用 Aspose.HTML 將 HTML 儲存為 ZIP 並包含圖像](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +說明如何使用 Aspose.HTML 將 HTML 及其相關圖像壓縮為 ZIP 檔案的完整步驟。 + ### [在 C# 中將 HTML 儲存為 PDF – 完整指南(含字型)](./save-html-as-pdf-in-c-complete-guide-with-fonts/) 使用 Aspose.HTML for .NET,在 C# 中將 HTML 轉換為 PDF,並嵌入自訂字型的完整步驟說明。 ### [在 C# 中設定 PDF 頁面大小 – 轉換 HTML 為 PDF](./set-pdf-page-size-in-c-convert-html-to-pdf/) diff --git a/html/hongkong/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/hongkong/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..54442ffb32 --- /dev/null +++ b/html/hongkong/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,330 @@ +--- +category: general +date: 2026-10-02 +description: 學習如何在 C# 中使用 Aspose.HTML 將 HTML 儲存為 zip。本指南亦說明如何將包含圖片的 HTML 儲存於單一壓縮檔中。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: zh-hant +lastmod: 2026-10-02 +og_description: 使用 Aspose.HTML 在 C# 中將 HTML 儲存為 zip。跟隨本完整教學,了解如何將含圖片的 HTML 儲存為單一壓縮檔。 +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: 使用 Aspose.HTML 將 HTML 儲存為 zip 檔案 – C# 步驟教學 +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: 如何使用 Aspose.HTML 將 HTML 儲存為 zip 並包含圖像 +url: /zh-hant/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何使用 Aspose.HTML 將 HTML 儲存為 zip 並包含圖像 + +如果您需要 **將 HTML 儲存為 zip** 以便輕鬆分發,本教學將示範使用 Aspose.HTML for .NET 的具體步驟。無論您是匯出靜態頁面、電子郵件範本,或是包含圖像的報告,您都會看到如何將 HTML、CSS 及圖像檔案打包成單一 ZIP 壓縮檔,而不必寫入暫存檔至磁碟。 + +除了主要目標外,我們還會回答常見的後續問題 **如何將 HTML 與圖像一起儲存**,使產生的壓縮檔能在任何瀏覽器中開啟且不會缺少資源。 + +閱讀完本指南後,您將擁有可重複使用的 `ResourceHandler` 實作、產生 `output.zip` 的完整 C# 程式,以及處理大型圖像或自訂資料夾結構的實用技巧。 + +## 前置條件 + +- .NET 6.0 或更新版本(此 API 亦支援 .NET Framework 4.6+) +- Aspose.HTML for .NET NuGet 套件 (`Aspose.Html`) +- 具備 C# 與串流的基本知識 +- Visual Studio 2022 或任何支援 .NET 開發的 IDE + +> **專業提示:** 安裝套件時使用 CLI,以保持專案檔案乾淨: +> `dotnet add package Aspose.Html` + +## 步驟 1:了解 Aspose.HTML 的輸出模型 + +當 Aspose.HTML 儲存文件時,它會將每個外部資源(CSS 檔案、圖像、字型等)視為單獨的 **resource**。預設情況下,函式庫會將這些資源寫入檔案系統。若要控制目的地,您需要提供自訂的 `ResourceHandler`。此處理程式會接收一個 `Resource` 物件,並必須回傳可寫入的 `Stream`。Aspose.HTML 隨後會將資源資料寫入該串流。 + +使用自訂處理程式可讓您: + +- 直接將資源寫入 `MemoryStream`,之後可作為 ZIP 條目 +- 將資源儲存於資料庫、雲端儲存或其他任何媒介 +- 調整檔名、壓縮等級或資料夾階層 + +## 步驟 2:建立寫入 ZIP 壓縮檔的 `ResourceHandler` + +以下是一個完整可用的處理程式,於記憶體中建立 `System.IO.Compression.ZipArchive`。每個資源皆以新條目加入,條目名稱會鏡像原始 URL 路徑,確保在解壓縮 ZIP 後瀏覽器能正確解析相對連結。 + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### 為何此方法可行 + +- **In‑memory operation**:不會在磁碟上產生暫存檔,適用於 Web 服務或沙盒環境。 +- **Preserves folder hierarchy**:使用原始資源 URI,可在解壓縮後保持相對參照的有效性。 +- **Extensible**:您可以將 `MemoryStream` 替換為 `FileStream` 直接寫入檔案,或使用網路串流寫入雲端儲存。 + +## 步驟 3:載入或建立 HTML 文件 + +為了示範,我們會建立一段簡單的 HTML 字串,內含對外部圖像的引用。在實際專案中,您會從檔案、資料庫或 HTTP 回應載入 HTML。 + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **注意:** 若您有實體的 HTML 檔案,請改用 `new HTMLDocument("path/to/file.html")`。 + +## 步驟 4:將處理程式連接至 `SaveOptions` 並儲存 ZIP + +現在我們將 `ZipResourceHandler` 連接至 `SaveOptions.OutputStorage`。當執行 `document.Save` 時,Aspose.HTML 會為每個資源呼叫 `HandleResource`,而處理程式則會填充 ZIP 壓縮檔。 + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### 預期結果 + +- `output.zip` 包含: + - `index.html`(主要的 HTML 檔案) + - `images/logo.png`(標記中引用的圖像) + - 任何 Aspose.HTML 自動偵測的額外 CSS 或字型檔案 + +當您解壓縮檔案並在瀏覽器中開啟 `index.html` 時,圖像會正確顯示——示範了 **如何將 HTML 與圖像一起儲存** 在 ZIP 中。 + +## 步驟 5:驗證壓縮檔並排除常見問題 + +### 快速驗證腳本 + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +執行此腳本應會列出 `index.html` 與 `images/logo.png`。若缺少預期的資源: + +- **Check the image URL**:必須能從 HTML 文件取得。相對路徑效果最佳。 +- **Ensure the resource type is supported**:Aspose.HTML 支援常見的網頁格式(PNG、JPEG、GIF、CSS、JS)。不常見的格式可能需要手動加入。 +- **Confirm `HandleResource` is called**:在 `HandleResource` 內加入 `Console.WriteLine(resource.Uri)` 以進行除錯。 + +## 步驟 6:進階變化 + +### 6.1 直接儲存至檔案而不使用中介位元組陣列 + +如果大型文件的記憶體使用量是個問題,請將 `MemoryStream` 替換為 `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +然後這樣使用: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 自訂條目名稱 + +如果您偏好平面結構(所有檔案位於根目錄),請調整 `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 新增 manifest 檔案 + +有時下游工具會期待 `manifest.json`。您可以在主要儲存之後加入它: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## 常見陷阱與避免方法 + +| 陷阱 | 發生原因 | 解決方法 | +|------|----------|----------| +| 解壓縮後圖像顯示破損 | HTML 中的圖像路徑與 ZIP 條目名稱不符。 | 在建立 `ZipArchiveEntry` 時保留原始相對路徑。 | +| 大型圖像導致記憶體不足例外 | 對於非常大的檔案使用 `MemoryStream` 可能超過程序的記憶體上限。 | 改用基於 `FileStream` 的處理程式(參見 6.1)。 | +| CSS URL 缺失 | 透過 `@import` 引用的外部 CSS 檔案不會被自動偵測。 | 手動將這些 CSS 檔案加入 ZIP,或在儲存前內嵌於 HTML。 | +| Unicode 字元變成亂碼 | 預設編碼可能與 HTML 原始碼或串流的編碼不同。 | 確保 HTML 字串為 UTF‑8;Aspose.HTML 會遵循文件的字符集。 | + +## 完整可執行範例(可直接複製貼上) + + + +## 接下來該學什麼? + +以下教學涵蓋與本指南緊密相關的主題,建立在本指南所示技術之上。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助您精通其他 API 功能,並在自己的專案中探索替代實作方式。 + +- [如何在 Aspose.HTML 中使用處理程式 – 載入 HTML,儲存為 ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [如何在 C# 中儲存 HTML – 自訂資源處理程式與 ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [使用 C# 將 HTML 轉為 PNG 並儲存為 ZIP – 完整指南](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 d9ac6d90ad..36f04b1d47 100644 --- a/html/hongkong/net/rendering-html-documents/_index.md +++ b/html/hongkong/net/rendering-html-documents/_index.md @@ -105,6 +105,9 @@ Aspose.HTML for .NET 因其豐富的功能、優秀的文件和活躍的社群 ### [如何使用 Aspose 將 HTML 渲染為 PDF – 步驟指南](./render-html-to-pdf-with-aspose-html-step-by-step-guide/) 一步步教您使用 Aspose.HTML for .NET 將 HTML 轉換為 PDF,掌握渲染技巧與設定。 +### [如何在 C# 中使用 Aspose 將 HTML 渲染為 PNG 圖像](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +一步步教您在 C# 中使用 Aspose.HTML 將 HTML 轉換為 PNG 圖像,掌握關鍵設定與最佳實踐。 + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/hongkong/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/hongkong/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..796efa1e97 --- /dev/null +++ b/html/hongkong/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-10-02 +description: 如何快速使用 Aspose 將 HTML 渲染為 PNG 圖像 – 學習使用抗鋸齒與文字提示將 HTML 轉換為 PNG。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: zh-hant +lastmod: 2026-10-02 +og_description: 如何使用 Aspose 將 HTML 渲染為 PNG 圖像。跟隨本完整教程,使用 C# 將 HTML 轉換為高品質的 PNG。 +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: 如何使用 Aspose 將 HTML 渲染為 PNG 圖片 – 步驟指南 +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: 如何在 C# 中使用 Aspose 將 HTML 渲染為 PNG 圖像 +url: /zh-hant/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 C# 中使用 Aspose 將 HTML 渲染為 PNG 圖像 + +**How to use Aspose to render HTML to PNG image** 是在需要網頁位圖預覽、電子郵件縮圖或適合 PDF 的快照時的常見需求。本教學展示一個完整、可直接執行的解決方案,能夠 **render html to image** 並使用抗鋸齒與文字 hinting,使結果在各平台上都保持銳利。 + +您將學會如何 **convert HTML to PNG**、設定渲染選項,並處理常見的問題,例如 Linux 字型渲染與檔案系統權限。無需外部工具——只需 Aspose.HTML for .NET 函式庫以及少量 C# 程式碼。 + +## 前置條件 + +* .NET 6.0 SDK 或更新版本已安裝 +* Visual Studio 2022(或任何 C# IDE) +* NuGet 參考 **Aspose.HTML** (`Install-Package Aspose.HTML`) +* 基本熟悉 C# 語法 + +這些前置條件相當輕量;本教學可在 Windows、Linux 與 macOS 上執行,因為 Aspose.HTML 支援跨平台。 + +## 步驟 1:安裝 Aspose.HTML 並建立新 Console 專案 + +在終端機或套件管理員主控台中開啟,執行以下指令: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +建立獨立的專案可將相依性隔離,並能輕鬆使用 `dotnet run` 執行範例。 + +## 步驟 2:設定影像渲染選項(抗鋸齒與文字 hinting) + +抗鋸齒可平滑邊緣,而文字 hinting 能提升字形清晰度,特別是在字型光柵化與 Windows 不同的 Linux 上。`ImageRenderingOptions` 類別可讓您同時啟用這兩項功能: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**為何重要:** 若未使用抗鋸齒,對角線與曲線會顯得鋸齒狀。若未使用文字 hinting,小字體尺寸可能變得模糊,這在您 **save html as png** 用於縮圖時尤為明顯。 + +## 步驟 3:定義 CSS 以確保字型與標題樣式一致 + +將 CSS 直接嵌入 HTML 可確保渲染出的影像符合設計預期。在此範例中,我們設定基礎字型並將 `

` 設為斜體: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +您可以在樣式表中加入顏色、邊距或媒體查詢。這段 CSS 會注入至 HTML 文件的 ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**提示:** 若需從遠端頁面 **render html as image**,請將字串建構子改為 `new HTMLDocument("https://example.com")`。Aspose 會下載該頁面、解析資源,並渲染最終版面。 + +## 步驟 5:將文件渲染為 PNG 檔案 + +現在呼叫 `RenderToImage`,傳入輸出路徑以及先前設定的選項: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +產生的 `output.png` 會包含帶有斜體樣式的 `

` 元素的清晰渲染,這得益於抗鋸齒與 hinting 設定。 + +## 完整程式碼清單 + +將以下程式碼複製到 `Program.cs` 中,即可直接編譯執行: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### 預期輸出 + +執行程式後會在專案資料夾產生 `output.png`。影像顯示斜體 Arial 的 **Sample** 文字,邊緣平滑且文字清晰。使用任何影像檢視器開啟檔案即可驗證品質。 + +## 步驟 6:常見變體與邊緣案例處理 + +| 情況 | 調整方式 | 原因 | +|-----------|----------------|--------| +| **大型 HTML 頁面** | 設定 `ImageRenderingOptions.Width` / `Height` 或使用 `PageSize` 以控制輸出尺寸 | 防止記憶體暴增,並確保 PNG 符合 UI 需求 | +| **Linux 缺少字型** | 在主機上安裝所需字型(`apt-get install fonts‑arial` 或使用自訂字型檔),並透過 `FontSettings` 指定給 Aspose | 若缺少字型,Aspose 會退回使用通用字型,導致外觀改變 | +| **需要透明背景** | 設定 `imgOptions.BackgroundColor = Color.Transparent` | 在將 PNG 嵌入其他圖形時很有用 | +| **批次轉換** | 迭代 HTML 字串或檔案路徑清單,重複使用相同的 `ImageRenderingOptions` 物件 | 提升效能並保持渲染設定一致 | + +## 專業提示:快取渲染選項 + +為每次轉換建立新的 `ImageRenderingOptions` 物件會增加額外開銷。若在服務中處理大量 HTML 片段,可宣告為 static 實例: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +在多次呼叫間重複使用 `SharedOptions`,可降低 CPU 使用率。 + +## 常見問題 + +**Q: 這在 macOS 上的 .NET Core 能運作嗎?** +A: 可以。Aspose.HTML 完全支援跨平台。請確保已安裝所需字型,且輸出目錄具寫入權限。 + +**Q: 我可以渲染成 JPEG 而非 PNG 嗎?** +A: 將 `RenderToImage("output.png", imgOptions)` 改為 `RenderToImage("output.jpg", imgOptions)`。亦可設定 `imgOptions.ImageFormat = ImageFormat.Jpeg` 以更細緻地控制品質。 + +**Q: 如何嵌入外部 CSS 檔案?** +A: 將 CSS 內容載入為字串並串接,或在 `` 標籤中引用遠端樣式表。當文件從 URL 載入時,Aspose 會自動解析 `` 標籤。 + +## 結論 + +現在您已了解 **how to use Aspose** 以高品質設定 **render HTML to PNG**(或其他點陣格式)。本教學涵蓋了安裝 Aspose.HTML、設定抗鋸齒與文字 hinting、注入 CSS、載入 HTML,最後 **save HTML as PNG**。依循這些步驟,即可在任何 .NET 應用程式中可靠地 **convert HTML to PNG**,無論執行於 Windows、Linux 或 macOS。 + +### 後續步驟 + +* 探索其他輸出格式,例如透過更改副檔名將 **render html as image** 產出為 JPEG 或 BMP。 +* 結合 **Aspose.PDF**,將 PNG 嵌入 PDF 報告中。 +* 嘗試調整 `ImageRenderingOptions.DpiX` 與 `DpiY`,以產生高解析度縮圖。 + +歡迎自行調整程式碼以支援批次處理、動態 HTML 產生,或整合至即時回傳 PNG 預覽的 Web 服務。祝渲染愉快! + +## 接下來您可以學習什麼? + +以下教學涵蓋與本指南密切相關的主題,並以此為基礎延伸。每篇資源皆提供完整可執行的程式碼範例與逐步說明,協助您精通更多 API 功能,並在專案中探索其他實作方式。 + +- [如何使用 Aspose 渲染 HTML 為 PNG – 步驟指南](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [如何使用 Aspose 渲染 HTML 為 PNG – 完整指南](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image 教學 – 使用 Aspose.HTML 在 C# 中渲染 HTML 為 PNG](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 13d9837ec9..923f47ed64 100644 --- a/html/hungarian/net/html-extensions-and-conversions/_index.md +++ b/html/hungarian/net/html-extensions-and-conversions/_index.md @@ -62,7 +62,7 @@ Lépésről‑lépésre útmutató a HTML PDF‑re konvertálásához C#‑ban, ### [HTML zip-elése C#-ban – HTML mentése zip-be](./how-to-zip-html-in-c-save-html-to-zip/) Ismerje meg, hogyan csomagolhatja be a HTML-fájlokat zip-archívumba C#-ban az Aspose.HTML for .NET segítségével. ### [HTML-dokumentum létrehozása formázott szöveggel és exportálása PDF-be – Teljes útmutató](./create-html-document-with-styled-text-and-export-to-pdf-full/) -Hozzon létre HTML-dokumentumot formázott szöveggel, majd exportálja PDF-be az Aspose.HTML for .NET segítségével. Lépésről lépésre útmutató. +Hozzon létre HTML-dokumentumot formázott szöveggel, majd exportálja PDF-be az Aspose.HTML for .NET segítségével. Lépésről‑lépésre útmutató. ### [PDF létrehozása HTML-ből – C# lépésről‑lépésre útmutató](./create-pdf-from-html-c-step-by-step-guide/) Ismerje meg, hogyan hozhat létre PDF-et HTML-ből C#‑ban az Aspose.HTML for .NET segítségével, részletes lépésről‑lépésre útmutatóval. ### [HTML-ből PDF létrehozása Aspose-szal C#‑ban – Teljes útmutató](./create-pdf-from-html-with-aspose-in-c-full-guide/) @@ -91,13 +91,13 @@ Megmutatjuk, hogyan menthet HTML-t közvetlenül memóriaáramba az Aspose.HTML ### [Egyéni erőforráskezelő C#‑ban – HTML konvertálása ZIP‑archívumba memóriából](./custom-resource-handler-in-c-convert-html-to-zip-archive-fro/) Ismerje meg, hogyan használhat egyéni erőforráskezelőt C#‑ban a HTML memóriában történő ZIP‑archívumba konvertálásához az Aspose.HTML for .NET segítségével. ### [HTML zip-elése C#-ban – HTML betöltése és egyéni kezelő használata](./how-to-zip-html-in-c-load-html-use-custom-handler/) -### [Egyéni erőforráskezelő C#-ban – HTML ZIP-be konvertálása oktatóanyag](./custom-resource-handler-in-c-convert-html-to-zip-tutorial/) +### [Egyéni erőforráskezelő C#‑ban – HTML ZIP-be konvertálása oktatóanyag](./custom-resource-handler-in-c-convert-html-to-zip-tutorial/) Ismerje meg, hogyan használhat egyéni erőforráskezelőt a HTML ZIP-archívumba konvertálásához C#-ban az Aspose.HTML for .NET segítségével. ### [HTML konvertálása PDF-be az Aspose.HTML segítségével – Teljes lépésről‑lépésre útmutató](./convert-html-to-pdf-with-aspose-html-full-step-by-step-guide/) Részletes útmutató a HTML PDF-be konvertálásához az Aspose.HTML for .NET használatával, lépésről‑lépésre példákkal. ### [Zip fájl létrehozása C# – Lépésről‑lépésre útmutató a HTML memóriában történő tömörítéséhez](./create-zip-file-c-step-by-step-guide-to-zip-html-in-memory/) ### [HTML konvertálása ZIP-be C#-ban – Teljes útmutató](./convert-html-to-zip-in-c-complete-guide/) -Ismerje meg, hogyan konvertálhat HTML-t ZIP-archívummá C#-ban az Aspose.HTML for .NET segítségével. Lépésről lépésre útmutató. +Ismerje meg, hogyan konvertálhat HTML-t ZIP-archívummá C#-ban az Aspose.HTML for .NET segítségével. Lépésről‑lépésre útmutató. ### [HTML ZIP-elése C#-ban – Teljes lépésről‑lépésre útmutató](./how-to-zip-html-in-c-complete-step-by-step-guide/) Ismerje meg, hogyan lehet HTML-fájlokat ZIP-archívumba csomagolni C#-ban az Aspose.HTML for .NET segítségével. ### [PDF létrehozása HTML-ből C#-ban – Teljes lépésről‑lépésre útmutató](./create-pdf-from-html-in-c-complete-step-by-step-guide/) @@ -114,6 +114,9 @@ Tanulja meg, hogyan menthet HTML-fájlokat ZIP-archívumba C#‑ban az Aspose.HT ### [HTML-dokumentum létrehozása és ZIP-be mentése – Teljes C# útmutató](./create-html-document-and-save-as-zip-complete-c-guide/) Ismerje meg, hogyan hozhat létre HTML-dokumentumot C#‑ban, és mentheti azt ZIP‑archívumba az Aspose.HTML for .NET segítségével. +### [HTML mentése ZIP-be az Aspose.HTML segítségével és képek beillesztése](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Ismerje meg, hogyan menthet HTML-t ZIP-archívumba, és hogyan ágyazhat be képeket az Aspose.HTML használatával. + ## Következtetés Összefoglalva, a HTML-kiterjesztések és -konverziók a modern webfejlesztés elengedhetetlen elemei. Az Aspose.HTML for .NET leegyszerűsíti a folyamatot, és minden szinten elérhetővé teszi a fejlesztők számára. Ha követi oktatóanyagainkat, jó úton halad afelé, hogy széles készségekkel rendelkező, gyakorlott webfejlesztővé váljon. diff --git a/html/hungarian/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/hungarian/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..5e1b2502b9 --- /dev/null +++ b/html/hungarian/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,343 @@ +--- +category: general +date: 2026-10-02 +description: Tanulja meg, hogyan mentse el a HTML-t zip formátumban az Aspose.HTML + használatával C#-ban. Ez az útmutató azt is bemutatja, hogyan mentse el a HTML-t + képekkel egyetlen archívumba. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: hu +lastmod: 2026-10-02 +og_description: HTML mentése zipként az Aspose.HTML használatával C#-ban. Kövesd ezt + a teljes útmutatót, hogy megtudd, hogyan menthetsz HTML-t képekkel egyetlen archívumba. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: HTML mentése zipként az Aspose.HTML segítségével – lépésről lépésre C# útmutató +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: HTML mentése zip fájlként az Aspose.HTML segítségével és képek hozzáadásával +url: /hu/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan mentse el a HTML-t zip formátumban az Aspose.HTML segítségével, és vegye bele a képeket + +Ha **HTML-t zip formátumban** kell menteni a könnyű terjesztés érdekében, ez a bemutató pontos lépéseket mutat be az Aspose.HTML for .NET használatával. Akár statikus oldalt, e‑mail sablont vagy képeket tartalmazó jelentést exportál, láthatja, hogyan csomagolhatja az HTML‑t, a CSS‑t és a képfájlokat egyetlen ZIP‑archívumba anélkül, hogy ideiglenes fájlokat írna a lemezre. + +Az elsődleges cél mellett megválaszoljuk a gyakori, kapcsolódó kérdést is, **hogyan mentse el a HTML-t képekkel**, hogy a létrehozott archívum bármely böngészőben megnyitható legyen hiányzó erőforrások nélkül. + +A útmutató végére egy újrahasználható `ResourceHandler` megvalósítással, egy teljes C# programmal, amely `output.zip`‑t hoz létre, valamint gyakorlati tippekkel fog rendelkezni a nagy képek vagy egyedi mappaszerkezetek kezeléséhez. + +## Prerequisites + +- .NET 6.0 vagy újabb (az API a .NET Framework 4.6+ verzióval is működik) +- Aspose.HTML for .NET NuGet csomag (`Aspose.Html`) +- Alapvető C# és stream ismeretek +- Visual Studio 2022 vagy bármely .NET fejlesztést támogató IDE + +> **Pro tipp:** Telepítse a csomagot a CLI‑n keresztül, hogy a projektfájl tiszta maradjon: +> `dotnet add package Aspose.Html` + +## 1. lépés: Az Aspose.HTML kimeneti modelljének megértése + +Amikor az Aspose.HTML egy dokumentumot ment, minden külső erőforrást (CSS‑fájlok, képek, betűkészletek stb.) külön **erőforrásként** kezel. Alapértelmezés szerint a könyvtár ezeket az erőforrásokat a fájlrendszerre írja. A célhely irányításához egy egyedi `ResourceHandler`‑t kell megadnia. A kezelő egy `Resource` objektumot kap, és egy írható `Stream`‑et kell visszaadjon. Az Aspose.HTML ezután az erőforrás adatokat ebbe a streambe írja. + +Egy egyedi kezelő használatával lehetővé válik: + +- Az erőforrások közvetlenül egy `MemoryStream`‑be írása, amely később ZIP bejegyzés lesz +- Az erőforrások tárolása adatbázisban, felhő tárolóban vagy bármely más médiumon +- Fájlnevek, tömörítési szintek vagy mappahierarchiák módosítása + +## 2. lépés: `ResourceHandler` létrehozása, amely ZIP archívumba ír + +Az alábbiakban egy teljesen működőképes kezelő látható, amely memóriában épít egy `System.IO.Compression.ZipArchive`‑t. Minden erőforrás új bejegyzésként kerül hozzáadásra, amelynek neve tükrözi az eredeti URL‑útvonalat, ezáltal biztosítva, hogy a böngésző a ZIP kibontása után is fel tudja oldani a relatív hivatkozásokat. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Miért működik ez a megközelítés + +- **Memóriában végzett művelet**: Nem jönnek létre ideiglenes fájlok a lemezen, ami ideális webszolgáltatások vagy elszigetelt környezetek számára. +- **Mappahierarchia megőrzése**: Az eredeti erőforrás URI használatával a relatív hivatkozások a kibontás után is érvényesek maradnak. +- **Bővíthető**: A `MemoryStream`‑et helyettesítheti egy `FileStream`‑nel, hogy közvetlenül fájlba írjon, vagy egy hálózati stream‑mel a felhő tároláshoz. + +## 3. lépés: HTML dokumentum betöltése vagy létrehozása + +Bemutatásként egy egyszerű HTML karakterláncot hozunk létre, amely egy külső képre hivatkozik. Valódi projektben a HTML‑t fájlból, adatbázisból vagy HTTP válaszból töltené be. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Megjegyzés:** Ha fizikai HTML fájlja van, használja a `new HTMLDocument("path/to/file.html")` kifejezést. + +## 4. lépés: A kezelő csatlakoztatása a `SaveOptions`‑hoz és a ZIP mentése + +Most csatlakoztatjuk a `ZipResourceHandler`‑t a `SaveOptions.OutputStorage`‑hez. Amikor a `document.Save` lefut, az Aspose.HTML minden erőforrásra meghívja a `HandleResource`‑t, és a kezelő feltölti a ZIP archívumot. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Várható eredmény + +- `output.zip` tartalma: + - `index.html` (a fő HTML fájl) + - `images/logo.png` (a jelölőnyelvben hivatkozott kép) + - Bármely további CSS vagy betűkészlet fájl, amelyet az Aspose.HTML automatikusan felismer + +Amikor kibontja az archívumot és a böngészőben megnyitja a `index.html`‑t, a kép helyesen jelenik meg – ez demonstrálja, **hogyan mentse el a HTML-t képekkel** egy ZIP‑ben. + +## 5. lépés: Az archívum ellenőrzése és a gyakori problémák hibaelhárítása + +### Gyors ellenőrző szkript + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +A szkript futtatása listázni kell a `index.html`‑t és az `images/logo.png`‑t. Ha egy várt erőforrás hiányzik: + +- **Ellenőrizze a kép URL‑jét**: Elérhetőnek kell lennie a HTML dokumentumból. A relatív útvonalak a legjobbak. +- **Győződjön meg arról, hogy az erőforrás típusa támogatott**: Az Aspose.HTML a gyakori webformátumokat (PNG, JPEG, GIF, CSS, JS) kezeli. Szokatlan formátumok esetén manuális hozzáadásra lehet szükség. +- **Erősítse meg, hogy a `HandleResource` meghívódik**: Helyezzen egy `Console.WriteLine(resource.Uri)` sort a `HandleResource`‑ba a hibakereséshez. + +## 6. lépés: Haladó változatok + +### 6.1 Közvetlen mentés fájlba közbenső bájt tömb nélkül + +Ha a memóriahasználat aggály nagy dokumentumok esetén, cserélje a `MemoryStream`‑et `FileStream`‑re: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Ezután használja a következő módon: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Bejegyzésnevek testreszabása + +Ha lapos struktúrát szeretne (minden fájl a gyökérben), módosítsa az `entryName`‑t: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Manifest fájl hozzáadása + +Néha a downstream eszközök egy `manifest.json` fájlt várnak. Ezt a fő mentés után hozzáadhatja: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Gyakori buktatók és hogyan kerülhetők el + +| Buktató | Miért fordul elő | Megoldás | +|---------|------------------|----------| +| A képek töröttek a kibontás után | A HTML‑ben lévő képadat útvonala nem egyezik a ZIP bejegyzés nevével. | Az eredeti relatív útvonal megőrzése a `ZipArchiveEntry` létrehozásakor. | +| Nagy képek memória‑kifogyási kivételt okoznak | `MemoryStream` használata nagyon nagy fájlok esetén meghaladhatja a folyamat memóriahatárát. | Váltson `FileStream`‑alapú kezelőre (lásd 6.1). | +| A CSS URL‑k hiányoznak | Az `@import`‑on keresztül hivatkozott külső CSS‑fájlok nem kerülnek automatikusan felismerésre. | Manuálisan adja hozzá ezeket a CSS‑fájlokat a ZIP‑hez, vagy ágyazza be őket inline módon a mentés előtt. | +| Az Unicode karakterek torzulnak | Az alapértelmezett kódolás eltérhet a HTML forrás és a stream között. | Győződjön meg arról, hogy a HTML karakterlánc UTF‑8, az Aspose.HTML tiszteletben tartja a dokumentum karakterkészletét. | + +## Teljes működő példa (másolás-beillesztésre kész) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## Mit érdemes következőként megtanulni? + +Az alábbi bemutatók szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljes, működő kódpéldákat tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsen elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket saját projektjeiben. + +- [hogyan használjuk a kezelőt az Aspose.HTML‑ben – HTML betöltése, mentés ZIP‑ként](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Hogyan mentse el a HTML-t C#‑ben – Egyedi erőforráskezelők és ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [HTML renderelése PNG‑be és mentése ZIP‑be C#‑vel – Teljes útmutató](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 54ed8cc0a7..1d20033b89 100644 --- a/html/hungarian/net/rendering-html-documents/_index.md +++ b/html/hungarian/net/rendering-html-documents/_index.md @@ -50,7 +50,7 @@ Tanulja meg, hogyan renderelhet HTML-t PNG formátumba az Aspose.HTML for .NET s 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-ként C#-ban – Lépésről‑lépésre útmutató](./how-to-render-html-to-png-in-c-step-by-step-guide/) Tanulja meg, hogyan renderelhet HTML-t PNG formátumba C#-ban az Aspose.HTML for .NET használatával. -### [HTML renderelése PNG-ként C#-ban – Lépésről lépésre útmutató](./how-to-render-html-as-png-in-c-step-by-step-guide/) +### [HTML renderelése PNG‑ként C#-ban – Lépésről lépésre útmutató](./how-to-render-html-as-png-in-c-step-by-step-guide/) Tanulja meg, hogyan renderelhet HTML-t PNG formátumba C#-ban az Aspose 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 webkaparás és egyebek világában. @@ -86,6 +86,8 @@ Tanulja meg, hogyan renderelhet HTML-t PNG-be, majd ZIP-fájlba mentheti C#-ban Tanulja meg, hogyan hozhat létre képet HTML-ből C#-ban az Aspose.HTML segítségével, részletes, lépésről‑lépésre útmutató. ### [HTML renderelése PDF-be az Aspose.HTML segítségével – Lépésről‑lépésre útmutató](./render-html-to-pdf-with-aspose-html-step-by-step-guide/) Ismerje meg, hogyan konvertálhat HTML-t PDF-be az Aspose.HTML segítségével .NET környezetben, részletes lépésről‑lépésre útmutatóval. +### [Hogyan használja az Aspose-ot HTML PNG képként renderelni C#-ban](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Tanulja meg, hogyan renderelhet HTML-t PNG képként C#-ban az Aspose segítségével, részletes lépésről‑lépésre útmutatóval. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/hungarian/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/hungarian/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..6356080288 --- /dev/null +++ b/html/hungarian/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-10-02 +description: Hogyan használjuk az Aspose-t HTML gyors PNG képpé rendereléséhez – tanulja + meg, hogyan konvertáljon HTML-t PNG-re anti‑aliasinggal és szöveg‑hinteléssel. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: hu +lastmod: 2026-10-02 +og_description: Hogyan használjuk az Aspose-t HTML PNG képpé rendereléséhez. Kövesd + ezt a teljes útmutatót, hogy HTML-t PNG-re konvertálj magas minőségű rendereléssel + C#-ban. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Hogyan használjuk az Aspose-t HTML PNG képpé rendereléséhez – lépésről lépésre + útmutató +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Hogyan használjuk az Aspose-t HTML PNG képre rendereléshez C#-ban +url: /hu/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan használjuk az Aspose-t HTML PNG képpé rendereléshez C#-ban + +**Az Aspose használata HTML PNG képpé rendereléséhez** gyakori igény, ha bitmap előnézetre van szükség egy weboldalról, egy e‑mail bélyegképről vagy egy PDF‑barát pillanatképről. Ez a bemutató egy teljes, azonnal futtatható megoldást mutat be, amely **render html to image** antialiasinggal és text hintinggel, így az eredmény minden platformon éles. + +Megtanulod, hogyan **convert HTML to PNG**, hogyan konfiguráld a renderelési beállításokat, és hogyan kezeld a tipikus buktatókat, mint a Linux betűkészlet renderelés és a fájlrendszer jogosultságok. Külső eszközök nem szükségesek – csak az Aspose.HTML for .NET könyvtár és néhány C# sor. + +## Előfeltételek + +* .NET 6.0 SDK vagy újabb telepítve +* Visual Studio 2022 (vagy bármely C# IDE) +* NuGet hivatkozás a **Aspose.HTML**-re (`Install-Package Aspose.HTML`) +* Alapvető ismeretek a C# szintaxisról + +Ezek az előfeltételek könnyűek; a bemutató Windows, Linux és macOS rendszereken is működik, mivel az Aspose.HTML platformfüggetlen. + +## 1. lépés: Aspose.HTML telepítése és új konzolos projekt létrehozása + +Nyiss egy terminált vagy a Package Manager Console-t, és futtasd: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Egy dedikált projekt létrehozása elszigeteli a függőségeket, és egyszerűvé teszi a minta futtatását a `dotnet run` paranccsal. + +## 2. lépés: Kép renderelési beállítások konfigurálása (anti‑aliasing és text hinting) + +Az antialiasing simítja az éleket, míg a text hinting javítja a glifek tisztaságát, különösen Linuxon, ahol a betűk rasterizálása eltér a Windowsétól. Az `ImageRenderingOptions` osztály lehetővé teszi mindkét funkció engedélyezését: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Miért fontos:** Antialiasing nélkül az átlós vonalak és ívek szaggatottak lesznek. Text hinting nélkül a kis betűméretek elmosódhatnak, ami különösen észrevehető, ha **save html as png** bélyegképeket készítesz. + +## 3. lépés: CSS meghatározása konzisztens betűtípusokhoz és címsor stílusokhoz + +A CSS közvetlen beágyazása a HTML-be biztosítja, hogy a renderelt kép megfeleljen a tervezési elvárásoknak. Ebben a példában alapbetűtípust állítunk be, és `

`-et dőlté tesszük: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Hozzáadhatsz színeket, margókat vagy media query-ket a stíluslaphoz. A CSS a HTML dokumentum ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Tipp:** Ha **render html as image** távoli oldalról kell, cseréld le a string konstruktorát `new HTMLDocument("https://example.com")`-ra. Az Aspose letölti az oldalt, feloldja az erőforrásokat, és rendereli a végleges elrendezést. + +## 5. lépés: Dokumentum renderelése PNG fájlba + +Most meghívjuk a `RenderToImage`-t, megadva a kimeneti útvonalat és a korábban konfigurált beállításokat: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +A generált `output.png` tiszta renderelést tartalmaz majd a `

` elemről dőlt stílussal, köszönhetően az antialiasing és hinting beállításoknak. + +## Teljes programkód + +Másold a következő kódot a `Program.cs` fájlba. Így fordítható és futtatható változatban: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Várható kimenet + +A program futtatása létrehozza az `output.png`-t a projekt mappájában. A kép a **Sample** szót jeleníti meg dőlt Arial betűtípussal, sima élekkel és tiszta szöveggel. Nyisd meg a fájlt bármely képnézővel a minőség ellenőrzéséhez. + +## 6. lépés: Gyakori variációk és szélsőséges esetek kezelése + +| Helyzet | Mit kell módosítani | Ok | +|-----------|----------------|--------| +| **Nagy HTML oldalak** | Állítsd be az `ImageRenderingOptions.Width` / `Height` értékeket vagy használd a `PageSize`-t a kimeneti méretek szabályozásához | Megakadályozza a memória túlterhelését és biztosítja, hogy a PNG illeszkedjen a UI-hoz | +| **Linux betűtípus hiányzik** | Telepítsd a szükséges betűtípusokat a gépre (`apt-get install fonts‑arial` vagy használj egy egyedi betűtípusfájlt) és állítsd be az Aspose-t a `FontSettings` segítségével | Betűtípus nélkül az Aspose egy általános helyettesítőre vált, ami megváltoztatja a megjelenést | +| **Átlátszó háttér szükséges** | Állítsd be `imgOptions.BackgroundColor = Color.Transparent` értéket | Hasznos, ha a PNG-t más grafikákba ágyazod be | +| **Kötegelt konverzió** | Iterálj egy HTML stringek vagy fájlutak listáján, újrahasználva ugyanazt az `ImageRenderingOptions` objektumot | Javítja a teljesítményt és konzisztens renderelési beállításokat biztosít | + +## Pro tipp: renderelési beállítások gyorsítótárazása + +Egy új `ImageRenderingOptions` objektum létrehozása minden konverzióhoz többletterhet jelent. Ha sok HTML részletet dolgozol fel egy szolgáltatásban, deklarálj egy statikus példányt: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Használd újra a `SharedOptions`-t a hívások között, hogy alacsony CPU használatot tarts fenn. + +## Gyakran ismételt kérdések + +**K: Működik ez .NET Core-on macOS-en?** +V: Igen. Az Aspose.HTML teljesen platformfüggetlen. Győződj meg róla, hogy a szükséges betűtípusok telepítve vannak, és a kimeneti könyvtár írható. + +**K: Renderelhetek JPEG-re PNG helyett?** +V: Cseréld le a `RenderToImage("output.png", imgOptions)`-t `RenderToImage("output.jpg", imgOptions)`-ra. Emellett beállíthatod az `imgOptions.ImageFormat = ImageFormat.Jpeg`-et a minőség finomabb szabályozásához. + +**K: Hogyan ágyazhatok be külső CSS fájlokat?** +V: Töltsd be a CSS tartalmat egy stringbe és fűzd össze, vagy hivatkozz egy távoli stíluslapra a `` tagben. Az Aspose automatikusan feloldja a `` tageket, ha a dokumentum URL-ről van betöltve. + +## Következtetés + +Most már tudod, **hogyan használjuk az Aspose-t** **HTML PNG képpé rendereléséhez** (vagy bármely más raszteres formátumba) magas minőségű beállításokkal. A bemutató lefedte az Aspose.HTML telepítését, az antialiasing és text hinting konfigurálását, a CSS beágyazását, a HTML betöltését, és végül a **HTML PNG‑ként mentését**. A lépések követésével megbízhatóan **HTML‑t PNG‑vé konvertálhatsz** bármely .NET alkalmazásban, legyen az Windows, Linux vagy macOS. + +### Következő lépések + +* Fedezd fel a többi kimeneti formátumot, például a **render html as image** JPEG vagy BMP formátumot a fájlkiterjesztés módosításával. +* Kombináld ezt a megközelítést az **Aspose.PDF**-vel, hogy a PNG-t PDF jelentésbe ágyazd. +* Kísérletezz az `ImageRenderingOptions.DpiX` és `DpiY` értékekkel a nagy felbontású bélyegképekhez. + +Nyugodtan módosítsd a kódot kötegelt feldolgozáshoz, dinamikus HTML generáláshoz, vagy egy webszolgáltatásba való integráláshoz, amely igény szerint PNG előnézeteket ad vissza. Jó renderelést! + +## Mit érdemes még megtanulni? + +A következő bemutatók szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljes, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy elsajátíthasd a további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Hogyan használjuk az Aspose-t HTML PNG képpé rendereléshez – Lépésről‑lépésre útmutató](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [HTML renderelése PNG-re Aspose‑szal – Teljes útmutató](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – HTML renderelése PNG-re Aspose.HTML‑el C#‑ban](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 8bb1e69edb..4fba6d749d 100644 --- a/html/indonesian/net/html-extensions-and-conversions/_index.md +++ b/html/indonesian/net/html-extensions-and-conversions/_index.md @@ -113,6 +113,8 @@ Pelajari cara mengompres file HTML menjadi arsip ZIP menggunakan C# dengan Aspos Pelajari cara menyimpan dokumen HTML sebagai file ZIP menggunakan Aspose.HTML untuk .NET dengan contoh kode C# lengkap. ### [Simpan HTML ke ZIP di C# – Panduan Lengkap](./save-html-to-zip-in-c-complete-guide/) Pelajari cara menyimpan HTML sebagai arsip ZIP menggunakan C# dengan panduan lengkap Aspose.HTML. +### [Cara menyimpan HTML sebagai zip dengan Aspose.HTML dan menyertakan gambar](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Pelajari cara menyimpan file HTML beserta gambar ke dalam arsip ZIP menggunakan Aspose.HTML. ### [single file html – Simpan Halaman Web sebagai Satu File HTML di C#](./single-file-html-save-a-web-page-as-one-html-file-in-c/) Pelajari cara menyimpan seluruh halaman web menjadi satu file HTML menggunakan C# dan Aspose.HTML. ### [Aspose HTML Save Options: Simpan HTML ke Stream dalam C#](./aspose-html-save-options-save-html-to-stream-in-c/) diff --git a/html/indonesian/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/indonesian/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..a577c2feb5 --- /dev/null +++ b/html/indonesian/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,343 @@ +--- +category: general +date: 2026-10-02 +description: Pelajari cara menyimpan HTML sebagai file zip menggunakan Aspose.HTML + di C#. Panduan ini juga menunjukkan cara menyimpan HTML beserta gambar dalam satu + arsip. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: id +lastmod: 2026-10-02 +og_description: Simpan HTML sebagai zip menggunakan Aspose.HTML di C#. Ikuti tutorial + lengkap ini untuk mempelajari cara menyimpan HTML dengan gambar ke dalam satu arsip. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Simpan HTML sebagai zip dengan Aspose.HTML – panduan langkah demi langkah + C# +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Cara menyimpan HTML sebagai zip dengan Aspose.HTML dan menyertakan gambar +url: /id/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara menyimpan HTML sebagai zip dengan Aspose.HTML dan menyertakan gambar + +Jika Anda perlu **menyimpan HTML sebagai zip** untuk distribusi yang mudah, tutorial ini menunjukkan langkah‑langkah tepat menggunakan Aspose.HTML untuk .NET. Baik Anda mengekspor halaman statis, templat email, atau laporan yang berisi gambar, Anda akan melihat cara menggabungkan file HTML, CSS, dan gambar ke dalam satu arsip ZIP tanpa menulis file sementara ke disk. + +Selain tujuan utama, kami juga akan menjawab pertanyaan lanjutan yang umum **cara menyimpan HTML dengan gambar** sehingga arsip yang dihasilkan dapat dibuka oleh browser apa pun tanpa kehilangan sumber daya. + +Pada akhir panduan ini Anda akan memiliki implementasi `ResourceHandler` yang dapat digunakan kembali, program C# lengkap yang menghasilkan `output.zip`, serta tip praktis untuk menangani gambar besar atau struktur folder khusus. + +## Prasyarat + +- .NET 6.0 atau lebih baru (API juga berfungsi dengan .NET Framework 4.6+) +- Paket NuGet Aspose.HTML untuk .NET (`Aspose.Html`) +- Pengetahuan dasar tentang C# dan stream +- Visual Studio 2022 atau IDE apa pun yang mendukung pengembangan .NET + +> **Tip pro:** Instal paket melalui CLI untuk menjaga file proyek tetap bersih: +> `dotnet add package Aspose.Html` + +## Langkah 1: Memahami model output Aspose.HTML + +Ketika Aspose.HTML menyimpan sebuah dokumen, ia memperlakukan setiap sumber eksternal (file CSS, gambar, font, dll.) sebagai **resource** terpisah. Secara default perpustakaan menulis sumber tersebut ke sistem file. Untuk mengontrol tujuan, Anda menyediakan `ResourceHandler` khusus. Handler menerima objek `Resource` dan harus mengembalikan `Stream` yang dapat ditulisi. Aspose.HTML kemudian menulis data sumber ke dalam stream tersebut. + +Menggunakan handler khusus memungkinkan Anda: + +- Menulis sumber langsung ke dalam `MemoryStream` yang kemudian menjadi entri ZIP +- Menyimpan sumber di basis data, penyimpanan cloud, atau media lain apa pun +- Menyesuaikan nama file, tingkat kompresi, atau hierarki folder + +## Langkah 2: Membuat `ResourceHandler` yang menulis ke dalam arsip ZIP + +Berikut ini adalah handler yang berfungsi penuh yang membangun `System.IO.Compression.ZipArchive` di memori. Setiap sumber ditambahkan sebagai entri baru dengan nama yang mencerminkan jalur URL asli, memastikan browser dapat menyelesaikan tautan relatif saat ZIP diekstrak. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Mengapa pendekatan ini berhasil + +- **Operasi dalam memori**: Tidak ada file sementara yang dibuat di disk, yang ideal untuk layanan web atau lingkungan sandbox. +- **Mempertahankan hierarki folder**: Dengan menggunakan URI sumber asli, referensi relatif tetap valid setelah ekstraksi. +- **Dapat diperluas**: Anda dapat mengganti `MemoryStream` dengan `FileStream` untuk menulis langsung ke file, atau dengan stream jaringan untuk penyimpanan cloud. + +## Langkah 3: Memuat atau membuat dokumen HTML + +Untuk demonstrasi kami akan membuat string HTML sederhana yang merujuk ke gambar eksternal. Pada proyek nyata Anda akan memuat HTML dari file, basis data, atau respons HTTP. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Catatan:** Jika Anda memiliki file HTML fisik, gunakan `new HTMLDocument("path/to/file.html")` sebagai gantinya. + +## Langkah 4: Menghubungkan handler ke `SaveOptions` dan menyimpan ZIP + +Sekarang kami menghubungkan `ZipResourceHandler` ke `SaveOptions.OutputStorage`. Saat `document.Save` dijalankan, Aspose.HTML akan memanggil `HandleResource` untuk setiap sumber, dan handler akan mengisi arsip ZIP. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Hasil yang diharapkan + +- `output.zip` berisi: + - `index.html` (file HTML utama) + - `images/logo.png` (gambar yang dirujuk dalam markup) + - File CSS atau font tambahan yang secara otomatis terdeteksi oleh Aspose.HTML + +Saat Anda mengekstrak arsip dan membuka `index.html` di browser, gambar akan ditampilkan dengan benar—menunjukkan **cara menyimpan HTML dengan gambar** di dalam ZIP. + +## Langkah 5: Memverifikasi arsip dan memecahkan masalah umum + +### Skrip verifikasi cepat + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Menjalankan skrip harus menampilkan `index.html` dan `images/logo.png`. Jika sumber yang diharapkan tidak ada: + +- **Periksa URL gambar**: URL harus dapat diakses dari dokumen HTML. Jalur relatif paling cocok. +- **Pastikan tipe sumber didukung**: Aspose.HTML menangani format web umum (PNG, JPEG, GIF, CSS, JS). Format yang tidak biasa mungkin memerlukan penambahan manual. +- **Pastikan `HandleResource` dipanggil**: Tambahkan `Console.WriteLine(resource.Uri)` di dalam `HandleResource` untuk debugging. + +## Langkah 6: Variasi lanjutan + +### 6.1 Menyimpan langsung ke file tanpa array byte perantara + +Jika penggunaan memori menjadi perhatian untuk dokumen yang sangat besar, ganti `MemoryStream` dengan `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Kemudian gunakan seperti ini: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Menyesuaikan nama entri + +Jika Anda lebih suka struktur datar (semua file di root), sesuaikan `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Menambahkan file manifest + +Kadang-kadang alat hilir mengharapkan `manifest.json`. Anda dapat menambahkannya setelah penyimpanan utama: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Kesalahan umum dan cara menghindarinya + +| Masalah | Mengapa terjadi | Solusi | +|---------|----------------|--------| +| Gambar muncul rusak setelah ekstraksi | Jalur gambar di dalam HTML tidak cocok dengan nama entri ZIP. | Pertahankan jalur relatif asli saat membuat `ZipArchiveEntry`. | +| Gambar besar menyebabkan pengecualian out‑of‑memory | Menggunakan `MemoryStream` untuk file yang sangat besar dapat melebihi batas memori proses. | Beralih ke handler berbasis `FileStream` (lihat 6.1). | +| URL CSS tidak ditemukan | File CSS eksternal yang dirujuk melalui `@import` tidak terdeteksi secara otomatis. | Tambahkan file CSS tersebut secara manual ke ZIP atau sematkan secara inline sebelum menyimpan. | +| Karakter Unicode menjadi rusak | Encoding default mungkin berbeda antara sumber HTML dan stream. | Pastikan string HTML menggunakan UTF‑8; Aspose.HTML menghormati charset dokumen. | + +## Contoh lengkap yang dapat dijalankan (siap salin‑tempel) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang terkait erat yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan menjelajahi pendekatan implementasi alternatif dalam proyek Anda. + +- [cara menggunakan handler di Aspose.HTML – Memuat HTML, Menyimpan sebagai ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Cara Menyimpan HTML di C# – Handler Sumber Daya Kustom & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Render HTML ke PNG dan Simpan ke ZIP dengan C# – Panduan Lengkap](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 a4641a80d5..84670d87f6 100644 --- a/html/indonesian/net/rendering-html-documents/_index.md +++ b/html/indonesian/net/rendering-html-documents/_index.md @@ -100,6 +100,9 @@ Pelajari cara merender HTML menjadi PDF menggunakan Aspose.HTML dengan panduan l ### [Cara Merender HTML sebagai PNG di C# – Panduan Langkah‑demi‑Langkah](./how-to-render-html-as-png-in-c-step-by-step-guide/) Pelajari cara merender HTML menjadi PNG menggunakan Aspose.HTML untuk .NET dengan panduan langkah demi langkah dalam C#. +### [Cara menggunakan Aspose untuk merender HTML menjadi gambar PNG di C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Pelajari cara menggunakan Aspose untuk merender file HTML menjadi gambar PNG menggunakan C# dengan contoh langkah demi langkah. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/indonesian/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/indonesian/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..3c7c1d12af --- /dev/null +++ b/html/indonesian/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-10-02 +description: Cara menggunakan Aspose untuk merender HTML menjadi gambar PNG dengan + cepat – pelajari cara mengonversi HTML ke PNG dengan anti‑aliasing dan petunjuk + teks. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: id +lastmod: 2026-10-02 +og_description: Cara menggunakan Aspose untuk merender HTML menjadi gambar PNG. Ikuti + tutorial lengkap ini untuk mengonversi HTML ke PNG dengan rendering berkualitas + tinggi di C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Cara menggunakan Aspose untuk merender HTML menjadi gambar PNG – panduan + langkah demi langkah +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Cara menggunakan Aspose untuk merender HTML menjadi gambar PNG di C# +url: /id/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara menggunakan Aspose untuk merender HTML menjadi gambar PNG di C# + +**How to use Aspose to render HTML to PNG image** adalah kebutuhan umum ketika Anda memerlukan pratinjau bitmap dari halaman web, thumbnail email, atau snapshot yang ramah PDF. Tutorial ini menunjukkan solusi lengkap yang siap dijalankan yang **render html to image** dengan anti‑aliasing dan text hinting, sehingga hasilnya tampak tajam di setiap platform. + +Anda akan belajar cara **convert HTML to PNG**, mengonfigurasi opsi rendering, dan menangani jebakan umum seperti rendering font di Linux serta izin sistem file. Tidak diperlukan alat eksternal—hanya pustaka Aspose.HTML untuk .NET dan beberapa baris kode C#. + +## Prasyarat + +* .NET 6.0 SDK atau yang lebih baru terpasang +* Visual Studio 2022 (atau IDE C# apa pun) +* Referensi NuGet ke **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Familiaritas dasar dengan sintaks C# + +Prasyarat ini ringan; tutorial berfungsi di Windows, Linux, dan macOS karena Aspose.HTML bersifat lintas‑platform. + +## Langkah 1: Instal Aspose.HTML dan buat proyek konsol baru + +Buka terminal atau Package Manager Console dan jalankan: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Membuat proyek khusus memisahkan dependensi dan memudahkan menjalankan contoh dengan `dotnet run`. + +## Langkah 2: Siapkan opsi rendering gambar (anti‑aliasing dan text hinting) + +Antialiasing menghaluskan tepi, sementara text hinting meningkatkan kejelasan glyph, terutama di Linux dimana rasterisasi font berbeda dengan Windows. Kelas `ImageRenderingOptions` memungkinkan Anda mengaktifkan kedua fitur tersebut: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Mengapa ini penting:** Tanpa antialiasing, garis diagonal dan kurva tampak bergerigi. Tanpa text hinting, ukuran font kecil dapat menjadi buram, yang terlihat ketika Anda **save html as png** untuk thumbnail. + +## Langkah 3: Definisikan CSS untuk font konsisten dan gaya heading + +Menyematkan CSS langsung dalam HTML memastikan gambar yang dirender cocok dengan harapan desain Anda. Pada contoh ini kami menetapkan font dasar dan membuat `

` miring: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Anda dapat memperluas stylesheet dengan warna, margin, atau media query. CSS disuntikkan ke dalam tag ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Tip:** Jika Anda perlu **render html as image** dari halaman remote, ganti konstruktor string dengan `new HTMLDocument("https://example.com")`. Aspose akan mengunduh halaman, menyelesaikan sumber daya, dan merender tata letak akhir. + +## Langkah 5: Render dokumen ke file PNG + +Sekarang kami memanggil `RenderToImage`, memberikan jalur output dan opsi yang telah kami konfigurasikan sebelumnya: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +`output.png` yang dihasilkan akan berisi rendering tajam dari elemen `

` dengan gaya miring, berkat pengaturan anti‑aliasing dan hinting. + +## Daftar program lengkap + +Salin kode berikut ke dalam `Program.cs`. Kode ini dapat dikompilasi dan dijalankan apa adanya: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Output yang diharapkan + +Menjalankan program membuat `output.png` di folder proyek. Gambar menampilkan kata **Sample** dalam Arial miring, dirender dengan tepi halus dan teks yang jelas. Buka file dengan penampil gambar apa pun untuk memverifikasi kualitasnya. + +## Langkah 6: Variasi umum dan penanganan kasus tepi + +| Situation | What to adjust | Reason | +|-----------|----------------|--------| +| **Large HTML pages** | Set `ImageRenderingOptions.Width` / `Height` atau gunakan `PageSize` untuk mengontrol dimensi output | Mencegah penggunaan memori berlebih dan memastikan PNG cocok dengan UI Anda | +| **Linux font missing** | Install font yang diperlukan pada host (`apt-get install fonts‑arial` atau gunakan file font khusus) dan arahkan Aspose ke sana via `FontSettings` | Tanpa font tersebut, Aspose akan beralih ke font generik, mengubah tampilan | +| **Transparent background needed** | Set `imgOptions.BackgroundColor = Color.Transparent` | Berguna saat menyematkan PNG ke grafik lain | +| **Batch conversion** | Loop over a list of HTML strings or file paths, reusing the same `ImageRenderingOptions` object | Meningkatkan performa dan menjaga konsistensi pengaturan rendering | + +## Pro tip: caching rendering options + +Membuat objek `ImageRenderingOptions` baru untuk setiap konversi menambah beban. Deklarasikan instance statis jika Anda memproses banyak potongan HTML dalam layanan: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Gunakan kembali `SharedOptions` di seluruh pemanggilan untuk menjaga penggunaan CPU tetap rendah. + +## Frequently asked questions + +**Q: Does this work with .NET Core on macOS?** +A: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are installed, and the output directory is writable. + +**Q: Can I render to JPEG instead of PNG?** +A: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for finer control over quality. + +**Q: How do I embed external CSS files?** +A: Load the CSS content into a string and concatenate it, or reference a remote stylesheet in the `` tag. Aspose resolves `` tags automatically when the document is loaded from a URL. + +## Conclusion + +Anda kini tahu **how to use Aspose** untuk **render HTML to PNG** (atau format raster lain) dengan pengaturan berkualitas tinggi. Tutorial ini mencakup instalasi Aspose.HTML, konfigurasi anti‑aliasing dan text hinting, penyuntikan CSS, pemuatan HTML, dan akhirnya **saving HTML as PNG**. Dengan mengikuti langkah‑langkah tersebut Anda dapat secara andal **convert HTML to PNG** dalam aplikasi .NET apa pun, baik berjalan di Windows, Linux, maupun macOS. + +### Langkah selanjutnya + +* Jelajahi format output lain seperti **render html as image** JPEG atau BMP dengan mengubah ekstensi file. +* Gabungkan pendekatan ini dengan **Aspose.PDF** untuk menyematkan PNG ke dalam laporan PDF. +* Bereksperimen dengan `ImageRenderingOptions.DpiX` dan `DpiY` untuk thumbnail beresolusi tinggi. + +Silakan sesuaikan kode untuk pemrosesan batch, pembuatan HTML dinamis, atau integrasi ke layanan web yang mengembalikan pratinjau PNG sesuai permintaan. Selamat merender! + +## What Should You Learn Next? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [Cara Menggunakan Aspose untuk Merender HTML ke PNG – Panduan Langkah‑per‑Langkah](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Cara Merender HTML ke PNG dengan Aspose – Panduan Lengkap](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Tutorial html ke gambar – Merender HTML ke PNG dengan Aspose.HTML di C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 4c5862eb5c..0b7bab834c 100644 --- a/html/italian/net/html-extensions-and-conversions/_index.md +++ b/html/italian/net/html-extensions-and-conversions/_index.md @@ -133,6 +133,8 @@ Scopri come salvare un documento HTML direttamente in uno stream usando le opzio Scopri come utilizzare il gestore di Aspose.HTML per caricare un documento HTML e salvarlo in un archivio ZIP in C#. ### [Creare documento HTML e salvarlo come ZIP – Guida completa C#](./create-html-document-and-save-as-zip-complete-c-guide/) Scopri come creare un documento HTML e comprimerlo in un archivio ZIP usando Aspose.HTML per .NET in C#. +### [Come salvare HTML come zip con Aspose.HTML e includere le immagini](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Scopri come salvare un documento HTML in un archivio ZIP includendo le immagini con Aspose.HTML per .NET. ## Conclusione diff --git a/html/italian/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/italian/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..ff96daee58 --- /dev/null +++ b/html/italian/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,343 @@ +--- +category: general +date: 2026-10-02 +description: Scopri come salvare HTML come zip usando Aspose.HTML in C#. Questa guida + mostra anche come salvare HTML con immagini in un unico archivio. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: it +lastmod: 2026-10-02 +og_description: Salva HTML come zip usando Aspose.HTML in C#. Segui questo tutorial + completo per imparare come salvare HTML con immagini in un unico archivio. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Salva HTML come zip con Aspose.HTML – guida passo‑passo C# +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Come salvare HTML come zip con Aspose.HTML e includere le immagini +url: /it/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come salvare HTML come zip con Aspose.HTML e includere le immagini + +Se hai bisogno di **salvare HTML come zip** per una distribuzione semplice, questo tutorial ti mostra i passaggi esatti usando Aspose.HTML per .NET. Che tu stia esportando una pagina statica, un modello di email o un report che contiene immagini, vedrai come raggruppare i file HTML, CSS e le immagini in un unico archivio ZIP senza scrivere file temporanei su disco. + +Oltre all’obiettivo principale, risponderemo anche alla domanda comune di seguito **come salvare HTML con immagini** in modo che l’archivio risultante possa essere aperto da qualsiasi browser senza risorse mancanti. + +Al termine di questa guida avrai un’implementazione riutilizzabile di `ResourceHandler`, un programma C# completo che produce `output.zip` e consigli pratici per gestire immagini di grandi dimensioni o strutture di cartelle personalizzate. + +## Prerequisiti + +- .NET 6.0 o versioni successive (l’API funziona anche con .NET Framework 4.6+) +- Pacchetto NuGet Aspose.HTML per .NET (`Aspose.Html`) +- Conoscenze di base di C# e stream +- Visual Studio 2022 o qualsiasi IDE che supporti lo sviluppo .NET + +> **Suggerimento:** Installa il pacchetto tramite la CLI per mantenere pulito il file di progetto: +> `dotnet add package Aspose.Html` + +## Passo 1: Comprendere il modello di output di Aspose.HTML + +Quando Aspose.HTML salva un documento, tratta ogni risorsa esterna (file CSS, immagini, font, ecc.) come una **risorsa** separata. Per impostazione predefinita la libreria scrive queste risorse sul file system. Per controllare la destinazione fornisci un `ResourceHandler` personalizzato. Il gestore riceve un oggetto `Resource` e deve restituire uno `Stream` scrivibile. Aspose.HTML quindi scrive i dati della risorsa in quello stream. + +Usare un gestore personalizzato ti consente di: + +- Scrivere le risorse direttamente in un `MemoryStream` che in seguito diventa una voce ZIP +- Archiviare le risorse in un database, storage cloud o qualsiasi altro supporto +- Regolare i nomi dei file, i livelli di compressione o le gerarchie di cartelle + +## Passo 2: Creare un `ResourceHandler` che scrive in un archivio ZIP + +Di seguito è riportato un gestore completamente funzionale che costruisce un `System.IO.Compression.ZipArchive` in memoria. Ogni risorsa viene aggiunta come nuova voce il cui nome rispecchia il percorso URL originale, garantendo che il browser possa risolvere i collegamenti relativi quando lo ZIP viene estratto. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Perché questo approccio funziona + +- **Operazione in memoria**: Non vengono creati file temporanei su disco, ideale per servizi web o ambienti sandbox. +- **Preserva la gerarchia delle cartelle**: Utilizzando l’URI della risorsa originale, i riferimenti relativi rimangono validi dopo l’estrazione. +- **Estendibile**: Puoi sostituire `MemoryStream` con un `FileStream` per scrivere direttamente su file, o con uno stream di rete per lo storage cloud. + +## Passo 3: Caricare o creare il documento HTML + +Per dimostrazione creiamo una semplice stringa HTML che fa riferimento a un’immagine esterna. In un progetto reale caricheresti l’HTML da un file, da un database o da una risposta HTTP. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Nota:** Se hai un file HTML fisico, usa `new HTMLDocument("path/to/file.html")` al suo posto. + +## Passo 4: Collegare il gestore a `SaveOptions` e salvare lo ZIP + +Ora colleghiamo il `ZipResourceHandler` a `SaveOptions.OutputStorage`. Quando `document.Save` viene eseguito, Aspose.HTML invocherà `HandleResource` per ogni risorsa e il gestore popolerà l’archivio ZIP. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Risultato atteso + +- `output.zip` contiene: + - `index.html` (il file HTML principale) + - `images/logo.png` (l’immagine referenziata nel markup) + - Qualsiasi file CSS o font aggiuntivo rilevato automaticamente da Aspose.HTML + +Quando estrai l’archivio e apri `index.html` in un browser, l’immagine viene visualizzata correttamente—dimostrando **come salvare HTML con immagini** all’interno di un ZIP. + +## Passo 5: Verificare l’archivio e risolvere i problemi comuni + +### Script di verifica rapida + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +L’esecuzione dello script dovrebbe elencare `index.html` e `images/logo.png`. Se una risorsa prevista è mancante: + +- **Controlla l’URL dell’immagine**: Deve essere raggiungibile dal documento HTML. I percorsi relativi funzionano meglio. +- **Assicurati che il tipo di risorsa sia supportato**: Aspose.HTML gestisce i formati web comuni (PNG, JPEG, GIF, CSS, JS). Formati insoliti potrebbero richiedere l’aggiunta manuale. +- **Verifica che `HandleResource` sia chiamato**: Aggiungi un `Console.WriteLine(resource.Uri)` all’interno di `HandleResource` per il debug. + +## Passo 6: Varianti avanzate + +### 6.1 Salvataggio diretto su file senza un array di byte intermedio + +Se l’uso della memoria è un problema per documenti molto grandi, sostituisci `MemoryStream` con un `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Quindi usalo così: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Personalizzare i nomi delle voci + +Se preferisci una struttura piatta (tutti i file nella radice), modifica `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Aggiungere un file manifest + +Alcuni strumenti a valle si aspettano un `manifest.json`. Puoi aggiungerlo dopo il salvataggio principale: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Problemi comuni e come evitarli + +| Problema | Perché accade | Soluzione | +|----------|----------------|-----------| +| Le immagini appaiono rotte dopo l’estrazione | Il percorso dell’immagine nell’HTML non corrisponde al nome della voce ZIP. | Mantieni il percorso relativo originale quando crei `ZipArchiveEntry`. | +| Immagini di grandi dimensioni causano eccezioni out‑of‑memory | L’uso di `MemoryStream` per file molto grandi può superare il limite di memoria del processo. | Passa a un gestore basato su `FileStream` (vedi 6.1). | +| Mancano gli URL dei CSS | I file CSS esterni referenziati tramite `@import` non vengono rilevati automaticamente. | Aggiungi manualmente quei file CSS allo ZIP o incorporali inline prima del salvataggio. | +| I caratteri Unicode diventano illeggibili | La codifica predefinita può differire tra la sorgente HTML e lo stream. | Assicurati che la stringa HTML sia UTF‑8; Aspose.HTML rispetta il charset del documento. | + +## Esempio completo funzionante (pronto per copia‑incolla) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## Cosa dovresti imparare dopo? + + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [come usare il gestore in Aspose.HTML – Carica HTML, Salva come ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Come salvare HTML in C# – Gestori di risorse personalizzati & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Renderizza HTML in PNG e salva in ZIP con C# – Guida completa](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 75552b6b18..7554bcf47c 100644 --- a/html/italian/net/rendering-html-documents/_index.md +++ b/html/italian/net/rendering-html-documents/_index.md @@ -88,7 +88,13 @@ Scopri come rendere HTML usando Aspose.HTML con un gestore di risorse personaliz ### [Come rendere HTML in PNG – Guida passo‑passo](./how-to-render-html-to-png-step-by-step-guide/) Scopri come convertire HTML in PNG passo dopo passo con Aspose.HTML per .NET. ### [Come utilizzare Aspose per rendere HTML in PNG in C#](./how-to-use-aspose-to-render-html-to-png-in-c/) -Scopri come convertire facilmente documenti HTML in immagini PNG usando Aspose.HTML con C#. +Scopri come convertire facilmente documenti HTML in PNG usando Aspose.HTML con C#. +### [Come utilizzare Aspose per rendere HTML in immagine PNG in C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Scopri come convertire facilmente file HTML in immagini PNG usando Aspose.HTML con C#. +### [Come rendere HTML in PNG – Guida passo‑passo](./how-to-render-html-to-png-step-by-step-guide/) +Scopri come convertire HTML in PNG passo dopo passo con Aspose.HTML per .NET. +### [Come utilizzare Aspose per rendere HTML in PNG in C#](./how-to-use-aspose-to-render-html-to-png-in-c/) +Scopri come convertire facilmente documenti HTML in PNG usando Aspose.HTML con C#. ### [Come rendere HTML in un'immagine con C# – Guida completa](./how-to-render-html-to-an-image-with-c-complete-guide/) Scopri come convertire HTML in immagini con C# usando Aspose.HTML, passo dopo passo, con esempi pratici. diff --git a/html/italian/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/italian/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..2576246682 --- /dev/null +++ b/html/italian/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-10-02 +description: Come usare Aspose per renderizzare rapidamente HTML in immagine PNG – + impara a convertire HTML in PNG con anti‑aliasing e hinting del testo. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: it +lastmod: 2026-10-02 +og_description: Come utilizzare Aspose per renderizzare HTML in immagine PNG. Segui + questo tutorial completo per convertire HTML in PNG con rendering ad alta qualità + in C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Come usare Aspose per convertire HTML in immagine PNG – guida passo passo +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Come utilizzare Aspose per renderizzare HTML in immagine PNG in C# +url: /it/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come usare Aspose per renderizzare HTML in immagine PNG in C# + +**Come usare Aspose per renderizzare HTML in immagine PNG** è una necessità comune quando ti serve un'anteprima bitmap di una pagina web, una miniatura di email o uno snapshot adatto a PDF. Questo tutorial ti mostra una soluzione completa, pronta all'uso, che **render html to image** con anti‑aliasing e text hinting, così il risultato appare nitido su ogni piattaforma. + +Imparerai a **convertire HTML in PNG**, a configurare le opzioni di rendering e a gestire le difficoltà tipiche come il rendering dei font su Linux e i permessi del file‑system. Non sono richiesti strumenti esterni: basta la libreria Aspose.HTML per .NET e qualche riga di C#. + +## Prerequisiti + +Prima di iniziare, assicurati di avere: + +* .NET 6.0 SDK o versioni successive installate +* Visual Studio 2022 (o qualsiasi IDE C#) +* Un riferimento NuGet a **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Familiarità di base con la sintassi C# + +Questi prerequisiti sono leggeri; il tutorial funziona su Windows, Linux e macOS perché Aspose.HTML è cross‑platform. + +## Passo 1: Installa Aspose.HTML e crea un nuovo progetto console + +Apri un terminale o la Package Manager Console ed esegui: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Creare un progetto dedicato isola le dipendenze e rende più semplice l'esecuzione del campione con `dotnet run`. + +## Passo 2: Configura le opzioni di rendering dell'immagine (anti‑aliasing e text hinting) + +L'anti‑aliasing smussa i bordi, mentre il text hinting migliora la chiarezza dei glifi, specialmente su Linux dove la rasterizzazione dei font differisce da Windows. La classe `ImageRenderingOptions` ti consente di abilitare entrambe le funzionalità: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Perché è importante:** senza anti‑aliasing, le linee diagonali e le curve appaiono frastagliate. Senza text hinting, le dimensioni di font piccole possono diventare sfocate, il che è evidente quando **save html as png** per le miniature. + +## Passo 3: Definisci il CSS per font coerenti e stili di intestazione + +Incorporare il CSS direttamente nell'HTML garantisce che l'immagine renderizzata corrisponda alle tue aspettative di design. In questo esempio impostiamo un font di base e rendiamo `

` in corsivo: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Puoi estendere il foglio di stile con colori, margini o media query. Il CSS viene iniettato nel tag ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Suggerimento:** se devi **render html as image** da una pagina remota, sostituisci il costruttore di stringa con `new HTMLDocument("https://example.com")`. Aspose scaricherà la pagina, risolverà le risorse e renderizzerà il layout finale. + +## Passo 5: Renderizza il documento in un file PNG + +Ora chiamiamo `RenderToImage`, passando il percorso di output e le opzioni configurate in precedenza: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +Il `output.png` generato conterrà un rendering nitido dell'elemento `

` con stile corsivo, grazie alle impostazioni di anti‑aliasing e hinting. + +## Elenco completo del programma + +Copia il codice seguente in `Program.cs`. Compila ed esegui così com'è: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Output previsto + +L'esecuzione del programma crea `output.png` nella cartella del progetto. L'immagine mostra la parola **Sample** in Arial corsivo, renderizzata con bordi lisci e testo chiaro. Apri il file con qualsiasi visualizzatore di immagini per verificare la qualità. + +## Passo 6: Varianti comuni e gestione dei casi limite + +| Situazione | Cosa modificare | Motivo | +|------------|----------------|--------| +| **Pagine HTML grandi** | Imposta `ImageRenderingOptions.Width` / `Height` o usa `PageSize` per controllare le dimensioni dell'output | Previene un eccessivo consumo di memoria e garantisce che il PNG si adatti alla tua interfaccia | +| **Font Linux mancante** | Installa i font richiesti sull'host (`apt-get install fonts‑arial` o usa un file di font personalizzato) e indica ad Aspose di usarli tramite `FontSettings` | Senza il font, Aspose ricade su uno generico, modificando l'aspetto | +| **Sfondo trasparente necessario** | Imposta `imgOptions.BackgroundColor = Color.Transparent` | Utile quando si incorpora il PNG in altre grafiche | +| **Conversione batch** | Itera su un elenco di stringhe HTML o percorsi di file, riutilizzando lo stesso oggetto `ImageRenderingOptions` | Migliora le prestazioni e mantiene coerenti le impostazioni di rendering | + +## Pro tip: caching delle opzioni di rendering + +Creare un nuovo oggetto `ImageRenderingOptions` per ogni conversione aggiunge overhead. Dichiarane un'istanza statica se elabori molti snippet HTML in un servizio: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Riutilizza `SharedOptions` tra le chiamate per mantenere basso l'uso della CPU. + +## Domande frequenti + +**D: Funziona con .NET Core su macOS?** +R: Sì. Aspose.HTML è completamente cross‑platform. Assicurati che i font richiesti siano installati e che la cartella di output sia scrivibile. + +**D: Posso renderizzare in JPEG invece di PNG?** +R: Sostituisci `RenderToImage("output.png", imgOptions)` con `RenderToImage("output.jpg", imgOptions)`. Puoi anche impostare `imgOptions.ImageFormat = ImageFormat.Jpeg` per un controllo più fine sulla qualità. + +**D: Come incorporo file CSS esterni?** +R: Carica il contenuto CSS in una stringa e concatenalo, oppure riferisci un foglio di stile remoto nel tag ``. Aspose risolve automaticamente i tag `` quando il documento è caricato da un URL. + +## Conclusione + +Ora sai **come usare Aspose** per **renderizzare HTML in PNG** (o qualsiasi altro formato raster) con impostazioni di alta qualità. Il tutorial ha coperto l'installazione di Aspose.HTML, la configurazione di anti‑aliasing e text hinting, l'iniezione di CSS, il caricamento di HTML e infine **saving HTML as PNG**. Seguendo i passaggi potrai convertire HTML in PNG in modo affidabile in qualsiasi applicazione .NET, sia su Windows, Linux o macOS. + +### Prossimi passi + +* Esplora altri formati di output come **render html as image** JPEG o BMP modificando l'estensione del file. +* Combina questo approccio con **Aspose.PDF** per incorporare il PNG in un report PDF. +* Sperimenta con `ImageRenderingOptions.DpiX` e `DpiY` per miniature ad alta risoluzione. + +Sentiti libero di adattare il codice per elaborazioni batch, generazione dinamica di HTML o integrazione in un servizio web che restituisce anteprime PNG su richiesta. Buon rendering! + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità aggiuntive dell'API ed esplorare approcci alternativi nei tuoi progetti. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 68784fd74d..44e193bdef 100644 --- a/html/japanese/net/html-extensions-and-conversions/_index.md +++ b/html/japanese/net/html-extensions-and-conversions/_index.md @@ -101,7 +101,6 @@ C# と Aspose.HTML を使用して、HTML を PDF に変換する方法をステ C# と Aspose.HTML を使用して、HTML ファイルを Zip アーカイブに圧縮する手順をステップバイステップで解説します。 ### [C# で HTML を ZIP として保存する – 完全ステップバイステップガイド](./save-html-as-zip-in-c-complete-step-by-step-guide/) Aspose.HTML for .NET を使用して、C# で HTML を ZIP ファイルに保存する方法をステップバイステップで解説します。 - ### [C# のカスタム リソース ハンドラ – メモリ内の HTML を ZIP アーカイブに変換](./custom-resource-handler-in-c-convert-html-to-zip-archive-fro/) Aspose.HTML for .NET を使用して、C# でカスタム リソース ハンドラを実装し、メモリ内の HTML を ZIP アーカイブに変換する手順を解説します。 @@ -114,25 +113,14 @@ C# と Aspose.HTML で HTML を PDF に変換し、ZIP アーカイブとして ### [C# で HTML を ZIP に保存 – 完全ガイド](./save-html-to-zip-in-c-complete-guide/) Aspose.HTML for .NET と C# を使用して、HTML を ZIP アーカイブに保存する完全な手順をステップバイステップで解説します。 -### [シングルファイル HTML – C# で Web ページを 1 つの HTML ファイルとして保存する](./single-file-html-save-a-web-page-as-one-html-file-in-c/) -Aspose.HTML for .NET を使用して、C# で Web ページを単一の HTML ファイルとして保存する手順をステップバイステップで解説します。 - -### [C# で HTML を Zip に圧縮する方法 – カスタムリソースハンドラ チュートリアル](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) - -### [Aspose.HTML Save Options: C# で HTML をストリームに保存](./aspose-html-save-options-save-html-to-stream-in-c/) - -### [Aspose.HTML のハンドラを使用する方法 – HTML を読み込み、ZIP に保存](./how-to-use-handler-in-aspose-html-load-html-save-as-zip/) -Aspose.HTML のハンドラを利用して HTML をロードし、ZIP アーカイブとして保存する手順をステップバイステップで解説します。 - -### [C# で HTML を ZIP に保存 – 完全ガイド](./save-html-as-zip-in-c-complete-guide/) -Aspose.HTML for .NET を使用して、HTML コンテンツを ZIP アーカイブとして保存する完全ガイドをステップバイステップで紹介します。 - ### [Aspose.HTML を使用して .NET で HTML ドキュメントを作成する – C# ステップバイステップ ガイド](./create-html-document-c-step-by-step-guide/) Aspose.HTML for .NET を使用して、C# で HTML ドキュメントを作成する手順をステップバイステップで解説します。 ### [HTML ドキュメントを作成して ZIP に保存 – 完全 C# ガイド](./create-html-document-and-save-as-zip-complete-c-guide/) Aspose.HTML for .NET を使用して、HTML ドキュメントを作成し、ZIP アーカイブとして保存する完全な C# 手順を解説します。 +### [Aspose.HTML を使用して画像を含む HTML を ZIP として保存する方法](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) + ## 結論 結論として、HTML の拡張と変換は、現代の Web 開発に不可欠な要素です。Aspose.HTML for .NET はプロセスを簡素化し、あらゆるレベルの開発者が利用できるようにします。当社のチュートリアルに従うことで、幅広いスキルを備えた熟練した Web 開発者になるための道を順調に進むことができます。 diff --git a/html/japanese/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/japanese/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..2bfc80d1b0 --- /dev/null +++ b/html/japanese/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,341 @@ +--- +category: general +date: 2026-10-02 +description: C#でAspose.HTMLを使用してHTMLをZIPとして保存する方法を学びます。このガイドでは、画像付きHTMLを単一のアーカイブに保存する方法も示しています。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: ja +lastmod: 2026-10-02 +og_description: C# で Aspose.HTML を使用して HTML を zip として保存します。この完全なチュートリアルに従い、画像付き HTML + を単一のアーカイブに保存する方法を学びましょう。 +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Aspose.HTMLでHTMLをZIPとして保存 – ステップバイステップ C# ガイド +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Aspose.HTML を使用して HTML を zip として保存し、画像を含める方法 +url: /ja/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.HTML を使用して HTML を zip として保存し、画像を含める方法 + +HTML を **zip として保存** して配布しやすくしたい場合、本チュートリアルでは Aspose.HTML for .NET を使った正確な手順を示します。静的ページ、メールテンプレート、画像を含むレポートのいずれをエクスポートする場合でも、HTML、CSS、画像ファイルを一つの ZIP アーカイブにまとめ、ディスクに一時ファイルを書き込むことなく実現できます。 + +さらに、**画像付きで HTML を保存する方法** という一般的な質問にも答え、生成されたアーカイブがブラウザでリソース欠損なく開けるようにします。 + +このガイドを読み終えると、再利用可能な `ResourceHandler` 実装、`output.zip` を生成する完全な C# プログラム、そして大容量画像やカスタムフォルダー構造を扱う際の実用的なヒントが手に入ります。 + +## 前提条件 + +- .NET 6.0 以上(API は .NET Framework 4.6+ でも動作します) +- Aspose.HTML for .NET NuGet パッケージ(`Aspose.Html`) +- C# とストリームに関する基本知識 +- Visual Studio 2022 または .NET 開発に対応した任意の IDE + +> **プロのコツ:** プロジェクト ファイルをすっきりさせるために CLI でパッケージをインストールしましょう: +> `dotnet add package Aspose.Html` + +## 手順 1: Aspose.HTML の出力モデルを理解する + +Aspose.HTML がドキュメントを保存するとき、外部リソース(CSS ファイル、画像、フォントなど)を個別の **リソース** として扱います。デフォルトではライブラリがそれらのリソースをファイルシステムに書き込みます。保存先を制御するにはカスタム `ResourceHandler` を提供します。ハンドラは `Resource` オブジェクトを受け取り、書き込み可能な `Stream` を返す必要があります。Aspose.HTML はそのストリームにリソースデータを書き込みます。 + +カスタムハンドラを使用すると次が可能です: + +- 後で ZIP エントリになる `MemoryStream` へ直接リソースを書き込む +- データベース、クラウドストレージ、その他任意の媒体にリソースを保存する +- ファイル名、圧縮レベル、フォルダー階層を調整する + +## 手順 2: ZIP アーカイブに書き込む `ResourceHandler` を作成する + +以下はメモリ上に `System.IO.Compression.ZipArchive` を構築する完全なハンドラです。各リソースは元の URL パスに対応した名前で新しいエントリとして追加され、ZIP を展開した際にブラウザが相対リンクを解決できるようになります。 + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### このアプローチが有効な理由 + +- **インメモリ操作**: ディスクに一時ファイルを作成しないため、Web サービスやサンドボックス環境に最適です。 +- **フォルダー階層を保持**: 元のリソース URI を使用することで、抽出後も相対参照が有効です。 +- **拡張性**: `MemoryStream` を `FileStream` に置き換えて直接ファイルに書き込んだり、ネットワークストリームでクラウド保存したりできます。 + +## 手順 3: HTML ドキュメントを読み込むまたは作成する + +デモ用に外部画像を参照するシンプルな HTML 文字列を作成します。実際のプロジェクトではファイル、データベース、HTTP 応答などから HTML を読み込むことになるでしょう。 + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **注:** 物理的な HTML ファイルがある場合は `new HTMLDocument("path/to/file.html")` を使用してください。 + +## 手順 4: ハンドラを `SaveOptions` に接続し、ZIP を保存する + +ここで `ZipResourceHandler` を `SaveOptions.OutputStorage` に設定します。`document.Save` が実行されると、Aspose.HTML は各リソースに対して `HandleResource` を呼び出し、ハンドラが ZIP アーカイブにデータを追加します。 + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### 期待される結果 + +- `output.zip` に含まれるもの: + - `index.html`(メイン HTML ファイル) + - `images/logo.png`(マークアップで参照された画像) + - Aspose.HTML が自動検出したその他の CSS やフォントファイル + +アーカイブを展開し `index.html` をブラウザで開くと、画像が正しく表示されます。これにより **画像付きで HTML を ZIP に保存する方法** が実証されます。 + +## 手順 5: アーカイブを検証し、一般的な問題をトラブルシュートする + +### 簡易検証スクリプト + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +スクリプトを実行すると `index.html` と `images/logo.png` が一覧表示されます。期待したリソースが欠けている場合は次を確認してください: + +- **画像 URL を確認**: HTML から到達可能である必要があります。相対パスが最も扱いやすいです。 +- **リソースタイプがサポート対象か**: Aspose.HTML は一般的な Web 形式(PNG、JPEG、GIF、CSS、JS)を処理します。特殊形式は手動で追加が必要です。 +- **`HandleResource` が呼び出されているか**: `HandleResource` 内に `Console.WriteLine(resource.Uri)` を追加してデバッグします。 + +## 手順 6: 応用バリエーション + +### 6.1 中間バイト配列を使わずに直接ファイルへ保存する + +非常に大きなドキュメントでメモリ使用量が懸念される場合は、`MemoryStream` を `FileStream` に置き換えます: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +その後は次のように使用します: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 エントリ名をカスタマイズする + +すべてのファイルをルートに配置したフラット構造にしたい場合は、`entryName` を調整します: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 マニフェストファイルを追加する + +下流ツールが `manifest.json` を期待することがあります。メイン保存後に以下のように追加できます: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## よくある落とし穴と回避策 + +| 落とし穴 | 発生理由 | 対策 | +|---------|----------|------| +| 抽出後に画像が表示されない | HTML 内の画像パスが ZIP エントリ名と一致していない | `ZipArchiveEntry` を作成する際に元の相対パスを保持する | +| 大容量画像でメモリ不足例外が発生する | `MemoryStream` を使用すると非常に大きなファイルでメモリ上限を超える可能性がある | 6.1 の `FileStream` ベースハンドラに切り替える | +| CSS の URL が欠落している | `@import` で参照された外部 CSS が自動検出されない | それらの CSS ファイルを手動で ZIP に追加するか、保存前にインライン化する | +| Unicode 文字が文字化けする | デフォルトエンコーディングが HTML ソースとストリームで異なる場合がある | HTML 文字列を UTF‑8 にし、Aspose.HTML がドキュメントの charset を尊重することを確認する | + +## 完全動作サンプル(コピー&ペースト用) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を応用した関連トピックを扱っています。各リソースには、ステップバイステップの解説と完全なコード例が含まれており、API の追加機能を習得したり、独自の実装アプローチを探求したりするのに役立ちます。 + +- [Aspose.HTML でハンドラを使用する方法 – HTML をロードし、ZIP として保存](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [C# で HTML を保存する方法 – カスタムリソースハンドラ & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [C# で HTML を PNG にレンダリングし、ZIP に保存する完全ガイド](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 ea969a3353..0549f112a4 100644 --- a/html/japanese/net/rendering-html-documents/_index.md +++ b/html/japanese/net/rendering-html-documents/_index.md @@ -40,6 +40,9 @@ Aspose.HTML for .NET は、豊富な機能、優れたドキュメント、ア Aspose.HTML for .NET のセットアップが完了したら、HTML レンダリングを習得するのに役立つチュートリアルを見てみましょう。以下は、HTML ドキュメントのレンダリングのさまざまな側面を網羅したチュートリアルの一覧です。 +### [How to use Aspose to render HTML to PNG image in C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) + + ### [Aspose.HTML を使用して .NET で HTML を PNG としてレンダリングする](./render-html-as-png/) Aspose.HTML for .NET の使い方を学びます。HTML の操作、さまざまな形式への変換などを行います。この包括的なチュートリアルをぜひご覧ください。 ### [C# で HTML を PNG にレンダリングする – 完全ステップバイステップガイド](./render-html-to-png-in-c-complete-step-by-step-guide/) diff --git a/html/japanese/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/japanese/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..d07f607a3e --- /dev/null +++ b/html/japanese/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-10-02 +description: Aspose を使用して HTML を PNG 画像に高速でレンダリングする方法 – アンチエイリアシングとテキストヒンティングを活用した + HTML から PNG への変換を学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: ja +lastmod: 2026-10-02 +og_description: Aspose を使用して HTML を PNG 画像にレンダリングする方法。C# で高品質なレンダリングにより HTML を PNG + に変換する完全なチュートリアルをご覧ください。 +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Aspose を使用して HTML を PNG 画像にレンダリングする方法 – ステップバイステップガイド +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: C#でAsposeを使用してHTMLをPNG画像にレンダリングする方法 +url: /ja/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で Aspose を使用して HTML を PNG 画像にレンダリングする方法 + +**How to use Aspose to render HTML to PNG image** は、ウェブページのビットマッププレビューやメールのサムネイル、PDF 用のスナップショットが必要なときに一般的な要件です。このチュートリアルでは、**render html to image** をアンチエイリアシングとテキストヒンティング付きで実行できる完全なソリューションを示します。その結果はすべてのプラットフォームで鮮明に表示されます。 + +このチュートリアルを通じて **convert HTML to PNG** の方法、レンダリングオプションの設定、Linux のフォントレンダリングやファイルシステム権限といった典型的な落とし穴の対処方法を学べます。外部ツールは不要で、Aspose.HTML for .NET ライブラリと数行の C# コードだけで完結します。 + +## 前提条件 + +開始する前に、以下が揃っていることを確認してください。 + +* .NET 6.0 SDK 以降がインストールされていること +* Visual Studio 2022(または任意の C# IDE) +* NuGet で **Aspose.HTML** を参照(`Install-Package Aspose.HTML`) +* C# の構文に関する基本的な知識 + +これらの前提条件は軽量で、Aspose.HTML がクロスプラットフォーム対応のため、Windows、Linux、macOS で動作します。 + +## Step 1: Install Aspose.HTML and create a new console project + +ターミナルまたは Package Manager Console を開き、次のコマンドを実行します。 + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +専用のプロジェクトを作成することで依存関係が分離され、`dotnet run` でサンプルを簡単に実行できます。 + +## Step 2: Set up image rendering options (anti‑aliasing and text hinting) + +アンチエイリアシングはエッジを滑らかにし、テキストヒンティングは特に Linux でフォントのラスタライズが Windows と異なる場合に文字の鮮明さを向上させます。`ImageRenderingOptions` クラスを使って両方の機能を有効にします。 + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Why this matters:** アンチエイリアシングが無いと斜め線や曲線がギザギザに見えます。テキストヒンティングが無いと小さいフォントサイズがぼやけ、サムネイル用に **save html as png** する際に目立ちます。 + +## Step 3: Define CSS for consistent fonts and heading styles + +HTML に直接 CSS を埋め込むことで、レンダリングされた画像がデザイン通りになることを保証します。この例ではベースフォントを設定し、`

` をイタリックにしています。 + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +色や余白、メディアクエリなどでスタイルシートを拡張できます。CSS は HTML ドキュメントの ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Tip:** リモートページから **render html as image** したい場合は、文字列コンストラクタを `new HTMLDocument("https://example.com")` に置き換えてください。Aspose がページをダウンロードし、リソースを解決して最終レイアウトをレンダリングします。 + +## Step 5: Render the document to a PNG file + +次に `RenderToImage` を呼び出し、出力パスと先ほど設定したオプションを渡します。 + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +生成された `output.png` には、イタリック体の Arial で描画された `

` 要素が、アンチエイリアシングとヒンティング設定により鮮明に表示されます。 + +## Full program listing + +以下のコードを `Program.cs` にコピーしてください。そのままコンパイルして実行できます。 + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Expected output + +プログラムを実行するとプロジェクトフォルダーに `output.png` が作成されます。画像にはイタリック体 Arial の **Sample** という文字が滑らかなエッジとクリアなテキストで描画されています。任意の画像ビューアで開き、品質を確認してください。 + +## Step 6: Common variations and edge‑case handling + +| 状況 | 調整項目 | 理由 | +|-----------|----------------|--------| +| **Large HTML pages** | `ImageRenderingOptions.Width` / `Height` を設定するか、`PageSize` を使用して出力サイズを制御する | メモリ使用量の増大を防ぎ、PNG が UI に収まるようにします | +| **Linux font missing** | ホストに必要なフォントをインストール(`apt-get install fonts‑arial` など)またはカスタムフォントファイルを使用し、`FontSettings` で Aspose に指定する | フォントが無いと Aspose が汎用フォントにフォールバックし、外観が変わります | +| **Transparent background needed** | `imgOptions.BackgroundColor = Color.Transparent` を設定する | PNG を他のグラフィックに埋め込む際に便利です | +| **Batch conversion** | HTML 文字列やファイルパスのリストをループし、同じ `ImageRenderingOptions` オブジェクトを再利用する | パフォーマンスが向上し、レンダリング設定が一貫します | + +## Pro tip: caching rendering options + +各変換ごとに新しい `ImageRenderingOptions` オブジェクトを作成するとオーバーヘッドが増えます。多数の HTML スニペットをサービスで処理する場合は、静的インスタンスを宣言して再利用しましょう。 + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +呼び出し間で `SharedOptions` を使い回すことで CPU 使用率を抑えられます。 + +## Frequently asked questions + +**Q: Does this work with .NET Core on macOS?** +A: Yes. Aspose.HTML は完全にクロスプラットフォームです。必要なフォントがインストールされ、出力ディレクトリに書き込み権限があることを確認してください。 + +**Q: Can I render to JPEG instead of PNG?** +A: `RenderToImage("output.png", imgOptions)` を `RenderToImage("output.jpg", imgOptions)` に置き換えるだけです。品質を細かく制御したい場合は `imgOptions.ImageFormat = ImageFormat.Jpeg` も設定できます。 + +**Q: How do I embed external CSS files?** +A: CSS 内容を文字列として読み込み連結するか、`` タグでリモートスタイルシートを参照してください。URL からドキュメントをロードすると Aspose が `` タグを自動的に解決します。 + +## Conclusion + +これで **how to use Aspose** を使って **render HTML to PNG**(または他のラスタ形式)を高品質設定で行う方法が分かりました。チュートリアルでは Aspose.HTML のインストール、アンチエイリアシングとテキストヒンティングの設定、CSS の注入、HTML のロード、そして最終的に **saving HTML as PNG** までをカバーしました。この手順に従えば、Windows、Linux、macOS のいずれの .NET アプリケーションでも確実に **convert HTML to PNG** が実現できます。 + +### Next steps + +* ファイル拡張子を変更して **render html as image** JPEG や BMP など他の出力形式を試す。 +* この手法を **Aspose.PDF** と組み合わせて、PNG を PDF レポートに埋め込む。 +* `ImageRenderingOptions.DpiX` と `DpiY` を調整して高解像度サムネイルを作成する。 + +コードはバッチ処理や動的 HTML 生成、オンデマンドで PNG プレビューを返す Web サービスへの統合など、さまざまなシナリオに合わせて自由にカスタマイズしてください。Happy rendering! + +## What Should You Learn Next? + +以下のチュートリアルは、本ガイドで示した手法を基にした関連トピックを扱っています。各リソースには完全な動作コード例とステップバイステップの解説が含まれており、追加の API 機能を習得したり、別の実装アプローチを自分のプロジェクトで試したりするのに役立ちます。 + +- [Aspose を使用して HTML を PNG にレンダリングする方法 – ステップバイステップガイド](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Aspose で HTML を PNG にレンダリングする方法 – 完全ガイド](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [HTML から画像へのチュートリアル – Aspose.HTML を使用した C# での HTML を PNG にレンダリング](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 20eb1839e7..8505d8b2cb 100644 --- a/html/korean/net/html-extensions-and-conversions/_index.md +++ b/html/korean/net/html-extensions-and-conversions/_index.md @@ -110,7 +110,7 @@ Aspose.HTML for .NET을 사용하여 C#에서 HTML 파일을 ZIP으로 압축하 ### [C#에서 HTML을 ZIP으로 저장 – 완전 단계별 가이드](./save-html-as-zip-in-c-complete-step-by-step-guide/) Aspose.HTML for .NET을 사용하여 C#에서 HTML을 ZIP 파일로 저장하는 방법을 단계별로 안내합니다. ### [C#에서 HTML을 ZIP으로 저장 – 완전 가이드](./save-html-to-zip-in-c-complete-guide/) -Aspose.HTML for .NET을 사용하여 C#에서 HTML을 ZIP 파일로 저장하는 전체 단계별 가이드. +Aspose.HTML for .NET을 사용해 C#에서 HTML을 ZIP 파일로 저장하는 전체 단계별 가이드를 확인하세요. ### [단일 파일 HTML – C#에서 웹 페이지를 하나의 HTML 파일로 저장](./single-file-html-save-a-web-page-as-one-html-file-in-c/) Aspose.HTML for .NET을 사용하여 C#에서 웹 페이지를 단일 HTML 파일로 저장하는 단계별 가이드. ### [C#에서 HTML을 Zip으로 압축하는 방법 – 사용자 정의 리소스 핸들러 튜토리얼](./how-to-zip-html-in-c-custom-resource-handler-tutorial/) @@ -125,6 +125,8 @@ Aspose.HTML의 핸들러를 활용해 HTML을 로드하고 ZIP 파일로 저장 Aspose.HTML for .NET을 사용해 C#에서 HTML을 ZIP 파일로 저장하는 전체 단계별 가이드를 확인하세요. ### [C#에서 HTML을 PDF로 저장하기 – 글꼴 포함 전체 가이드](./save-html-as-pdf-in-c-complete-guide-with-fonts/) Aspose.HTML for .NET을 사용해 C#에서 글꼴을 포함한 HTML을 PDF로 저장하는 전체 단계별 가이드를 확인하세요. +### [Aspose.HTML을 사용하여 HTML을 ZIP으로 저장하고 이미지 포함하기](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Aspose.HTML for .NET을 사용해 HTML을 ZIP 파일로 저장하고 이미지 파일을 포함하는 방법을 단계별로 안내합니다. ### [HTML에서 PDF 만들기 – 개발자를 위한 단계별 가이드](./create-pdf-from-html-step-by-step-guide-for-developers/) Aspose.HTML for .NET을 활용해 HTML을 PDF로 변환하는 개발자용 단계별 가이드입니다. diff --git a/html/korean/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/korean/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..3afc1b2b4c --- /dev/null +++ b/html/korean/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,331 @@ +--- +category: general +date: 2026-10-02 +description: Aspose.HTML을 사용하여 C#에서 HTML을 zip으로 저장하는 방법을 배웁니다. 이 가이드는 이미지가 포함된 HTML을 + 하나의 압축 파일로 저장하는 방법도 보여줍니다. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: ko +lastmod: 2026-10-02 +og_description: C#에서 Aspose.HTML을 사용해 HTML을 zip 파일로 저장합니다. 이 완전한 튜토리얼을 따라 HTML과 이미지를 + 하나의 아카이브에 저장하는 방법을 배워보세요. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Aspose.HTML를 사용하여 HTML을 zip으로 저장 – 단계별 C# 가이드 +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Aspose.HTML를 사용하여 HTML을 zip으로 저장하고 이미지 포함하기 +url: /ko/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.HTML와 이미지 포함하여 HTML을 zip으로 저장하는 방법 + +If you need to **save HTML as zip** for easy distribution, this tutorial shows you the exact steps using Aspose.HTML for .NET. Whether you are exporting a static page, an email template, or a report that contains images, you’ll see how to bundle the HTML, CSS, and image files into a single ZIP archive without writing temporary files to disk. + +> **Pro tip:** Install the package via the CLI to keep your project file clean: +> `dotnet add package Aspose.Html` + +## 사전 요구 사항 + +- .NET 6.0 이상 (API는 .NET Framework 4.6+에서도 작동합니다) +- Aspose.HTML for .NET NuGet 패키지 (`Aspose.Html`) +- C# 및 스트림에 대한 기본 지식 +- Visual Studio 2022 또는 .NET 개발을 지원하는 모든 IDE + +> **Pro tip:** 프로젝트 파일을 깔끔하게 유지하려면 CLI를 통해 패키지를 설치하세요: +> `dotnet add package Aspose.Html` + +## Step 1: Aspose.HTML의 출력 모델 이해하기 + +When Aspose.HTML saves a document, it treats every external resource (CSS files, images, fonts, etc.) as a separate **resource**. By default the library writes those resources to the file system. To control the destination you provide a custom `ResourceHandler`. The handler receives a `Resource` object and must return a writable `Stream`. Aspose.HTML then writes the resource data into that stream. + +Using a custom handler lets you: + +- 리소스를 나중에 ZIP 항목이 되는 `MemoryStream`에 직접 기록 +- 리소스를 데이터베이스, 클라우드 스토리지 또는 기타 매체에 저장 +- 파일 이름, 압축 수준, 폴더 계층 구조를 조정 + +## Step 2: ZIP 아카이브에 쓰는 `ResourceHandler` 만들기 + +Below is a fully functional handler that builds a `System.IO.Compression.ZipArchive` in memory. Each resource is added as a new entry whose name mirrors the original URL path, ensuring the browser can resolve relative links when the ZIP is extracted. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### 이 접근 방식이 작동하는 이유 + +- **In‑memory operation**: 디스크에 임시 파일이 생성되지 않아 웹 서비스나 샌드박스 환경에 이상적입니다. +- **Preserves folder hierarchy**: 원본 리소스 URI를 사용함으로써 추출 후에도 상대 참조가 유효합니다. +- **Extensible**: `MemoryStream`을 `FileStream`으로 교체하여 파일에 직접 쓰거나, 클라우드 스토리지를 위한 네트워크 스트림으로 교체할 수 있습니다. + +## Step 3: HTML 문서 로드 또는 생성 + +For demonstration we’ll create a simple HTML string that references an external image. In a real project you would load HTML from a file, a database, or an HTTP response. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Note:** 실제 HTML 파일이 있는 경우 `new HTMLDocument("path/to/file.html")`를 사용하세요. + +## Step 4: 핸들러를 `SaveOptions`에 연결하고 ZIP 저장 + +Now we connect the `ZipResourceHandler` to `SaveOptions.OutputStorage`. When `document.Save` runs, Aspose.HTML will invoke `HandleResource` for each resource, and the handler will populate the ZIP archive. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### 예상 결과 + +- `output.zip`에 포함: + - `index.html` (주 HTML 파일) + - `images/logo.png` (마크업에서 참조된 이미지) + - Aspose.HTML이 자동으로 감지한 추가 CSS 또는 폰트 파일 + +When you extract the archive and open `index.html` in a browser, the image displays correctly—demonstrating **how to save HTML with images** inside a ZIP. + +## Step 5: 아카이브 확인 및 일반적인 문제 해결 + +### 빠른 검증 스크립트 + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Running the script should list `index.html` and `images/logo.png`. If an expected resource is missing: + +- **이미지 URL 확인**: HTML 문서에서 접근 가능해야 합니다. 상대 경로가 가장 좋습니다. +- **리소스 유형 지원 여부 확인**: Aspose.HTML은 일반 웹 포맷(PNG, JPEG, GIF, CSS, JS)을 처리합니다. 특이한 포맷은 수동 추가가 필요할 수 있습니다. +- **`HandleResource` 호출 확인**: 디버깅을 위해 `HandleResource` 내부에 `Console.WriteLine(resource.Uri)`를 추가하세요. + +## Step 6: 고급 변형 + +### 6.1 중간 바이트 배열 없이 파일에 직접 저장 + +If memory usage is a concern for very large documents, replace `MemoryStream` with a `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +그런 다음 다음과 같이 사용합니다: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 엔트리 이름 사용자 정의 + +If you prefer a flat structure (all files at the root), adjust `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 매니페스트 파일 추가 + +Sometimes downstream tools expect a `manifest.json`. You can add it after the main save: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## 일반적인 함정 및 회피 방법 + +| 함정 | 발생 원인 | 해결 방법 | +|------|----------|----------| +| 추출 후 이미지가 깨짐 | HTML 내부 이미지 경로가 ZIP 엔트리 이름과 일치하지 않음. | `ZipArchiveEntry` 생성 시 원본 상대 경로를 유지하세요. | +| 큰 이미지로 인한 메모리 부족 예외 | 매우 큰 파일에 `MemoryStream`을 사용하면 프로세스 메모리 한도를 초과할 수 있음. | `FileStream` 기반 핸들러로 전환 (6.1 참고). | +| CSS URL 누락 | `@import`로 참조된 외부 CSS 파일이 자동으로 감지되지 않음. | 해당 CSS 파일을 수동으로 ZIP에 추가하거나 저장 전에 인라인으로 삽입하세요. | +| 유니코드 문자 깨짐 | 기본 인코딩이 HTML 소스와 스트림 간에 다를 수 있음. | HTML 문자열이 UTF‑8인지 확인하세요; Aspose.HTML은 문서의 charset을 따릅니다. | + +## 전체 작동 예제 (복사‑붙여넣기 가능) + + + +## 다음에 배워야 할 내용은? + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Aspose.HTML에서 핸들러 사용 방법 – HTML 로드, ZIP으로 저장](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [C#에서 HTML 저장하기 – 사용자 정의 리소스 핸들러 & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [C#로 HTML을 PNG로 렌더링하고 ZIP에 저장 – 완전 가이드](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 e76e190560..45cef76567 100644 --- a/html/korean/net/rendering-html-documents/_index.md +++ b/html/korean/net/rendering-html-documents/_index.md @@ -40,6 +40,9 @@ Aspose.HTML for .NET은 풍부한 기능, 훌륭한 설명서, 활발한 커뮤 이제 Aspose.HTML for .NET을 설정했으므로 HTML 렌더링을 마스터하는 데 도움이 되는 튜토리얼을 살펴볼 차례입니다. 아래는 HTML 문서 렌더링의 다양한 측면을 다루는 튜토리얼 목록입니다. +### [How to use Aspose to render HTML to PNG image in C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) + + ### [Aspose.HTML을 사용하여 .NET에서 HTML을 PNG로 렌더링합니다.](./render-html-as-png/) .NET용 Aspose.HTML을 사용하는 방법을 배우세요: HTML을 조작하고, 다양한 형식으로 변환하고, 더 많은 것을 하세요. 이 포괄적인 튜토리얼에 뛰어드세요! ### [C#에서 HTML을 PNG로 렌더링 – 완전 단계별 가이드](./render-html-to-png-in-c-complete-step-by-step-guide/) diff --git a/html/korean/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/korean/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..2123a93975 --- /dev/null +++ b/html/korean/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-10-02 +description: Aspose를 사용하여 HTML을 PNG 이미지로 빠르게 렌더링하는 방법 – 안티앨리어싱 및 텍스트 힌팅을 적용해 HTML을 + PNG로 변환하는 방법을 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: ko +lastmod: 2026-10-02 +og_description: Aspose를 사용하여 HTML을 PNG 이미지로 렌더링하는 방법. C#에서 고품질 렌더링으로 HTML을 PNG로 변환하는 + 완전한 튜토리얼을 따라보세요. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Aspose를 사용하여 HTML을 PNG 이미지로 렌더링하는 방법 – 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: C#에서 Aspose를 사용하여 HTML을 PNG 이미지로 렌더링하는 방법 +url: /ko/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 Aspose를 사용해 HTML을 PNG 이미지로 렌더링하는 방법 + +**HTML을 PNG 이미지로 렌더링하는 방법**은 웹 페이지의 비트맵 미리보기, 이메일 썸네일, 혹은 PDF 친화적인 스냅샷이 필요할 때 흔히 요구되는 작업입니다. 이 튜토리얼에서는 **render html to image**를 안티앨리어싱 및 텍스트 힌팅과 함께 수행하는 완전한 실행 가능한 솔루션을 보여줍니다. 결과물은 모든 플랫폼에서 선명하게 표시됩니다. + +이 튜토리얼을 통해 **HTML을 PNG로 변환**하는 방법, 렌더링 옵션 설정 방법, Linux 폰트 렌더링 및 파일 시스템 권한과 같은 일반적인 함정들을 다루는 방법을 배울 수 있습니다. 외부 도구는 전혀 필요하지 않으며, Aspose.HTML for .NET 라이브러리와 몇 줄의 C# 코드만 있으면 됩니다. + +## Prerequisites + +시작하기 전에 다음이 준비되어 있는지 확인하세요: + +* .NET 6.0 SDK 이상이 설치되어 있음 +* Visual Studio 2022 (또는 기타 C# IDE) +* **Aspose.HTML**에 대한 NuGet 참조 (`Install-Package Aspose.HTML`) +* C# 문법에 대한 기본적인 이해 + +이 전제 조건들은 가볍고, Aspose.HTML이 크로스‑플랫폼이기 때문에 Windows, Linux, macOS 모두에서 동작합니다. + +## Step 1: Install Aspose.HTML and create a new console project + +터미널이나 Package Manager Console을 열고 다음을 실행합니다: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +전용 프로젝트를 만들면 종속성을 격리할 수 있어 `dotnet run`으로 샘플을 쉽게 실행할 수 있습니다. + +## Step 2: Set up image rendering options (anti‑aliasing and text hinting) + +Antialiasing은 가장자리를 부드럽게 만들고, text hinting은 특히 Linux에서 폰트 래스터화가 Windows와 다를 때 글리프 선명도를 향상시킵니다. `ImageRenderingOptions` 클래스를 사용하면 두 기능을 모두 활성화할 수 있습니다: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**왜 중요한가:** 안티앨리어싱이 없으면 대각선 및 곡선이 들쭉날쭉하게 보입니다. 텍스트 힌팅이 없으면 작은 글꼴 크기가 흐릿해져 **save html as png** 시 썸네일 품질이 떨어집니다. + +## Step 3: Define CSS for consistent fonts and heading styles + +CSS를 HTML에 직접 삽입하면 렌더링된 이미지가 디자인 기대치와 일치합니다. 이 예제에서는 기본 폰트를 지정하고 `

`을 이탤릭체로 설정합니다: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +색상, 마진, 미디어 쿼리 등으로 스타일시트를 확장할 수 있습니다. CSS는 HTML 문서의 ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**팁:** 원격 페이지에서 **render html as image** 해야 한다면 문자열 생성자를 `new HTMLDocument("https://example.com")` 로 교체하세요. Aspose가 페이지를 다운로드하고 리소스를 해석한 뒤 최종 레이아웃을 렌더링합니다. + +## Step 5: Render the document to a PNG file + +이제 `RenderToImage`를 호출하고 출력 경로와 앞서 설정한 옵션을 전달합니다: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +생성된 `output.png`는 안티앨리어싱 및 힌팅 설정 덕분에 이탤릭 스타일이 적용된 `

` 요소를 선명하게 렌더링합니다. + +## Full program listing + +다음 코드를 `Program.cs`에 복사하세요. 그대로 컴파일하고 실행할 수 있습니다: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Expected output + +프로그램을 실행하면 프로젝트 폴더에 `output.png`가 생성됩니다. 이미지에는 이탤릭 Arial로 표시된 **Sample**이라는 단어가 부드러운 가장자리와 선명한 텍스트로 나타납니다. 이미지 뷰어로 열어 품질을 확인해 보세요. + +## Step 6: Common variations and edge‑case handling + +| Situation | What to adjust | Reason | +|-----------|----------------|--------| +| **Large HTML pages** | `ImageRenderingOptions.Width` / `Height` 또는 `PageSize`를 설정해 출력 크기 제어 | 메모리 과다 사용을 방지하고 PNG가 UI에 맞게 맞춰짐 | +| **Linux font missing** | 호스트에 필요한 폰트를 설치(`apt-get install fonts‑arial` 등)하고 `FontSettings`를 통해 Aspose에 지정 | 폰트가 없으면 Aspose가 일반 폰트로 대체해 외관이 달라짐 | +| **Transparent background needed** | `imgOptions.BackgroundColor = Color.Transparent` 설정 | PNG를 다른 그래픽에 삽입할 때 유용 | +| **Batch conversion** | HTML 문자열 또는 파일 경로 리스트를 순회하면서 동일한 `ImageRenderingOptions` 객체 재사용 | 성능 향상 및 렌더링 설정 일관성 유지 | + +## Pro tip: caching rendering options + +각 변환마다 새로운 `ImageRenderingOptions` 객체를 만들면 오버헤드가 발생합니다. 서비스에서 많은 HTML 스니펫을 처리한다면 정적 인스턴스를 선언하세요: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +`SharedOptions`를 재사용하면 CPU 사용량을 낮출 수 있습니다. + +## Frequently asked questions + +**Q: Does this work with .NET Core on macOS?** +A: Yes. Aspose.HTML은 완전한 크로스‑플랫폼을 지원합니다. 필요한 폰트가 설치되어 있고 출력 디렉터리에 쓰기 권한이 있으면 됩니다. + +**Q: Can I render to JPEG instead of PNG?** +A: `RenderToImage("output.png", imgOptions)`를 `RenderToImage("output.jpg", imgOptions)`로 바꾸면 됩니다. 품질을 세밀하게 제어하려면 `imgOptions.ImageFormat = ImageFormat.Jpeg`도 설정하세요. + +**Q: How do I embed external CSS files?** +A: CSS 내용을 문자열로 로드해 연결하거나 `` 태그에 원격 스타일시트를 참조하면 됩니다. Aspose는 URL에서 문서를 로드할 때 `` 태그를 자동으로 해석합니다. + +## Conclusion + +이제 **Aspose를 사용해 HTML을 PNG**(또는 다른 래스터 포맷)로 고품질 설정으로 렌더링하는 방법을 알게 되었습니다. 튜토리얼에서는 Aspose.HTML 설치, 안티앨리어싱 및 텍스트 힌팅 설정, CSS 삽입, HTML 로드, 그리고 최종 **save html as png**까지 다루었습니다. 이 단계를 따라 하면 Windows, Linux, macOS 어느 환경에서도 .NET 애플리케이션에서 **HTML을 PNG로 변환**할 수 있습니다. + +### Next steps + +* 파일 확장자를 바꿔 **render html as image** JPEG 또는 BMP 등 다른 출력 포맷을 탐색하세요. +* 이 방법을 **Aspose.PDF**와 결합해 PNG를 PDF 보고서에 삽입해 보세요. +* 고해상도 썸네일을 위해 `ImageRenderingOptions.DpiX`와 `DpiY`를 실험해 보세요. + +코드를 배치 처리, 동적 HTML 생성, 혹은 PNG 미리보기를 실시간으로 반환하는 웹 서비스와 통합하도록 자유롭게 변형하세요. 즐거운 렌더링 되세요! + +## What Should You Learn Next? + +다음 튜토리얼들은 이 가이드에서 배운 기술을 기반으로 하며, 추가 API 기능을 마스터하고 다양한 구현 방식을 탐색할 수 있도록 단계별 코드 예제와 설명을 제공합니다. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 d58d3b4ee1..202a20f317 100644 --- a/html/polish/net/html-extensions-and-conversions/_index.md +++ b/html/polish/net/html-extensions-and-conversions/_index.md @@ -70,7 +70,7 @@ Dowiedz się, jak wykorzystać moc Aspose.HTML dla .NET w tym przewodniku krok p ### [Konwertuj HTML na GIF w .NET za pomocą Aspose.HTML](./convert-html-to-gif/) Odkryj moc Aspose.HTML dla .NET: przewodnik krok po kroku po konwersji HTML na GIF. Wymagania wstępne, przykłady kodu, FAQ i więcej! Zoptymalizuj manipulację HTML za pomocą Aspose.HTML. ### [Konwersja HTML do JPEG w .NET za pomocą Aspose.HTML](./convert-html-to-jpeg/) -Dowiedz się, jak konwertować HTML na JPEG w .NET za pomocą Aspose.HTML dla .NET. Przewodnik krok po kroku, jak wykorzystać moc Aspose.HTML dla .NET. Zoptymalizuj swoje zadania związane z tworzeniem stron internetowych bez wysiłku. +Dowiedz się, jak konwertować HTML na JPEG w .NET przy użyciu Aspose.HTML dla .NET. Przewodnik krok po kroku, jak wykorzystać moc Aspose.HTML dla .NET. Zoptymalizuj swoje zadania związane z tworzeniem stron internetowych bez wysiłku. ### [Konwersja HTML do Markdown w .NET za pomocą Aspose.HTML](./convert-html-to-markdown/) Dowiedz się, jak konwertować HTML na Markdown w .NET przy użyciu Aspose.HTML w celu wydajnej manipulacji treścią. Uzyskaj wskazówki krok po kroku dotyczące płynnego procesu konwersji. ### [Konwersja HTML do MHTML w .NET za pomocą Aspose.HTML](./convert-html-to-mhtml/) @@ -130,6 +130,8 @@ Dowiedz się, jak w C# zapisać dokument HTML jako archiwum ZIP, korzystając z ### [Ustaw rozmiar strony PDF w C# – konwertuj HTML do PDF](./set-pdf-page-size-in-c-convert-html-to-pdf/) Dowiedz się, jak ustawić rozmiar strony PDF w C# podczas konwersji HTML do PDF przy użyciu Aspose.HTML. +### [Jak zapisać HTML jako zip przy użyciu Aspose.HTML i uwzględnić obrazy](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) + ## Wniosek Podsumowując, rozszerzenia i konwersje HTML są niezbędnymi elementami nowoczesnego rozwoju sieci. Aspose.HTML dla .NET upraszcza proces i czyni go dostępnym dla programistów na każdym poziomie. Postępując zgodnie z naszymi samouczkami, będziesz na dobrej drodze do stania się biegłym programistą sieciowym o szerokim zestawie umiejętności. diff --git a/html/polish/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/polish/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..585e5b6d67 --- /dev/null +++ b/html/polish/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,344 @@ +--- +category: general +date: 2026-10-02 +description: Dowiedz się, jak zapisać HTML jako zip przy użyciu Aspose.HTML w C#. + Ten przewodnik pokazuje również, jak zapisać HTML z obrazami w jednym archiwum. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: pl +lastmod: 2026-10-02 +og_description: Zapisz HTML jako zip przy użyciu Aspose.HTML w C#. Przejdź ten kompletny + samouczek, aby dowiedzieć się, jak zapisać HTML z obrazami w jednym archiwum. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Zapisz HTML jako zip przy użyciu Aspose.HTML – krok po kroku przewodnik + C# +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Jak zapisać HTML jako zip przy użyciu Aspose.HTML i dołączyć obrazy +url: /pl/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak zapisać HTML jako zip przy użyciu Aspose.HTML i dołączyć obrazy + +Jeśli potrzebujesz **zapisać HTML jako zip** w celu łatwej dystrybucji, ten samouczek pokaże Ci dokładne kroki przy użyciu Aspose.HTML dla .NET. Niezależnie od tego, czy eksportujesz statyczną stronę, szablon e‑maila, czy raport zawierający obrazy, zobaczysz, jak spakować pliki HTML, CSS i obrazy do jednego archiwum ZIP bez tworzenia tymczasowych plików na dysku. + +Oprócz głównego celu, odpowiemy także na częste pytanie **jak zapisać HTML z obrazami**, tak aby powstałe archiwum mogło być otwarte w dowolnej przeglądarce bez brakujących zasobów. + +Pod koniec tego przewodnika będziesz mieć gotową implementację `ResourceHandler`, kompletny program w C#, który generuje `output.zip`, oraz praktyczne wskazówki dotyczące obsługi dużych obrazów lub niestandardowych struktur folderów. + +## Wymagania wstępne + +- .NET 6.0 lub nowszy (API działa także z .NET Framework 4.6+) +- Pakiet NuGet Aspose.HTML for .NET (`Aspose.Html`) +- Podstawowa znajomość C# i strumieni +- Visual Studio 2022 lub dowolne IDE obsługujące rozwój w .NET + +> **Pro tip:** Zainstaluj pakiet za pomocą CLI, aby utrzymać plik projektu w czystości: +> `dotnet add package Aspose.Html` + +## Krok 1: Zrozumienie modelu wyjściowego Aspose.HTML + +Gdy Aspose.HTML zapisuje dokument, traktuje każdy zewnętrzny zasób (pliki CSS, obrazy, czcionki itp.) jako osobny **resource**. Domyślnie biblioteka zapisuje te zasoby w systemie plików. Aby kontrolować miejsce docelowe, podajesz własny `ResourceHandler`. Obsługa otrzymuje obiekt `Resource` i musi zwrócić zapisywalny `Stream`. Aspose.HTML następnie zapisuje dane zasobu do tego strumienia. + +Użycie własnego handlera pozwala na: + +- Zapisywanie zasobów bezpośrednio do `MemoryStream`, który później staje się wpisem ZIP +- Przechowywanie zasobów w bazie danych, chmurze lub innym medium +- Dostosowanie nazw plików, poziomów kompresji lub hierarchii folderów + +## Krok 2: Utworzenie `ResourceHandler`, który zapisuje do archiwum ZIP + +Poniżej znajduje się w pełni funkcjonalny handler, który buduje `System.IO.Compression.ZipArchive` w pamięci. Każdy zasób jest dodawany jako nowy wpis, którego nazwa odzwierciedla oryginalną ścieżkę URL, zapewniając, że przeglądarka będzie mogła rozwiązać względne odnośniki po rozpakowaniu ZIP. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Dlaczego to podejście działa + +- **Operacja w pamięci**: Nie są tworzone tymczasowe pliki na dysku, co jest idealne dla usług webowych lub środowisk sandbox. +- **Zachowanie hierarchii folderów**: Dzięki użyciu oryginalnego URI zasobu, odwołania względne pozostają prawidłowe po rozpakowaniu. +- **Rozszerzalność**: Możesz zamienić `MemoryStream` na `FileStream`, aby zapisywać bezpośrednio do pliku, lub na strumień sieciowy dla przechowywania w chmurze. + +## Krok 3: Załadowanie lub utworzenie dokumentu HTML + +Dla demonstracji utworzymy prosty ciąg HTML, który odwołuje się do zewnętrznego obrazu. W rzeczywistym projekcie ładowałbyś HTML z pliku, bazy danych lub odpowiedzi HTTP. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Uwaga:** Jeśli masz fizyczny plik HTML, użyj `new HTMLDocument("path/to/file.html")` zamiast tego. + +## Krok 4: Podłączenie handlera do `SaveOptions` i zapis ZIP + +Teraz łączymy `ZipResourceHandler` z `SaveOptions.OutputStorage`. Gdy wywołane zostanie `document.Save`, Aspose.HTML wywoła `HandleResource` dla każdego zasobu, a handler wypełni archiwum ZIP. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Oczekiwany rezultat + +- `output.zip` zawiera: + - `index.html` (główny plik HTML) + - `images/logo.png` (obraz odwołany w znaczniku) + - Wszelkie dodatkowe pliki CSS lub czcionki automatycznie wykryte przez Aspose.HTML + +Po rozpakowaniu archiwum i otwarciu `index.html` w przeglądarce, obraz wyświetli się poprawnie — co demonstruje **jak zapisać HTML z obrazami** wewnątrz ZIP. + +## Krok 5: Weryfikacja archiwum i rozwiązywanie typowych problemów + +### Szybki skrypt weryfikacyjny + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Uruchomienie skryptu powinno wypisać `index.html` oraz `images/logo.png`. Jeśli oczekiwany zasób jest brakujący: + +- **Sprawdź URL obrazu**: Musi być dostępny z dokumentu HTML. Najlepiej działają ścieżki względne. +- **Upewnij się, że typ zasobu jest obsługiwany**: Aspose.HTML obsługuje popularne formaty webowe (PNG, JPEG, GIF, CSS, JS). Nietypowe formaty mogą wymagać ręcznego dodania. +- **Potwierdź wywołanie `HandleResource`**: Dodaj `Console.WriteLine(resource.Uri)` wewnątrz `HandleResource`, aby debugować. + +## Krok 6: Zaawansowane warianty + +### 6.1 Zapis bezpośrednio do pliku bez pośredniej tablicy bajtów + +Jeśli zużycie pamięci jest problemem przy bardzo dużych dokumentach, zamień `MemoryStream` na `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Następnie użyj go w ten sposób: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Dostosowywanie nazw wpisów + +Jeśli wolisz płaską strukturę (wszystkie pliki w katalogu głównym), zmodyfikuj `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Dodawanie pliku manifestu + +Czasami narzędzia downstream oczekują pliku `manifest.json`. Możesz go dodać po głównym zapisie: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Typowe pułapki i jak ich unikać + +| Pułapka | Dlaczego się pojawia | Rozwiązanie | +|---------|----------------------|-------------| +| Obrazy wyświetlają się jako zepsute po rozpakowaniu | Ścieżka obrazu w HTML nie odpowiada nazwie wpisu w ZIP | Zachowaj oryginalną względną ścieżkę przy tworzeniu `ZipArchiveEntry`. | +| Duże obrazy powodują wyjątki out‑of‑memory | Używanie `MemoryStream` dla bardzo dużych plików może przekroczyć limit pamięci procesu | Przejdź na handler oparty na `FileStream` (zob. 6.1). | +| Brakujące URL‑e CSS | Zewnętrzne pliki CSS odwoływane przez `@import` nie są wykrywane automatycznie | Ręcznie dodaj te pliki CSS do ZIP lub osadź je inline przed zapisem. | +| Znaki Unicode są zniekształcone | Domyślne kodowanie może różnić się między źródłem HTML a strumieniem | Upewnij się, że ciąg HTML jest w UTF‑8; Aspose.HTML respektuje charset dokumentu. | + +## Pełny działający przykład (gotowy do skopiowania) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## Co powinieneś nauczyć się dalej? + + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [jak używać handlera w Aspose.HTML – Load HTML, Save as ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Jak zapisać HTML w C# – Custom Resource Handlers & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Render HTML to PNG and Save to ZIP with C# – Complete Guide](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 d93c40e7cd..8d6153cd7a 100644 --- a/html/polish/net/rendering-html-documents/_index.md +++ b/html/polish/net/rendering-html-documents/_index.md @@ -51,34 +51,15 @@ Naucz się, jak przy użyciu Aspose.HTML w C# renderować HTML do PNG i zapisywa 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. - -### [Jak renderować HTML do PNG przy użyciu Aspose – Kompletny przewodnik](./how-to-render-html-to-png-with-aspose-complete-guide/) -Pełny przewodnik pokazujący, jak przy użyciu Aspose.HTML renderować dokumenty HTML do formatu PNG krok po kroku. - -### [Jak renderować HTML do PNG w C# – przewodnik krok po kroku](./how-to-render-html-to-png-in-c-step-by-step-guide/) -Kompletny przewodnik w C#, pokazujący, jak przy użyciu Aspose.HTML renderować HTML do formatu PNG krok po kroku. -### [Jak renderować HTML jako PNG w C# – Przewodnik krok po kroku](./how-to-render-html-as-png-in-c-step-by-step-guide/) -Kompletny przewodnik w C# pokazujący, jak przy użyciu Aspose.HTML renderować HTML jako PNG krok po kroku. - -### [Renderuj EPUB jako XPS w .NET za pomocą Aspose.HTML](./render-epub-as-xps/) -Dowiedz się, jak tworzyć i renderować dokumenty HTML za pomocą Aspose.HTML dla .NET w tym kompleksowym samouczku. Zanurz się w świecie manipulacji HTML, web scrapingu i nie tylko. - -### [Limit czasu renderowania w .NET z Aspose.HTML](./rendering-timeout/) -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! +Pełny przewodnik C# pokazujący, jak przy użyciu Aspose.HTML renderować HTML jako PNG, krok po kroku. -### [Renderowanie wielu dokumentów w .NET za pomocą Aspose.HTML](./render-multiple-documents/) -Naucz się renderować wiele dokumentów HTML za pomocą Aspose.HTML dla .NET. Zwiększ możliwości przetwarzania dokumentów dzięki tej potężnej bibliotece. +### [Jak używać Aspose do renderowania HTML do PNG w C#](./how-to-use-aspose-to-render-html-to-png-in-c/) +Poznaj krok po kroku, jak przy użyciu Aspose.HTML renderować dokumenty HTML do formatu PNG w języku C#. +### [Jak używać Aspose do renderowania HTML do obrazu PNG w C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Naucz się, jak przy użyciu Aspose.HTML w C# renderować HTML do obrazu PNG krok po kroku. +### [Jak renderować HTML do obrazu w C# – Kompletny przewodnik](./how-to-render-html-to-an-image-with-c-complete-guide/) +Pełny przewodnik, jak przy użyciu Aspose.HTML w C# renderować HTML do obrazu, krok po kroku. -### [Renderuj SVG Doc jako PNG w .NET za pomocą Aspose.HTML](./render-svg-doc-as-png/) -Odblokuj moc Aspose.HTML dla .NET! Dowiedz się, jak bez wysiłku renderować SVG Doc jako PNG. Zanurz się w przykładach krok po kroku i FAQ. Zacznij teraz! -### [Jak renderować HTML w C# – Kompletny przewodnik po stylizacji akapitów](./how-to-render-html-in-c-complete-guide-to-styling-paragraphs/) -Naucz się renderować HTML w C# i stylizować akapity w kompletnym przewodniku. ### [Jak renderować HTML – Kompletny przewodnik z własnym obsługiwaczem zasobów](./how-to-render-html-complete-guide-with-custom-resource-handl/) Poznaj pełny przewodnik renderowania HTML w .NET z własnym obsługiwaczem zasobów, aby kontrolować ładowanie plików i stylów. ### [Jak renderować HTML do PNG – Kompletny przewodnik krok po kroku](./how-to-render-html-to-png-complete-step-by-step-guide/) diff --git a/html/polish/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/polish/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..4c7a660c50 --- /dev/null +++ b/html/polish/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-10-02 +description: Jak używać Aspose do szybkiego renderowania HTML do obrazu PNG – dowiedz + się, jak konwertować HTML na PNG z antyaliasingiem i hintowaniem tekstu. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: pl +lastmod: 2026-10-02 +og_description: Jak używać Aspose do renderowania HTML jako obrazu PNG. Śledź ten + kompletny samouczek, aby konwertować HTML na PNG z wysokiej jakości renderowaniem + w C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Jak używać Aspose do renderowania HTML do obrazu PNG – przewodnik krok po + kroku +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Jak używać Aspose do renderowania HTML do obrazu PNG w C# +url: /pl/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak używać Aspose do renderowania HTML na obraz PNG w C# + +**Jak używać Aspose do renderowania HTML na obraz PNG** jest częstym wymaganiem, gdy potrzebujesz podglądu bitmapowego strony internetowej, miniaturki e‑maila lub migawki przyjaznej dla PDF. Ten samouczek pokazuje kompletną, gotową do uruchomienia rozwiązanie, które **renderować html na obraz** z antyaliasingiem i podpowiedziami tekstowymi, dzięki czemu wynik wygląda ostro na każdej platformie. + +Nauczysz się, jak **konwertować HTML na PNG**, konfigurować opcje renderowania i radzić sobie z typowymi problemami, takimi jak renderowanie czcionek w Linuksie oraz uprawnienia systemu plików. Nie są wymagane żadne zewnętrzne narzędzia — wystarczy biblioteka Aspose.HTML dla .NET oraz kilka linii C#. + +## Wymagania wstępne + +Przed rozpoczęciem upewnij się, że masz: + +* .NET 6.0 SDK lub nowszy zainstalowany +* Visual Studio 2022 (lub dowolne IDE C#) +* Odwołanie NuGet do **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Podstawową znajomość składni C# + +Te wymagania są lekkie; samouczek działa na Windows, Linux i macOS, ponieważ Aspose.HTML jest wieloplatformowy. + +## Krok 1: Zainstaluj Aspose.HTML i utwórz nowy projekt konsolowy + +Otwórz terminal lub Package Manager Console i uruchom: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Utworzenie dedykowanego projektu izoluje zależności i ułatwia uruchomienie przykładu przy użyciu `dotnet run`. + +## Krok 2: Skonfiguruj opcje renderowania obrazu (antyaliasing i podpowiedzi tekstowe) + +Antyaliasing wygładza krawędzie, a podpowiedzi tekstowe poprawiają czytelność glifów, szczególnie w Linuksie, gdzie rasteryzacja czcionek różni się od Windows. Klasa `ImageRenderingOptions` pozwala włączyć oba te elementy: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Dlaczego to ważne:** Bez antyaliasingu linie i krzywe wyglądają ząbkowanie. Bez podpowiedzi tekstowych małe rozmiary czcionek mogą stać się rozmyte, co jest zauważalne, gdy **zapisujesz html jako png** dla miniaturek. + +## Krok 3: Zdefiniuj CSS dla spójnych czcionek i stylów nagłówków + +Osadzenie CSS bezpośrednio w HTML zapewnia, że renderowany obraz odpowiada Twoim oczekiwaniom projektowym. W tym przykładzie ustawiamy podstawową czcionkę i sprawiamy, że `

` jest pochyłe: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Możesz rozbudować arkusz stylów o kolory, marginesy lub zapytania medialne. CSS jest wstrzykiwany do znacznika ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Wskazówka:** Jeśli musisz **renderować html jako obraz** z zdalnej strony, zamień konstruktor łańcucha znaków na `new HTMLDocument("https://example.com")`. Aspose pobierze stronę, rozwiąże zasoby i wyrenderuje ostateczny układ. + +## Krok 5: Renderuj dokument do pliku PNG + +Teraz wywołujemy `RenderToImage`, przekazując ścieżkę wyjściową oraz wcześniej skonfigurowane opcje: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +Wygenerowany plik `output.png` będzie zawierał wyraźny rendering elementu `

` z kursywnym stylem Arial, dzięki ustawieniom antyaliasingu i podpowiedziom tekstowym. + +## Pełny listing programu + +Skopiuj poniższy kod do `Program.cs`. Kompiluje się i działa od razu: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Oczekiwany wynik + +Uruchomienie programu tworzy `output.png` w folderze projektu. Obraz pokazuje słowo **Sample** w kursywnym Arial, wyrenderowane z gładkimi krawędziami i wyraźnym tekstem. Otwórz plik w dowolnej przeglądarce obrazów, aby zweryfikować jakość. + +## Krok 6: Typowe warianty i obsługa przypadków brzegowych + +| Sytuacja | Co dostosować | Powód | +|-----------|----------------|--------| +| **Duże strony HTML** | Ustaw `ImageRenderingOptions.Width` / `Height` lub użyj `PageSize`, aby kontrolować wymiary wyjścia | Zapobiega nadmiernemu zużyciu pamięci i zapewnia, że PNG pasuje do Twojego interfejsu | +| **Brak czcionki na Linuxie** | Zainstaluj wymagane czcionki na hoście (`apt-get install fonts‑arial` lub użyj własnego pliku czcionki) i wskaż je Aspose za pomocą `FontSettings` | Bez czcionki Aspose przechodzi na domyślną, co zmienia wygląd | +| **Wymagane przezroczyste tło** | Ustaw `imgOptions.BackgroundColor = Color.Transparent` | Przydatne przy osadzaniu PNG w innych grafikach | +| **Konwersja wsadowa** | Iteruj listę ciągów HTML lub ścieżek plików, ponownie używając tego samego obiektu `ImageRenderingOptions` | Poprawia wydajność i utrzymuje spójne ustawienia renderowania | + +## Pro tip: buforowanie opcji renderowania + +Tworzenie nowego obiektu `ImageRenderingOptions` dla każdej konwersji generuje narzut. Zadeklaruj statyczną instancję, jeśli przetwarzasz wiele fragmentów HTML w usłudze: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Ponowne użycie `SharedOptions` w kolejnych wywołaniach utrzymuje niskie zużycie CPU. + +## Najczęściej zadawane pytania + +**P: Czy to działa z .NET Core na macOS?** +O: Tak. Aspose.HTML jest w pełni wieloplatformowy. Upewnij się, że wymagane czcionki są zainstalowane, a katalog wyjściowy ma prawa zapisu. + +**P: Czy mogę renderować do JPEG zamiast PNG?** +O: Zamień `RenderToImage("output.png", imgOptions)` na `RenderToImage("output.jpg", imgOptions)`. Możesz także ustawić `imgOptions.ImageFormat = ImageFormat.Jpeg` dla precyzyjniejszej kontroli jakości. + +**P: Jak wstawić zewnętrzne pliki CSS?** +O: Wczytaj zawartość CSS do łańcucha znaków i połącz go, lub odwołaj się do zdalnego arkusza stylów w znaczniku ``. Aspose automatycznie rozwiązuje znaczniki `` przy ładowaniu dokumentu z URL. + +## Zakończenie + +Teraz wiesz, **jak używać Aspose** do **renderowania HTML na PNG** (lub inny format rastrowy) z ustawieniami wysokiej jakości. Samouczek obejmował instalację Aspose.HTML, konfigurowanie antyaliasingu i podpowiedzi tekstowych, wstrzykiwanie CSS, wczytywanie HTML oraz ostateczne **zapisywanie HTML jako PNG**. Postępując zgodnie z krokami, możesz niezawodnie **konwertować HTML na PNG** w dowolnej aplikacji .NET, niezależnie od tego, czy działa ona na Windows, Linuxie czy macOS. + +### Następne kroki + +* Eksploruj inne formaty wyjściowe, takie jak **render html as image** JPEG lub BMP, zmieniając rozszerzenie pliku. +* Połącz to podejście z **Aspose.PDF**, aby osadzić PNG w raporcie PDF. +* Eksperymentuj z `ImageRenderingOptions.DpiX` i `DpiY` dla miniatur o wysokiej rozdzielczości. + +Śmiało dostosowuj kod do przetwarzania wsadowego, dynamicznego generowania HTML lub integracji z usługą sieciową zwracającą podglądy PNG na żądanie. Szczęśliwego renderowania! + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia w własnych projektach. + +- [Jak używać Aspose do renderowania HTML na PNG – przewodnik krok po kroku](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Jak renderować HTML do PNG przy użyciu Aspose – kompletny przewodnik](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [samouczek html do obrazu – renderowanie HTML do PNG z Aspose.HTML w C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 e2ff52bcdc..391e52f5db 100644 --- a/html/portuguese/net/html-extensions-and-conversions/_index.md +++ b/html/portuguese/net/html-extensions-and-conversions/_index.md @@ -119,7 +119,7 @@ Aprenda a converter arquivos HTML em arquivos ZIP usando C# e Aspose.HTML. Guia ### [Como Compactar HTML em C# – Guia Completo Passo a Passo](./how-to-zip-html-in-c-complete-step-by-step-guide/) Aprenda a compactar arquivos HTML em um ZIP usando C# com Aspose.HTML, passo a passo e exemplos de código. ### [Salvar HTML como ZIP em C# – Guia Completo Passo a Passo](./save-html-as-zip-in-c-complete-step-by-step-guide/) -Aprenda a salvar arquivos HTML em um arquivo ZIP usando C# com Aspose.HTML. Guia passo a passo com exemplos de código. +Aprenda a salvar arquivos HTML em um arquivo ZIP usando C# com Aspose.HTML. Guia passo a paso com exemplos de código. ### [Manipulador de Recurso Personalizado em C# – Converter HTML para Arquivo ZIP a partir da Memória](./custom-resource-handler-in-c-convert-html-to-zip-archive-fro/) Aprenda a usar um manipulador de recursos personalizado em C# para converter HTML em um arquivo ZIP totalmente em memória. @@ -145,6 +145,9 @@ Aprenda a salvar documentos HTML em um fluxo usando Aspose.HTML para .NET com C# ### [Como usar handler no Aspose.HTML – Carregar HTML, Salvar como ZIP](./how-to-use-handler-in-aspose-html-load-html-save-as-zip/) Aprenda a usar o handler do Aspose.HTML para carregar documentos HTML e salvá-los como arquivos ZIP em C#. +### [Como salvar HTML como zip com Aspose.HTML e incluir imagens](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Aprenda a salvar documentos HTML em um arquivo ZIP incluindo imagens usando Aspose.HTML em C#. + ## 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-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/portuguese/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..e3b76e8a56 --- /dev/null +++ b/html/portuguese/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,343 @@ +--- +category: general +date: 2026-10-02 +description: Aprenda como salvar HTML como zip usando Aspose.HTML em C#. Este guia + também mostra como salvar HTML com imagens em um único arquivo. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: pt +lastmod: 2026-10-02 +og_description: Salve HTML como zip usando Aspose.HTML em C#. Siga este tutorial completo + para aprender como salvar HTML com imagens em um único arquivo. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Salvar HTML como zip com Aspose.HTML – guia passo a passo em C# +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Como salvar HTML como zip com Aspose.HTML e incluir imagens +url: /pt/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como salvar HTML como zip com Aspose.HTML e incluir imagens + +Se você precisa **salvar HTML como zip** para facilitar a distribuição, este tutorial mostra os passos exatos usando Aspose.HTML para .NET. Seja exportando uma página estática, um modelo de e‑mail ou um relatório que contém imagens, você verá como agrupar os arquivos HTML, CSS e de imagem em um único arquivo ZIP sem gravar arquivos temporários no disco. + +Além do objetivo principal, também responderemos à pergunta comum de acompanhamento **como salvar HTML com imagens** para que o arquivo resultante possa ser aberto por qualquer navegador sem recursos ausentes. + +Ao final deste guia você terá uma implementação reutilizável de `ResourceHandler`, um programa C# completo que produz `output.zip` e dicas práticas para lidar com imagens grandes ou estruturas de pastas personalizadas. + +## Pré‑requisitos + +- .NET 6.0 ou superior (a API também funciona com .NET Framework 4.6+) +- Pacote NuGet Aspose.HTML for .NET (`Aspose.Html`) +- Conhecimento básico de C# e streams +- Visual Studio 2022 ou qualquer IDE que suporte desenvolvimento .NET + +> **Dica profissional:** Instale o pacote via CLI para manter seu arquivo de projeto limpo: +> `dotnet add package Aspose.Html` + +## Etapa 1: Entender o modelo de saída do Aspose.HTML + +Quando o Aspose.HTML salva um documento, ele trata cada recurso externo (arquivos CSS, imagens, fontes, etc.) como um **recurso** separado. Por padrão, a biblioteca grava esses recursos no sistema de arquivos. Para controlar o destino, você fornece um `ResourceHandler` personalizado. O handler recebe um objeto `Resource` e deve retornar um `Stream` gravável. O Aspose.HTML então escreve os dados do recurso nesse stream. + +Usar um handler personalizado permite: + +- Gravar recursos diretamente em um `MemoryStream` que depois se torna uma entrada ZIP +- Armazenar recursos em um banco de dados, armazenamento em nuvem ou qualquer outro meio +- Ajustar nomes de arquivos, níveis de compressão ou hierarquias de pastas + +## Etapa 2: Criar um `ResourceHandler` que grava em um arquivo ZIP + +Abaixo está um handler totalmente funcional que constrói um `System.IO.Compression.ZipArchive` na memória. Cada recurso é adicionado como uma nova entrada cujo nome espelha o caminho original da URL, garantindo que o navegador possa resolver links relativos quando o ZIP for extraído. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Por que essa abordagem funciona + +- **Operação em memória**: Nenhum arquivo temporário é criado no disco, o que é ideal para serviços web ou ambientes sandbox. +- **Preserva a hierarquia de pastas**: Ao usar o URI original do recurso, as referências relativas permanecem válidas após a extração. +- **Extensível**: Você pode substituir `MemoryStream` por um `FileStream` para gravar diretamente em um arquivo, ou por um stream de rede para armazenamento em nuvem. + +## Etapa 3: Carregar ou criar o documento HTML + +Para demonstração, criaremos uma string HTML simples que referencia uma imagem externa. Em um projeto real, você carregaria o HTML de um arquivo, de um banco de dados ou de uma resposta HTTP. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Observação:** Se você tem um arquivo HTML físico, use `new HTMLDocument("path/to/file.html")` em vez disso. + +## Etapa 4: Conectar o handler ao `SaveOptions` e salvar o ZIP + +Agora conectamos o `ZipResourceHandler` ao `SaveOptions.OutputStorage`. Quando `document.Save` for executado, o Aspose.HTML invocará `HandleResource` para cada recurso, e o handler preencherá o arquivo ZIP. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Resultado esperado + +- `output.zip` contém: + - `index.html` (o arquivo HTML principal) + - `images/logo.png` (a imagem referenciada no markup) + - Qualquer arquivo CSS ou fonte adicional detectado automaticamente pelo Aspose.HTML + +Ao extrair o arquivo e abrir `index.html` em um navegador, a imagem será exibida corretamente—demonstrando **como salvar HTML com imagens** dentro de um ZIP. + +## Etapa 5: Verificar o arquivo e solucionar problemas comuns + +### Script de verificação rápida + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Executar o script deve listar `index.html` e `images/logo.png`. Se um recurso esperado estiver ausente: + +- **Verifique a URL da imagem**: Ela deve ser acessível a partir do documento HTML. Caminhos relativos funcionam melhor. +- **Garanta que o tipo de recurso seja suportado**: Aspose.HTML lida com formatos web comuns (PNG, JPEG, GIF, CSS, JS). Formatos incomuns podem exigir adição manual. +- **Confirme que `HandleResource` está sendo chamado**: Adicione um `Console.WriteLine(resource.Uri)` dentro de `HandleResource` para depurar. + +## Etapa 6: Variações avançadas + +### 6.1 Salvando diretamente em um arquivo sem um array de bytes intermediário + +Se o uso de memória for uma preocupação para documentos muito grandes, substitua `MemoryStream` por um `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Então use da seguinte forma: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Personalizando nomes de entrada + +Se preferir uma estrutura plana (todos os arquivos na raiz), ajuste `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Adicionando um arquivo de manifesto + +Algumas ferramentas downstream esperam um `manifest.json`. Você pode adicioná‑lo após a gravação principal: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Armadilhas comuns e como evitá‑las + +| Armadilha | Por que acontece | Solução | +|-----------|------------------|---------| +| Imagens aparecem quebradas após a extração | O caminho da imagem dentro do HTML não corresponde ao nome da entrada no ZIP. | Preserve o caminho relativo original ao criar `ZipArchiveEntry`. | +| Imagens grandes causam exceções de falta de memória | Usar `MemoryStream` para arquivos muito grandes pode exceder o limite de memória do processo. | Troque para um handler baseado em `FileStream` (veja 6.1). | +| URLs de CSS estão ausentes | Arquivos CSS externos referenciados via `@import` não são detectados automaticamente. | Adicione manualmente esses arquivos CSS ao ZIP ou incorpore‑os inline antes de salvar. | +| Caracteres Unicode ficam corrompidos | A codificação padrão pode diferir entre a fonte HTML e o stream. | Garanta que a string HTML esteja em UTF‑8; o Aspose.HTML respeita o charset do documento. | + +## Exemplo completo funcional (pronto para copiar e colar) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## O que você deve aprender a seguir? + + +Os tutoriais a seguir cobrem tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas de implementação em seus próprios projetos. + +- [como usar handler no Aspose.HTML – Carregar HTML, Salvar como ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Como salvar HTML em C# – Handlers de recurso personalizados & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Renderizar HTML para PNG e salvar em ZIP com C# – Guia completo](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 bc302d3b94..25ebd72a54 100644 --- a/html/portuguese/net/rendering-html-documents/_index.md +++ b/html/portuguese/net/rendering-html-documents/_index.md @@ -63,6 +63,9 @@ Aprenda a usar Aspose.HTML para converter documentos HTML em imagens PNG usando ### [Como renderizar HTML como PNG em C# – Guia passo a passo](./how-to-render-html-as-png-in-c-step-by-step-guide/) Aprenda a converter HTML em PNG usando Aspose.HTML para .NET com um guia detalhado passo a passo em C#. +### [Como usar Aspose para renderizar HTML em imagem PNG em C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Aprenda a usar Aspose para converter HTML em imagens PNG com C# neste tutorial completo. + ### [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. diff --git a/html/portuguese/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/portuguese/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..5e83c803e7 --- /dev/null +++ b/html/portuguese/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-10-02 +description: Como usar o Aspose para renderizar HTML em imagem PNG rapidamente – aprenda + a converter HTML em PNG com anti‑aliasing e hinting de texto. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: pt +lastmod: 2026-10-02 +og_description: Como usar o Aspose para renderizar HTML em imagem PNG. Siga este tutorial + completo para converter HTML em PNG com renderização de alta qualidade em C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Como usar o Aspose para renderizar HTML em imagem PNG – guia passo a passo +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Como usar o Aspose para renderizar HTML em imagem PNG em C# +url: /pt/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como usar Aspose para renderizar HTML em imagem PNG em C# + +**Como usar Aspose para renderizar HTML em imagem PNG** é uma necessidade comum quando você precisa de uma pré‑visualização bitmap de uma página web, uma miniatura de e‑mail ou uma captura de tela amigável para PDF. Este tutorial mostra uma solução completa, pronta‑para‑executar que **renderiza html para imagem** com anti‑aliasing e text hinting, para que o resultado fique nítido em todas as plataformas. + +Você aprenderá como **converter HTML para PNG**, configurar opções de renderização e lidar com armadilhas típicas, como renderização de fontes no Linux e permissões de sistema de arquivos. Nenhuma ferramenta externa é necessária — apenas a biblioteca Aspose.HTML para .NET e algumas linhas de C#. + +## Pré-requisitos + +* .NET 6.0 SDK ou posterior instalado +* Visual Studio 2022 (ou qualquer IDE C#) +* Uma referência NuGet ao **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Familiaridade básica com a sintaxe C# + +Esses pré-requisitos são leves; o tutorial funciona no Windows, Linux e macOS porque o Aspose.HTML é multiplataforma. + +## Etapa 1: Instalar Aspose.HTML e criar um novo projeto console + +Abra um terminal ou o Package Manager Console e execute: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Criar um projeto dedicado isola as dependências e facilita a execução do exemplo com `dotnet run`. + +## Etapa 2: Configurar opções de renderização de imagem (anti‑aliasing e text hinting) + +Antialiasing suaviza as bordas, enquanto text hinting melhora a clareza dos glifos, especialmente no Linux onde a rasterização de fontes difere do Windows. A classe `ImageRenderingOptions` permite habilitar ambos os recursos: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Por que isso importa:** Sem antialiasing, linhas diagonais e curvas parecem serrilhadas. Sem text hinting, tamanhos de fonte pequenos podem ficar borrados, o que é perceptível ao **salvar html como png** para miniaturas. + +## Etapa 3: Definir CSS para fontes consistentes e estilos de cabeçalhos + +Incorporar CSS diretamente no HTML garante que a imagem renderizada corresponda às suas expectativas de design. Neste exemplo definimos uma fonte base e deixamos `

` em itálico: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Você pode estender a folha de estilos com cores, margens ou media queries. O CSS é inserido na tag ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Dica:** Se precisar **renderizar html como imagem** a partir de uma página remota, substitua o construtor de string por `new HTMLDocument("https://example.com")`. Aspose baixará a página, resolverá os recursos e renderizará o layout final. + +## Etapa 5: Renderizar o documento para um arquivo PNG + +Agora chamamos `RenderToImage`, passando o caminho de saída e as opções que configuramos anteriormente: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +O `output.png` gerado conterá uma renderização nítida do elemento `

` com estilo itálico, graças às configurações de anti‑aliasing e hinting. + +## Listagem completa do programa + +Copie o código a seguir para `Program.cs`. Ele compila e executa como está: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Saída esperada + +Ao executar o programa, ele cria `output.png` na pasta do projeto. A imagem mostra a palavra **Sample** em Arial itálico, renderizada com bordas suaves e texto nítido. Abra o arquivo com qualquer visualizador de imagens para verificar a qualidade. + +## Etapa 6: Variações comuns e tratamento de casos extremos + +| Situação | O que ajustar | Motivo | +|-----------|----------------|--------| +| **Páginas HTML grandes** | Defina `ImageRenderingOptions.Width` / `Height` ou use `PageSize` para controlar as dimensões de saída | Prevém estouro de memória e garante que o PNG se ajuste à sua UI | +| **Fonte Linux ausente** | Instale as fontes necessárias no host (`apt-get install fonts‑arial` ou use um arquivo de fonte personalizado) e aponte o Aspose para ele via `FontSettings` | Sem a fonte, o Aspose recorre a uma genérica, alterando a aparência | +| **Necessário fundo transparente** | Defina `imgOptions.BackgroundColor = Color.Transparent` | Útil ao incorporar o PNG em outras imagens | +| **Conversão em lote** | Itere sobre uma lista de strings HTML ou caminhos de arquivos, reutilizando o mesmo objeto `ImageRenderingOptions` | Melhora o desempenho e mantém as configurações de renderização consistentes | + +## Dica profissional: cache de opções de renderização + +Criar um novo objeto `ImageRenderingOptions` para cada conversão adiciona sobrecarga. Declare uma instância estática se você processar muitos trechos HTML em um serviço: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Reutilize `SharedOptions` nas chamadas para manter o uso de CPU baixo. + +## Perguntas frequentes + +**Q: Isso funciona com .NET Core no macOS?** +A: Sim. Aspose.HTML é totalmente multiplataforma. Certifique‑se de que as fontes necessárias estejam instaladas e que o diretório de saída seja gravável. + +**Q: Posso renderizar para JPEG em vez de PNG?** +A: Substitua `RenderToImage("output.png", imgOptions)` por `RenderToImage("output.jpg", imgOptions)`. Você também pode definir `imgOptions.ImageFormat = ImageFormat.Jpeg` para um controle mais fino da qualidade. + +**Q: Como incorporo arquivos CSS externos?** +A: Carregue o conteúdo CSS em uma string e concatene‑o, ou referencie uma folha de estilo remota na tag ``. Aspose resolve as tags `` automaticamente quando o documento é carregado a partir de uma URL. + +## Conclusão + +Agora você sabe **como usar Aspose** para **renderizar HTML em PNG** (ou qualquer outro formato raster) com configurações de alta qualidade. O tutorial abordou a instalação do Aspose.HTML, a configuração de anti‑aliasing e text hinting, a injeção de CSS, o carregamento de HTML e, finalmente, **salvar HTML como PNG**. Seguindo os passos, você pode converter HTML para PNG de forma confiável em qualquer aplicação .NET, seja ela executada no Windows, Linux ou macOS. + +### Próximos passos + +* Explore outros formatos de saída, como **render html as image** JPEG ou BMP, alterando a extensão do arquivo. +* Combine esta abordagem com **Aspose.PDF** para incorporar o PNG em um relatório PDF. +* Experimente `ImageRenderingOptions.DpiX` e `DpiY` para miniaturas de alta resolução. + +Sinta‑se à vontade para adaptar o código para processamento em lote, geração dinâmica de HTML ou integração a um serviço web que devolve pré‑visualizações PNG sob demanda. Boa renderização! + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos estreitamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Como usar Aspose para renderizar HTML em PNG – Guia passo a passo](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Como renderizar HTML em PNG com Aspose – Guia completo](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [Tutorial html para imagem – Renderizar HTML em PNG com Aspose.HTML em C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 c0207701b1..cc1d988f6c 100644 --- a/html/russian/net/html-extensions-and-conversions/_index.md +++ b/html/russian/net/html-extensions-and-conversions/_index.md @@ -99,7 +99,6 @@ Aspose.HTML для .NET — это не просто библиотека; эт Сохраните HTML в архив ZIP полностью в памяти с помощью Aspose.HTML для .NET, используя C#. ### [Aspose HTML в PDF на C# – Полное руководство с архивом ZIP](./aspose-html-to-pdf-in-c-complete-guide-with-zip-archive/) Узнайте, как конвертировать HTML в PDF на C# с помощью Aspose.HTML и упаковать результат в архив ZIP. - ### [Пользовательский обработчик ресурсов в C# – Конвертировать HTML в ZIP‑архив из памяти](./custom-resource-handler-in-c-convert-html-to-zip-archive-fro/) Узнайте, как создать пользовательский обработчик ресурсов в C# для конвертации HTML в ZIP‑архив непосредственно из памяти с помощью Aspose.HTML. ### [Как заархивировать HTML в C# – загрузить HTML и использовать пользовательский обработчик](./how-to-zip-html-in-c-load-html-use-custom-handler/) @@ -130,6 +129,8 @@ Aspose.HTML для .NET — это не просто библиотека; эт Подробное руководство по сохранению HTML в PDF в C# с поддержкой пользовательских шрифтов. ### [Создайте HTML‑документ и сохраните в ZIP – Полный учебник C#](./create-html-document-and-save-as-zip-complete-c-guide/) Узнайте, как создать HTML‑документ и сохранить его в архив ZIP с помощью Aspose.HTML и C# в полном пошаговом руководстве. +### [Как сохранить HTML в zip с Aspose.HTML и включить изображения](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Сохраните HTML‑страницу в zip‑архив вместе с изображениями, используя Aspose.HTML для .NET. ## Заключение diff --git a/html/russian/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/russian/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..e4bddf8f34 --- /dev/null +++ b/html/russian/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,343 @@ +--- +category: general +date: 2026-10-02 +description: Узнайте, как сохранять HTML в виде zip с помощью Aspose.HTML в C#. Это + руководство также показывает, как сохранять HTML с изображениями в один архив. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: ru +lastmod: 2026-10-02 +og_description: Сохраните HTML в виде zip‑архива с помощью Aspose.HTML в C#. Следуйте + этому полному руководству, чтобы узнать, как сохранить HTML с изображениями в один + архив. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Сохранение HTML в zip с Aspose.HTML – пошаговое руководство по C# +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Как сохранить HTML в zip с помощью Aspose.HTML и включить изображения +url: /ru/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как сохранить HTML в zip с помощью Aspose.HTML и включить изображения + +Если вам необходимо **сохранить HTML в zip** для удобного распространения, этот учебник покажет точные шаги с использованием Aspose.HTML для .NET. Независимо от того, экспортируете ли вы статическую страницу, шаблон письма или отчет, содержащий изображения, вы увидите, как упаковать HTML, CSS и файлы изображений в один ZIP‑архив без записи временных файлов на диск. + +В дополнение к основной цели мы также ответим на часто задаваемый вопрос **как сохранить HTML с изображениями**, чтобы полученный архив можно было открыть в любом браузере без отсутствующих ресурсов. + +К концу этого руководства у вас будет переиспользуемая реализация `ResourceHandler`, полностью готовая программа на C#, создающая `output.zip`, а также практические советы по работе с большими изображениями или пользовательскими структурами папок. + +## Требования + +- .NET 6.0 или новее (API также работает с .NET Framework 4.6+) +- NuGet‑пакет Aspose.HTML для .NET (`Aspose.Html`) +- Базовые знания C# и потоков +- Visual Studio 2022 или любая IDE, поддерживающая разработку на .NET + +> **Совет:** Установите пакет через CLI, чтобы ваш файл проекта оставался чистым: +> `dotnet add package Aspose.Html` + +## Шаг 1: Понимание модели вывода Aspose.HTML + +Когда Aspose.HTML сохраняет документ, он рассматривает каждый внешний ресурс (CSS‑файлы, изображения, шрифты и т.д.) как отдельный **ресурс**. По умолчанию библиотека записывает эти ресурсы в файловую систему. Чтобы управлять местом назначения, вы предоставляете пользовательский `ResourceHandler`. Обработчик получает объект `Resource` и должен вернуть записываемый `Stream`. Затем Aspose.HTML записывает данные ресурса в этот поток. + +Используя пользовательский обработчик, вы можете: + +- Записывать ресурсы напрямую в `MemoryStream`, который позже станет записью в ZIP +- Сохранять ресурсы в базе данных, облачном хранилище или любом другом месте +- Настраивать имена файлов, уровни сжатия или иерархию папок + +## Шаг 2: Создание `ResourceHandler`, который записывает в ZIP‑архив + +Ниже представлен полностью рабочий обработчик, который создает `System.IO.Compression.ZipArchive` в памяти. Каждый ресурс добавляется как новая запись, имя которой отражает исходный путь URL, обеспечивая возможность браузеру разрешать относительные ссылки после извлечения ZIP. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Почему этот подход работает + +- **Операция в памяти**: На диске не создаются временные файлы, что идеально подходит для веб‑служб или изолированных сред. +- **Сохраняет иерархию папок**: Используя исходный URI ресурса, относительные ссылки остаются корректными после извлечения. +- **Расширяемость**: Вы можете заменить `MemoryStream` на `FileStream` для прямой записи в файл или на сетевой поток для облачного хранилища. + +## Шаг 3: Загрузка или создание HTML‑документа + +Для демонстрации мы создадим простую строку HTML, которая ссылается на внешнее изображение. В реальном проекте вы бы загружали HTML из файла, базы данных или HTTP‑ответа. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Примечание:** Если у вас есть физический HTML‑файл, используйте `new HTMLDocument("path/to/file.html")`. + +## Шаг 4: Подключение обработчика к `SaveOptions` и сохранение ZIP + +Теперь мы подключаем `ZipResourceHandler` к `SaveOptions.OutputStorage`. Когда вызывается `document.Save`, Aspose.HTML вызывает `HandleResource` для каждого ресурса, и обработчик заполняет ZIP‑архив. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Ожидаемый результат + +- `output.zip` содержит: + - `index.html` (основной HTML‑файл) + - `images/logo.png` (изображение, указанное в разметке) + - Любые дополнительные CSS‑ или шрифтовые файлы, автоматически обнаруженные Aspose.HTML + +Когда вы извлечете архив и откроете `index.html` в браузере, изображение отобразится корректно — демонстрируя **как сохранить HTML с изображениями** внутри ZIP. + +## Шаг 5: Проверка архива и устранение распространённых проблем + +### Быстрый скрипт проверки + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Запуск скрипта должен вывести `index.html` и `images/logo.png`. Если ожидаемый ресурс отсутствует: + +- **Проверьте URL изображения**: Он должен быть доступен из HTML‑документа. Относительные пути работают лучше всего. +- **Убедитесь, что тип ресурса поддерживается**: Aspose.HTML обрабатывает распространённые веб‑форматы (PNG, JPEG, GIF, CSS, JS). Необычные форматы могут потребовать ручного добавления. +- **Подтвердите, что `HandleResource` вызывается**: Добавьте `Console.WriteLine(resource.Uri)` внутри `HandleResource` для отладки. + +## Шаг 6: Расширенные варианты + +### 6.1 Сохранение напрямую в файл без промежуточного массива байтов + +Если использование памяти является проблемой для очень больших документов, замените `MemoryStream` на `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Затем используйте его так: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Настройка имён записей + +Если вы предпочитаете плоскую структуру (все файлы в корне), измените `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Добавление файла манифеста + +Иногда инструменты нижнего уровня ожидают `manifest.json`. Вы можете добавить его после основного сохранения: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Распространённые подводные камни и как их избежать + +| Подводный камень | Почему происходит | Решение | +|------------------|-------------------|---------| +| Изображения отображаются с ошибками после извлечения | Путь к изображению в HTML не совпадает с именем записи в ZIP. | Сохраняйте исходный относительный путь при создании `ZipArchiveEntry`. | +| Большие изображения вызывают исключения out‑of‑memory | Использование `MemoryStream` для очень больших файлов может превысить лимит памяти процесса. | Перейдите на обработчик, основанный на `FileStream` (см. 6.1). | +| Отсутствуют URL‑ы CSS | Внешние CSS‑файлы, указанные через `@import`, не обнаруживаются автоматически. | Добавьте эти CSS‑файлы в ZIP вручную или внедрите их inline перед сохранением. | +| Unicode‑символы искажаются | Кодировка по умолчанию может отличаться между исходным HTML и потоком. | Убедитесь, что строка HTML в кодировке UTF‑8; Aspose.HTML учитывает charset документа. | + +## Полный рабочий пример (готовый к копированию) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## Что стоит изучить дальше? + +Следующие учебники охватывают тесно связанные темы, опирающиеся на техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [как использовать обработчик в Aspose.HTML – загрузка HTML, сохранение в ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Как сохранить HTML в C# – пользовательские обработчики ресурсов и ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Рендеринг HTML в PNG и сохранение в ZIP с C# – полное руководство](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 14e01cd309..3fbf5b0800 100644 --- a/html/russian/net/rendering-html-documents/_index.md +++ b/html/russian/net/rendering-html-documents/_index.md @@ -78,8 +78,9 @@ Aspose.HTML для .NET выделяется как лучший выбор дл ### [Как использовать Aspose для рендеринга HTML в PNG – пошаговое руководство](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) Подробный пошаговый учебник по использованию Aspose.HTML для конвертации HTML в PNG в .NET. -### [Как отрендерить HTML в PNG с помощью Aspose – Полное руководство](./how-to-render-html-to-png-with-aspose-complete-guide/) -Подробный пошаговый учебник по рендерингу HTML в PNG с использованием Aspose.HTML для .NET. +### [Как использовать Aspose для рендеринга HTML в PNG‑изображение на C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Подробный пошаговый учебник по рендерингу HTML в PNG‑изображение с помощью Aspose.HTML в .NET на C#. + ### [Как отрендерить HTML в PNG – пошаговое руководство](./how-to-render-html-to-png-step-by-step-guide/) Подробный пошаговый учебник по рендерингу HTML в PNG с помощью Aspose.HTML для .NET. ### [Как отрендерить HTML в PNG на C# – пошаговое руководство](./how-to-render-html-to-png-in-c-step-by-step-guide/) diff --git a/html/russian/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/russian/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..4626667325 --- /dev/null +++ b/html/russian/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-10-02 +description: Как использовать Aspose для быстрой отрисовки HTML в PNG‑изображение + — узнайте, как конвертировать HTML в PNG с антиалиасингом и хинтингом текста. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: ru +lastmod: 2026-10-02 +og_description: Как использовать Aspose для рендеринга HTML в PNG‑изображение. Следуйте + этому полному руководству, чтобы преобразовать HTML в PNG с высококачественным рендерингом + на C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Как использовать Aspose для рендеринга HTML в PNG‑изображение – пошаговое + руководство +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Как использовать Aspose для рендеринга HTML в PNG‑изображение на C# +url: /ru/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как использовать Aspose для рендеринга HTML в PNG‑изображение на C# + +**How to use Aspose to render HTML to PNG image** является распространенной задачей, когда нужен растровый предварительный просмотр веб‑страницы, миниатюра письма или снимок, пригодный для PDF. Этот учебник показывает полное, готовое к запуску решение, которое **render html to image** с анти‑алиасингом и подсказкой текста, так что результат выглядит чётко на любой платформе. + +Вы узнаете, как **convert HTML to PNG**, настроить параметры рендеринга и справиться с типичными подводными камнями, такими как рендеринг шрифтов в Linux и разрешения файловой системы. Внешние инструменты не требуются — только библиотека Aspose.HTML для .NET и несколько строк кода на C#. + +## Требования + +* .NET 6.0 SDK или более поздняя версия, установленная +* Visual Studio 2022 (или любой IDE для C#) +* Ссылка NuGet на **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Базовое знакомство с синтаксисом C# + +Эти требования минимальны; учебник работает на Windows, Linux и macOS, поскольку Aspose.HTML кросс‑платформен. + +## Шаг 1: Установите Aspose.HTML и создайте новый консольный проект + +Откройте терминал или консоль диспетчера пакетов и выполните: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Создание отдельного проекта изолирует зависимости и упрощает запуск примера с помощью `dotnet run`. + +## Шаг 2: Настройте параметры рендеринга изображения (anti‑aliasing и text hinting) + +Антиалиасинг сглаживает края, а подсказка текста улучшает чёткость глифов, особенно в Linux, где растеризация шрифтов отличается от Windows. Класс `ImageRenderingOptions` позволяет включить обе функции: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Почему это важно:** Без антиалиасинга диагональные линии и кривые выглядят зубчатыми. Без подсказки текста небольшие размеры шрифта могут стать размытыми, что заметно, когда вы **save html as png** для миниатюр. + +## Шаг 3: Определите CSS для согласованных шрифтов и стилей заголовков + +Встраивание CSS непосредственно в HTML гарантирует, что отрендеренное изображение соответствует вашим дизайнерским ожиданиям. В этом примере мы задаём базовый шрифт и делаем `

` курсивным: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Вы можете расширить таблицу стилей цветами, отступами или медиа‑запросами. CSS внедряется в тег ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Подсказка:** Если вам нужно **render html as image** с удалённой страницы, замените конструктор строки на `new HTMLDocument("https://example.com")`. Aspose загрузит страницу, разрешит ресурсы и отрендерит окончательный макет. + +## Шаг 5: Отрендерите документ в PNG‑файл + +Теперь вызываем `RenderToImage`, передавая путь вывода и параметры, которые мы настроили ранее: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +Сгенерированный `output.png` будет содержать чёткое отображение элемента `

` с курсивным стилем благодаря настройкам антиалиасинга и подсказки. + +## Полный список программы + +Скопируйте следующий код в `Program.cs`. Он компилируется и запускается как есть: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Ожидаемый результат + +Запуск программы создаёт `output.png` в папке проекта. На изображении отображается слово **Sample** курсивным шрифтом Arial, отрендеренное со сглаженными краями и чётким текстом. Откройте файл в любом просмотрщике изображений, чтобы проверить качество. + +## Шаг 6: Распространённые варианты и обработка граничных случаев + +| Ситуация | Что изменить | Причина | +|-----------|----------------|--------| +| **Большие HTML‑страницы** | Установите `ImageRenderingOptions.Width` / `Height` или используйте `PageSize` для контроля размеров вывода | Предотвращает переполнение памяти и гарантирует, что PNG впишется в ваш UI | +| **Отсутствует шрифт в Linux** | Установите необходимые шрифты на хосте (`apt-get install fonts‑arial` или используйте пользовательский файл шрифта) и укажите Aspose на него через `FontSettings` | Без шрифта Aspose переходит к общему, меняя внешний вид | +| **Требуется прозрачный фон** | Установите `imgOptions.BackgroundColor = Color.Transparent` | Полезно при встраивании PNG в другую графику | +| **Пакетное преобразование** | Пройдитесь по списку строк HTML или путей к файлам, переиспользуя один объект `ImageRenderingOptions` | Улучшает производительность и сохраняет согласованные настройки рендеринга | + +## Профессиональный совет: кэширование параметров рендеринга + +Создание нового объекта `ImageRenderingOptions` для каждой конверсии добавляет накладные расходы. Объявите статический экземпляр, если обрабатываете множество HTML‑фрагментов в сервисе: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +## Часто задаваемые вопросы + +**В: Работает ли это с .NET Core на macOS?** +О: Да. Aspose.HTML полностью кросс‑платформен. Убедитесь, что необходимые шрифты установлены, и каталог вывода доступен для записи. + +**В: Можно ли рендерить в JPEG вместо PNG?** +О: Замените `RenderToImage("output.png", imgOptions)` на `RenderToImage("output.jpg", imgOptions)`. Также можно установить `imgOptions.ImageFormat = ImageFormat.Jpeg` для более точного контроля качества. + +**В: Как встроить внешние CSS‑файлы?** +О: Загрузите содержимое CSS в строку и объедините её, либо укажите удалённую таблицу стилей в теге ``. Aspose автоматически обрабатывает теги ``, когда документ загружается по URL. + +## Заключение + +Теперь вы знаете **how to use Aspose** для **render HTML to PNG** (или любого другого растрового формата) с настройками высокого качества. В учебнике рассмотрена установка Aspose.HTML, настройка антиалиасинга и подсказки текста, внедрение CSS, загрузка HTML и, наконец, **saving HTML as PNG**. Следуя шагам, вы надёжно сможете **convert HTML to PNG** в любом приложении .NET, независимо от того, работает ли оно на Windows, Linux или macOS. + +### Следующие шаги + +* Исследуйте другие форматы вывода, такие как **render html as image** JPEG или BMP, изменив расширение файла. +* Скомбинируйте этот подход с **Aspose.PDF**, чтобы встроить PNG в PDF‑отчёт. +* Поэкспериментируйте с `ImageRenderingOptions.DpiX` и `DpiY` для высоко‑разрешённых миниатюр. + +Не стесняйтесь адаптировать код для пакетной обработки, динамической генерации HTML или интеграции в веб‑сервис, который по запросу возвращает PNG‑превью. Приятного рендеринга! + +## Что стоит изучить дальше? + +Следующие учебники охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 c48f8adba0..d89bdb5bab 100644 --- a/html/spanish/net/html-extensions-and-conversions/_index.md +++ b/html/spanish/net/html-extensions-and-conversions/_index.md @@ -60,7 +60,7 @@ Aprenda a guardar HTML como PDF en C# con fuentes integradas, siguiendo una guí Aprenda a generar un PDF desde HTML usando C# y Aspose.HTML con esta guía paso a paso para desarrolladores. ### [Crear PDF a partir de HTML con Aspose – Guía paso a paso](./create-pdf-from-html-with-aspose-step-by-step-guide/) -Aprenda a generar un PDF desde HTML usando Aspose con esta guía paso a paso en C#. +Aprenda a generar un PDF desde HTML usando Aspose con una guía paso a paso en C#. ### [Crear PDF a partir de HTML – Guía completa con Aspose.Html](./create-pdf-from-html-complete-guide-with-aspose-html/) Aprenda a generar un PDF desde HTML usando Aspose.HTML con una guía completa paso a paso. ### [Crear documento HTML con texto con estilo y exportarlo a PDF – Guía completa](./create-html-document-with-styled-text-and-export-to-pdf-full/) @@ -96,7 +96,7 @@ Aprenda a guardar documentos HTML como archivos ZIP usando Aspose.HTML para .NET Aprenda a guardar documentos HTML directamente en un flujo de datos usando Aspose.HTML para .NET en C#. ### [Guardar HTML como ZIP en C# – Guía completa](./save-html-as-zip-in-c-complete-guide/) Aprenda a guardar HTML como archivo ZIP en C# con Aspose.HTML paso a paso. -### [Convierte HTML a TIFF en .NET con Aspose.HTML](./convert-html-to-tiff/) +### [Convertir HTML a TIFF en .NET con Aspose.HTML](./convert-html-to-tiff/) Aprenda a convertir HTML a TIFF con Aspose.HTML para .NET. Siga nuestra guía paso a paso para optimizar eficazmente el contenido web. ### [Convierta HTML a XPS en .NET con Aspose.HTML](./convert-html-to-xps/) 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. @@ -132,6 +132,22 @@ Aprenda a guardar una página web completa en un solo archivo HTML usando Aspose Aprenda a cargar HTML y guardarlo como archivo ZIP usando un handler en Aspose.HTML para .NET. ### [Crear documento HTML y guardarlo como ZIP – Guía completa en C#](./create-html-document-and-save-as-zip-complete-c-guide/) Aprenda a crear un documento HTML y guardarlo como archivo ZIP usando C# y Aspose.HTML paso a paso. +### [Guardar HTML como ZIP – Tutorial completo en C#](./save-html-as-zip-complete-c-tutorial/) +Aprenda a guardar documentos HTML como archivos ZIP usando Aspose.HTML para .NET con este tutorial paso a paso en C#. +### [Opciones de guardado de Aspose HTML: Guardar HTML en Stream en C#](./aspose-html-save-options-save-html-to-stream-in-c/) +Aprenda a guardar documentos HTML directamente en un flujo de datos usando Aspose.HTML para .NET en C#. +### [Guardar HTML como ZIP en C# – Guía completa](./save-html-as-zip-in-c-complete-guide/) +Aprenda a guardar HTML como archivo ZIP en C# con Aspose.HTML paso a paso. +### [Guardar HTML como ZIP en C# – Guía completa paso a paso](./save-html-as-zip-in-c-complete-step-by-step-guide/) +Aprenda a guardar documentos HTML en un archivo ZIP usando C# con Aspose.HTML, siguiendo una guía paso a paso. +### [Guardar HTML en ZIP en C# – Guía completa](./save-html-to-zip-in-c-complete-guide/) +Aprenda a guardar archivos HTML en un archivo ZIP usando C# y Aspose.HTML con una guía paso a paso completa. + +### [Cómo guardar HTML como zip con Aspose.HTML e incluir imágenes](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Aprenda a guardar documentos HTML como un archivo ZIP que incluya imágenes usando Aspose.HTML en C#. + +### [Archivo HTML único – Guardar una página web como un solo archivo HTML en C#](./single-file-html-save-a-web-page-as-one-html-file-in-c/) +Aprenda a guardar una página web completa en un solo archivo HTML usando Aspose.HTML y C# paso a paso. ## Conclusión diff --git a/html/spanish/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/spanish/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..be59621b25 --- /dev/null +++ b/html/spanish/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,341 @@ +--- +category: general +date: 2026-10-02 +description: Aprende cómo guardar HTML como zip usando Aspose.HTML en C#. Esta guía + también muestra cómo guardar HTML con imágenes en un solo archivo. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: es +lastmod: 2026-10-02 +og_description: Guarda HTML como zip usando Aspose.HTML en C#. Sigue este tutorial + completo para aprender cómo guardar HTML con imágenes en un solo archivo. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Guardar HTML como zip con Aspose.HTML – guía paso a paso en C# +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Cómo guardar HTML como zip con Aspose.HTML e incluir imágenes +url: /es/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo guardar HTML como zip con Aspose.HTML e incluir imágenes + +Si necesitas **guardar HTML como zip** para una distribución fácil, este tutorial te muestra los pasos exactos usando Aspose.HTML para .NET. Ya sea que estés exportando una página estática, una plantilla de correo electrónico o un informe que contiene imágenes, verás cómo empaquetar los archivos HTML, CSS e imágenes en un solo archivo ZIP sin escribir archivos temporales en disco. + +Además del objetivo principal, también responderemos la pregunta frecuente de seguimiento **cómo guardar HTML con imágenes** para que el archivo resultante pueda abrirse en cualquier navegador sin recursos faltantes. + +Al final de esta guía tendrás una implementación reutilizable de `ResourceHandler`, un programa completo en C# que produce `output.zip`, y consejos prácticos para manejar imágenes grandes o estructuras de carpetas personalizadas. + +## Requisitos previos + +- .NET 6.0 o posterior (la API también funciona con .NET Framework 4.6+) +- Paquete NuGet Aspose.HTML para .NET (`Aspose.Html`) +- Conocimientos básicos de C# y streams +- Visual Studio 2022 o cualquier IDE que soporte desarrollo .NET + +> **Pro tip:** Instala el paquete vía CLI para mantener limpio tu archivo de proyecto: +> `dotnet add package Aspose.Html` + +## Paso 1: Entender el modelo de salida de Aspose.HTML + +Cuando Aspose.HTML guarda un documento, trata cada recurso externo (archivos CSS, imágenes, fuentes, etc.) como un **recurso** separado. Por defecto, la biblioteca escribe esos recursos en el sistema de archivos. Para controlar el destino, proporcionas un `ResourceHandler` personalizado. El controlador recibe un objeto `Resource` y debe devolver un `Stream` escribible. Aspose.HTML entonces escribe los datos del recurso en ese stream. + +Usar un controlador personalizado le permite: + +- Escribir recursos directamente en un `MemoryStream` que luego se convierte en una entrada ZIP +- Almacenar recursos en una base de datos, almacenamiento en la nube o cualquier otro medio +- Ajustar nombres de archivo, niveles de compresión o jerarquías de carpetas + +## Paso 2: Crear un `ResourceHandler` que escribe en un archivo ZIP + +A continuación se muestra un controlador totalmente funcional que construye un `System.IO.Compression.ZipArchive` en memoria. Cada recurso se agrega como una nueva entrada cuyo nombre refleja la ruta URL original, asegurando que el navegador pueda resolver los enlaces relativos cuando se extraiga el ZIP. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Por qué funciona este enfoque + +- **Operación en memoria**: No se crean archivos temporales en disco, lo que es ideal para servicios web o entornos aislados. +- **Preserva la jerarquía de carpetas**: Al usar la URI del recurso original, las referencias relativas siguen siendo válidas después de la extracción. +- **Extensible**: Puedes reemplazar `MemoryStream` por un `FileStream` para escribir directamente a un archivo, o por un stream de red para almacenamiento en la nube. + +## Paso 3: Cargar o crear el documento HTML + +Para la demostración crearemos una cadena HTML simple que referencia una imagen externa. En un proyecto real cargarías HTML desde un archivo, una base de datos o una respuesta HTTP. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Nota:** Si tienes un archivo HTML físico, usa `new HTMLDocument("path/to/file.html")` en su lugar. + +## Paso 4: Conectar el controlador a `SaveOptions` y guardar el ZIP + +Ahora conectamos el `ZipResourceHandler` a `SaveOptions.OutputStorage`. Cuando se ejecuta `document.Save`, Aspose.HTML invocará `HandleResource` para cada recurso, y el controlador rellenará el archivo ZIP. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Resultado esperado + +- `output.zip` contiene: + - `index.html` (el archivo HTML principal) + - `images/logo.png` (la imagen referenciada en el marcado) + - Cualquier archivo CSS o de fuentes adicional detectado automáticamente por Aspose.HTML + +Al extraer el archivo y abrir `index.html` en un navegador, la imagen se muestra correctamente—demostrando **cómo guardar HTML con imágenes** dentro de un ZIP. + +## Paso 5: Verificar el archivo y solucionar problemas comunes + +### Script de verificación rápida + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Ejecutar el script debería listar `index.html` y `images/logo.png`. Si falta un recurso esperado: + +- **Verifica la URL de la imagen**: Debe ser accesible desde el documento HTML. Las rutas relativas funcionan mejor. +- **Asegúrate de que el tipo de recurso sea compatible**: Aspose.HTML maneja formatos web comunes (PNG, JPEG, GIF, CSS, JS). Los formatos inusuales pueden requerir una adición manual. +- **Confirma que `HandleResource` se llame**: Añade un `Console.WriteLine(resource.Uri)` dentro de `HandleResource` para depurar. + +## Paso 6: Variaciones avanzadas + +### 6.1 Guardar directamente a un archivo sin un arreglo de bytes intermedio + +Si el uso de memoria es una preocupación para documentos muy grandes, reemplaza `MemoryStream` por un `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Luego úselo así: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Personalizar nombres de entradas + +Si prefieres una estructura plana (todos los archivos en la raíz), ajusta `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Añadir un archivo de manifiesto + +A veces las herramientas posteriores esperan un `manifest.json`. Puedes añadirlo después de la guardada principal: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Problemas comunes y cómo evitarlos + +| Problema | Por qué ocurre | Solución | +|----------|----------------|----------| +| Las imágenes aparecen rotas después de la extracción | La ruta de la imagen dentro del HTML no coincide con el nombre de la entrada ZIP. | Conserve la ruta relativa original al crear `ZipArchiveEntry`. | +| Imágenes grandes provocan excepciones de falta de memoria | Usar `MemoryStream` para archivos muy grandes puede superar el límite de memoria del proceso. | Cambie a un controlador basado en `FileStream` (ver 6.1). | +| Faltan URLs de CSS | Los archivos CSS externos referenciados mediante `@import` no se detectan automáticamente. | Agregue manualmente esos archivos CSS al ZIP o incrústelos en línea antes de guardar. | +| Los caracteres Unicode se corrompen | La codificación predeterminada puede diferir entre la fuente HTML y el flujo. | Asegúrese de que la cadena HTML sea UTF‑8; Aspose.HTML respeta el conjunto de caracteres del documento. | + +## Ejemplo completo (listo para copiar y pegar) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [cómo usar el controlador en Aspose.HTML – Cargar HTML, Guardar como ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Cómo guardar HTML en C# – Controladores de recursos personalizados y ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Renderizar HTML a PNG y guardar en ZIP con C# – Guía completa](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 feade5235b..0f9bd67dd1 100644 --- a/html/spanish/net/rendering-html-documents/_index.md +++ b/html/spanish/net/rendering-html-documents/_index.md @@ -85,6 +85,9 @@ Aprenda paso a paso a convertir HTML a PNG usando C# y Aspose.HTML con ejemplos ### [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. +### [Cómo usar Aspose para renderizar HTML a imagen PNG en C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Aprenda a convertir HTML a PNG usando Aspose.HTML en C# con una guía paso a paso. + ### [Cómo renderizar HTML a una imagen con C# – Guía completa](./how-to-render-html-to-an-image-with-c-complete-guide/) Aprenda a renderizar HTML a imágenes usando C# paso a paso con Aspose.HTML para .NET. ### [Cómo renderizar HTML a PNG en C# – Guía paso a paso](./how-to-render-html-to-png-in-c-step-by-step-guide/) diff --git a/html/spanish/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/spanish/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..55597d1f33 --- /dev/null +++ b/html/spanish/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-10-02 +description: Cómo usar Aspose para renderizar HTML a una imagen PNG rápidamente – + aprende a convertir HTML a PNG con suavizado y ajuste de texto. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: es +lastmod: 2026-10-02 +og_description: Cómo usar Aspose para renderizar HTML a imagen PNG. Sigue este tutorial + completo para convertir HTML a PNG con renderizado de alta calidad en C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Cómo usar Aspose para renderizar HTML a imagen PNG – guía paso a paso +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Cómo usar Aspose para renderizar HTML a imagen PNG en C# +url: /es/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo usar Aspose para renderizar HTML a imagen PNG en C# + +**Cómo usar Aspose para renderizar HTML a imagen PNG** es un requisito frecuente cuando necesitas una vista previa en bitmap de una página web, una miniatura de correo electrónico o una captura apta para PDF. Este tutorial te muestra una solución completa, lista para ejecutar que **renderiza html a imagen** con anti‑aliasing y text hinting, de modo que el resultado se vea nítido en cualquier plataforma. + +Aprenderás a **convertir HTML a PNG**, a configurar las opciones de renderizado y a manejar problemas típicos como el renderizado de fuentes en Linux y los permisos del sistema de archivos. No se requieren herramientas externas, solo la biblioteca Aspose.HTML para .NET y unas pocas líneas de C#. + +## Prerrequisitos + +Antes de comenzar, asegúrate de tener: + +* .NET 6.0 SDK o posterior instalado +* Visual Studio 2022 (o cualquier IDE de C#) +* Una referencia NuGet a **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Familiaridad básica con la sintaxis de C# + +Estos prerrequisitos son ligeros; el tutorial funciona en Windows, Linux y macOS porque Aspose.HTML es multiplataforma. + +## Paso 1: Instalar Aspose.HTML y crear un nuevo proyecto de consola + +Abre una terminal o la Consola del Administrador de paquetes y ejecuta: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Crear un proyecto dedicado aísla las dependencias y facilita la ejecución del ejemplo con `dotnet run`. + +## Paso 2: Configurar las opciones de renderizado de imagen (anti‑aliasing y text hinting) + +El antialiasing suaviza los bordes, mientras que el text hinting mejora la claridad de los glifos, especialmente en Linux donde la rasterización de fuentes difiere de Windows. La clase `ImageRenderingOptions` te permite habilitar ambas características: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Por qué es importante:** Sin antialiasing, las líneas diagonales y curvas se ven dentadas. Sin text hinting, los tamaños de fuente pequeños pueden quedar borrosos, lo que se nota al **guardar html como png** para miniaturas. + +## Paso 3: Definir CSS para fuentes consistentes y estilos de encabezados + +Incorporar CSS directamente en el HTML garantiza que la imagen renderizada coincida con tus expectativas de diseño. En este ejemplo establecemos una fuente base y hacemos que `

` sea itálica: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Puedes ampliar la hoja de estilos con colores, márgenes o consultas de medios. El CSS se inyecta dentro de la etiqueta ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Consejo:** Si necesitas **renderizar html como imagen** desde una página remota, reemplaza el constructor de cadena con `new HTMLDocument("https://example.com")`. Aspose descargará la página, resolverá los recursos y renderizará el diseño final. + +## Paso 5: Renderizar el documento a un archivo PNG + +Ahora llamamos a `RenderToImage`, pasando la ruta de salida y las opciones que configuramos antes: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +El `output.png` generado contendrá una representación nítida del elemento `

` con estilo itálico, gracias a la configuración de anti‑aliasing y hinting. + +## Listado completo del programa + +Copia el siguiente código en `Program.cs`. Compila y se ejecuta tal cual: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Resultado esperado + +Al ejecutar el programa se crea `output.png` en la carpeta del proyecto. La imagen muestra la palabra **Sample** en Arial itálica, renderizada con bordes suaves y texto claro. Abre el archivo con cualquier visor de imágenes para verificar la calidad. + +## Paso 6: Variaciones comunes y manejo de casos límite + +| Situación | Qué ajustar | Razón | +|-----------|-------------|-------| +| **Páginas HTML grandes** | Establecer `ImageRenderingOptions.Width` / `Height` o usar `PageSize` para controlar las dimensiones de salida | Evita un consumo excesivo de memoria y asegura que el PNG se ajuste a tu UI | +| **Falta de fuente en Linux** | Instalar las fuentes requeridas en el host (`apt-get install fonts‑arial` o usar un archivo de fuente personalizado) y apuntar a ella mediante `FontSettings` | Sin la fuente, Aspose recurre a una genérica, alterando la apariencia | +| **Se necesita fondo transparente** | Configurar `imgOptions.BackgroundColor = Color.Transparent` | Útil al incrustar el PNG en otros gráficos | +| **Conversión por lotes** | Recorrer una lista de cadenas HTML o rutas de archivo, reutilizando el mismo objeto `ImageRenderingOptions` | Mejora el rendimiento y mantiene consistentes los ajustes de renderizado | + +## Consejo profesional: almacenar en caché las opciones de renderizado + +Crear un nuevo objeto `ImageRenderingOptions` para cada conversión genera sobrecarga. Declara una instancia estática si procesas muchos fragmentos HTML en un servicio: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Reutiliza `SharedOptions` entre llamadas para mantener bajo el uso de CPU. + +## Preguntas frecuentes + +**P: ¿Esto funciona con .NET Core en macOS?** +R: Sí. Aspose.HTML es totalmente multiplataforma. Asegúrate de que las fuentes requeridas estén instaladas y de que el directorio de salida sea escribible. + +**P: ¿Puedo renderizar a JPEG en lugar de PNG?** +R: Reemplaza `RenderToImage("output.png", imgOptions)` por `RenderToImage("output.jpg", imgOptions)`. También puedes establecer `imgOptions.ImageFormat = ImageFormat.Jpeg` para un control más fino de la calidad. + +**P: ¿Cómo incrusto archivos CSS externos?** +R: Carga el contenido CSS en una cadena y concaténalo, o referencia una hoja de estilo remota en la etiqueta ``. Aspose resuelve automáticamente las etiquetas `` cuando el documento se carga desde una URL. + +## Conclusión + +Ahora sabes **cómo usar Aspose** para **renderizar HTML a PNG** (o cualquier otro formato raster) con configuraciones de alta calidad. El tutorial cubrió la instalación de Aspose.HTML, la configuración de anti‑aliasing y text hinting, la inyección de CSS, la carga de HTML y, finalmente, **guardar HTML como PNG**. Siguiendo los pasos podrás **convertir HTML a PNG** de forma fiable en cualquier aplicación .NET, ya sea en Windows, Linux o macOS. + +### Próximos pasos + +* Explora otros formatos de salida como **render html as image** JPEG o BMP cambiando la extensión del archivo. +* Combina este enfoque con **Aspose.PDF** para incrustar el PNG en un informe PDF. +* Experimenta con `ImageRenderingOptions.DpiX` y `DpiY` para miniaturas de alta resolución. + +Siéntete libre de adaptar el código para procesamiento por lotes, generación dinámica de HTML o integración en un servicio web que devuelva vistas previas PNG bajo demanda. ¡Feliz renderizado! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 b9e6a93aa2..b26018cc9c 100644 --- a/html/swedish/net/html-extensions-and-conversions/_index.md +++ b/html/swedish/net/html-extensions-and-conversions/_index.md @@ -76,6 +76,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. +### [Spara HTML som zip med Aspose.HTML och inkludera bilder](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Lär dig hur du sparar HTML-filer som ett zip‑arkiv och inkluderar bilder med Aspose.HTML i C#. ### [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/) diff --git a/html/swedish/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/swedish/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..88cea90fac --- /dev/null +++ b/html/swedish/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,342 @@ +--- +category: general +date: 2026-10-02 +description: Lär dig hur du sparar HTML som zip med Aspose.HTML i C#. Denna guide + visar också hur du sparar HTML med bilder i ett enda arkiv. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: sv +lastmod: 2026-10-02 +og_description: Spara HTML som zip med Aspose.HTML i C#. Följ den här kompletta handledningen + för att lära dig hur du sparar HTML med bilder i ett enda arkiv. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Spara HTML som zip med Aspose.HTML – steg‑för‑steg C#‑guide +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Hur man sparar HTML som zip med Aspose.HTML och inkluderar bilder +url: /sv/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Så sparar du HTML som zip med Aspose.HTML och inkluderar bilder + +Om du behöver **spara HTML som zip** för enkel distribution visar den här handledningen de exakta stegen med Aspose.HTML för .NET. Oavsett om du exporterar en statisk sida, en e‑postmall eller en rapport som innehåller bilder, kommer du att se hur du paketerar HTML‑, CSS‑ och bildfilerna i ett enda ZIP‑arkiv utan att skriva temporära filer till disk. + +Utöver huvudmålet kommer vi också att besvara den vanliga uppföljningsfrågan **hur man sparar HTML med bilder** så att det resulterande arkivet kan öppnas i vilken webbläsare som helst utan saknade resurser. + +I slutet av den här guiden har du en återanvändbar `ResourceHandler`‑implementation, ett komplett C#‑program som producerar `output.zip`, samt praktiska tips för att hantera stora bilder eller anpassade mappstrukturer. + +## Förutsättningar + +- .NET 6.0 eller senare (API:et fungerar även med .NET Framework 4.6+) +- Aspose.HTML för .NET NuGet‑paket (`Aspose.Html`) +- Grundläggande kunskap om C# och strömmar +- Visual Studio 2022 eller någon IDE som stödjer .NET‑utveckling + +> **Pro tip:** Installera paketet via CLI för att hålla din projektfil ren: +> `dotnet add package Aspose.Html` + +## Steg 1: Förstå Aspose.HTML:s output‑modell + +När Aspose.HTML sparar ett dokument behandlar det varje extern resurs (CSS‑filer, bilder, teckensnitt osv.) som en separat **resource**. Som standard skriver biblioteket dessa resurser till filsystemet. För att styra destinationen tillhandahåller du en anpassad `ResourceHandler`. Handlaren tar emot ett `Resource`‑objekt och måste returnera en skrivbar `Stream`. Aspose.HTML skriver sedan resursdata till den strömmen. + +Att använda en anpassad handler låter dig: + +- Skriva resurser direkt till en `MemoryStream` som senare blir ett ZIP‑inlägg +- Lagra resurser i en databas, molnlagring eller något annat medium +- Justera filnamn, komprimeringsnivåer eller mapphierarkier + +## Steg 2: Skapa en `ResourceHandler` som skriver till ett ZIP‑arkiv + +Nedan är en fullt funktionell handler som bygger ett `System.IO.Compression.ZipArchive` i minnet. Varje resurs läggs till som ett nytt inlägg vars namn speglar den ursprungliga URL‑sökvägen, vilket säkerställer att webbläsaren kan lösa relativa länkar när ZIP‑filen extraheras. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Varför detta tillvägagångssätt fungerar + +- **In‑memory‑operation**: Inga temporära filer skapas på disk, vilket är idealiskt för webbtjänster eller sandlådemiljöer. +- **Bevarar mapphierarki**: Genom att använda den ursprungliga resurs‑URI:n förblir relativa referenser giltiga efter extraktion. +- **Utbyggbart**: Du kan ersätta `MemoryStream` med en `FileStream` för att skriva direkt till en fil, eller med en nätverksström för molnlagring. + +## Steg 3: Ladda eller skapa HTML‑dokumentet + +För demonstration skapar vi en enkel HTML‑sträng som refererar till en extern bild. I ett riktigt projekt skulle du ladda HTML från en fil, en databas eller ett HTTP‑svar. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Obs:** Om du har en fysisk HTML‑fil, använd `new HTMLDocument("path/to/file.html")` istället. + +## Steg 4: Koppla handlern till `SaveOptions` och spara ZIP‑filen + +Nu ansluter vi `ZipResourceHandler` till `SaveOptions.OutputStorage`. När `document.Save` körs kommer Aspose.HTML att anropa `HandleResource` för varje resurs, och handlern kommer att fylla ZIP‑arkivet. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Förväntat resultat + +- `output.zip` innehåller: + - `index.html` (huvud‑HTML‑filen) + - `images/logo.png` (bilden som refereras i markupen) + - Eventuella ytterligare CSS‑ eller teckensnittsfiler som automatiskt upptäcks av Aspose.HTML + +När du extraherar arkivet och öppnar `index.html` i en webbläsare visas bilden korrekt—vilket demonstrerar **hur man sparar HTML med bilder** i ett ZIP‑arkiv. + +## Steg 5: Verifiera arkivet och felsök vanliga problem + +### Snabb verifierings‑script + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Att köra skriptet bör lista `index.html` och `images/logo.png`. Om en förväntad resurs saknas: + +- **Kontrollera bild‑URL:en**: Den måste vara åtkomlig från HTML‑dokumentet. Relativa sökvägar fungerar bäst. +- **Säkerställ att resurstypen stöds**: Aspose.HTML hanterar vanliga webbformat (PNG, JPEG, GIF, CSS, JS). Ovanliga format kan kräva manuell tilläggning. +- **Bekräfta att `HandleResource` anropas**: Lägg till en `Console.WriteLine(resource.Uri)` inuti `HandleResource` för felsökning. + +## Steg 6: Avancerade varianter + +### 6.1 Spara direkt till en fil utan en mellanliggande byte‑array + +Om minnesanvändning är ett problem för mycket stora dokument, ersätt `MemoryStream` med en `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Använd den sedan så här: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Anpassa inläggsnamn + +Om du föredrar en platt struktur (alla filer i rotkatalogen), justera `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Lägga till en manifestfil + +Ibland förväntar sig nedströmsverktyg en `manifest.json`. Du kan lägga till den efter huvud‑sparandet: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Vanliga fallgropar och hur man undviker dem + +| Fallgrop | Varför det händer | Lösning | +|----------|-------------------|---------| +| Bilder visas trasiga efter extraktion | Bildens sökväg i HTML matchar inte ZIP‑inläggets namn. | Bevara den ursprungliga relativa sökvägen när du skapar `ZipArchiveEntry`. | +| Stora bilder orsakar out‑of‑memory‑undantag | Att använda `MemoryStream` för mycket stora filer kan överskrida processens minnesgräns. | Byt till en handler baserad på `FileStream` (se 6.1). | +| CSS‑URL:er saknas | Externa CSS‑filer som refereras via `@import` upptäcks inte automatiskt. | Lägg manuellt till dessa CSS‑filer i ZIP‑filen eller bädda in dem inline innan sparandet. | +| Unicode‑tecken blir förvrängda | Standardkodningen kan skilja sig mellan HTML‑källan och strömmen. | Säkerställ att HTML‑strängen är UTF‑8; Aspose.HTML respekterar dokumentets teckenuppsättning. | + +## Fullt fungerande exempel (klistra‑in redo) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstreras i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [hur man använder handler i Aspose.HTML – Ladda HTML, spara som ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Hur man sparar HTML i C# – Anpassade Resource Handlers & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Rendera HTML till PNG och spara till ZIP med C# – Komplett guide](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 2508bfe38b..b48acf222d 100644 --- a/html/swedish/net/rendering-html-documents/_index.md +++ b/html/swedish/net/rendering-html-documents/_index.md @@ -93,6 +93,7 @@ Lär dig steg för steg hur du renderar HTML till PNG i C# med Aspose.HTML för Lär dig hur du med Aspose.HTML för .NET konverterar HTML till PNG och packar dem i en ZIP‑fil i en komplett C#‑guide. ### [Rendera HTML till PDF med Aspose.HTML – Steg‑för‑steg‑guide](./render-html-to-pdf-with-aspose-html-step-by-step-guide/) Lär dig hur du med Aspose.HTML för .NET konverterar HTML till PDF i en detaljerad steg‑för‑steg‑handledning. +### [Hur man använder Aspose för att rendera HTML till PNG-bild i C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/swedish/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/swedish/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..d559777f3a --- /dev/null +++ b/html/swedish/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-10-02 +description: Hur man använder Aspose för att rendera HTML till PNG‑bild snabbt – lär + dig konvertera HTML till PNG med kantutjämning och texthintning. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: sv +lastmod: 2026-10-02 +og_description: Hur man använder Aspose för att rendera HTML till PNG‑bild. Följ den + här kompletta handledningen för att konvertera HTML till PNG med högkvalitativ rendering + i C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Hur man använder Aspose för att rendera HTML till PNG‑bild – steg‑för‑steg‑guide +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Hur man använder Aspose för att rendera HTML till PNG-bild i C# +url: /sv/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Så använder du Aspose för att rendera HTML till PNG‑bild i C# + +**How to use Aspose to render HTML to PNG image** är ett vanligt krav när du behöver en bitmap‑förhandsgranskning av en webbsida, en e‑post‑miniatyr eller ett PDF‑vänligt ögonblicksbild. Denna handledning visar en komplett, färdig‑att‑köra lösning som **render html to image** med antialiasing och text‑hinting, så resultatet blir skarpt på alla plattformar. + +Du kommer att lära dig hur du **konverterar HTML till PNG**, konfigurerar renderingsalternativ och hanterar vanliga fallgropar som Linux‑teckensnittsrendering och filsystembehörigheter. Inga externa verktyg krävs—bara Aspose.HTML för .NET‑biblioteket och några rader C#. + +## Förutsättningar + +* .NET 6.0 SDK eller senare installerat +* Visual Studio 2022 (eller någon C#‑IDE) +* En NuGet‑referens till **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Grundläggande kunskap om C#‑syntax + +Dessa förutsättningar är lätta; handledningen fungerar på Windows, Linux och macOS eftersom Aspose.HTML är plattformsoberoende. + +## Steg 1: Installera Aspose.HTML och skapa ett nytt konsolprojekt + +Öppna en terminal eller Package Manager Console och kör: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Att skapa ett dedikerat projekt isolerar beroenden och gör det enkelt att köra exemplet med `dotnet run`. + +## Steg 2: Ställ in bildrenderingsalternativ (antialiasing och text‑hinting) + +Antialiasing jämnar ut kanter, medan text‑hinting förbättrar glyf‑klarhet, särskilt på Linux där teckensnittsrasterisering skiljer sig från Windows. Klassen `ImageRenderingOptions` låter dig aktivera båda funktionerna: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Varför detta är viktigt:** Utan antialiasing ser diagonala linjer och kurvor hackiga ut. Utan text‑hinting kan små teckensnitt bli suddiga, vilket märks när du **save html as png** för miniatyrer. + +## Steg 3: Definiera CSS för konsekventa teckensnitt och rubrikstilar + +Att bädda in CSS direkt i HTML säkerställer att den renderade bilden matchar dina designförväntningar. I detta exempel sätter vi ett bas‑teckensnitt och gör `

` kursivt: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Du kan utöka stilmallen med färger, marginaler eller media‑queries. CSS‑koden injiceras i ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Tips:** Om du behöver **render html as image** från en fjärrsida, ersätt strängkonstruktorn med `new HTMLDocument("https://example.com")`. Aspose laddar ner sidan, löser resurser och renderar den slutgiltiga layouten. + +## Steg 5: Rendera dokumentet till en PNG‑fil + +Nu anropar vi `RenderToImage`, med utdata‑sökvägen och de alternativ vi konfigurerade tidigare: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +Den genererade `output.png` kommer att innehålla en skarp rendering av `

`‑elementet med kursiv stil, tack vare antialiasing‑ och hinting‑inställningarna. + +## Fullständig programlista + +Kopiera följande kod till `Program.cs`. Den kompileras och körs som den är: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Förväntad output + +När programmet körs skapas `output.png` i projektmappen. Bilden visar ordet **Sample** i kursiv Arial, renderat med mjuka kanter och tydlig text. Öppna filen med någon bildvisare för att verifiera kvaliteten. + +## Steg 6: Vanliga variationer och hantering av kantfall + +| Situation | Vad som ska justeras | Orsak | +|-----------|----------------------|-------| +| **Stora HTML‑sidor** | Sätt `ImageRenderingOptions.Width` / `Height` eller använd `PageSize` för att kontrollera utdata‑dimensioner | Förhindrar minnesökning och säkerställer att PNG‑filen passar ditt UI | +| **Linux‑teckensnitt saknas** | Installera de nödvändiga teckensnitten på värden (`apt-get install fonts‑arial` eller använd en anpassad teckensnittsfil) och peka Aspose på den via `FontSettings` | Utan teckensnittet faller Aspose tillbaka på ett generiskt, vilket förändrar utseendet | +| **Transparent bakgrund behövs** | Sätt `imgOptions.BackgroundColor = Color.Transparent` | Användbart när PNG‑filen ska bäddas in i annan grafik | +| **Batch‑konvertering** | Loopa över en lista med HTML‑strängar eller filsökvägar, återanvänd samma `ImageRenderingOptions`‑objekt | Förbättrar prestanda och håller renderingsinställningarna konsekventa | + +## Pro‑tips: cachea renderingsalternativ + +Att skapa ett nytt `ImageRenderingOptions`‑objekt för varje konvertering ger extra overhead. Deklarera en statisk instans om du bearbetar många HTML‑snuttar i en tjänst: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Återanvänd `SharedOptions` mellan anrop för att hålla CPU‑användningen låg. + +## Vanliga frågor + +**Q: Fungerar detta med .NET Core på macOS?** +A: Ja. Aspose.HTML är helt plattformsoberoende. Se till att de nödvändiga teckensnitten är installerade och att utdata‑katalogen är skrivbar. + +**Q: Kan jag rendera till JPEG istället för PNG?** +A: Ersätt `RenderToImage("output.png", imgOptions)` med `RenderToImage("output.jpg", imgOptions)`. Du kan också sätta `imgOptions.ImageFormat = ImageFormat.Jpeg` för finare kontroll över kvaliteten. + +**Q: Hur bäddar jag in externa CSS‑filer?** +A: Läs in CSS‑innehållet i en sträng och konkatenera det, eller referera till en fjärr‑stylesheet i ``‑taggen. Aspose löser ``‑taggar automatiskt när dokumentet laddas från en URL. + +## Slutsats + +Du vet nu **hur du använder Aspose** för att **rendera HTML till PNG** (eller något annat rasterformat) med högkvalitativa inställningar. Handledningen täckte installation av Aspose.HTML, konfiguration av antialiasing och text‑hinting, injicering av CSS, laddning av HTML och slutligen **spara HTML som PNG**. Genom att följa stegen kan du på ett pålitligt sätt **konvertera HTML till PNG** i vilken .NET‑applikation som helst, oavsett om den körs på Windows, Linux eller macOS. + +### Nästa steg + +* Utforska andra utdataformat som **render html as image** JPEG eller BMP genom att ändra filändelsen. +* Kombinera detta tillvägagångssätt med **Aspose.PDF** för att bädda in PNG‑filen i en PDF‑rapport. +* Experimentera med `ImageRenderingOptions.DpiX` och `DpiY` för högupplösta miniatyrer. + +Känn dig fri att anpassa koden för batch‑behandling, dynamisk HTML‑generering eller integration i en webbtjänst som returnerar PNG‑förhandsvisningar på begäran. Lycka till med renderingen! + +## Vad du bör lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger vidare på teknikerna som demonstrerats i denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Hur du använder Aspose för att rendera HTML till PNG – Steg‑för‑steg‑guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [Hur du renderar HTML till PNG med Aspose – Komplett guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html till bild‑handledning – Rendera HTML till PNG med Aspose.HTML i C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 7056fd94cd..3ccb945266 100644 --- a/html/thai/net/html-extensions-and-conversions/_index.md +++ b/html/thai/net/html-extensions-and-conversions/_index.md @@ -133,6 +133,12 @@ Aspose.HTML สำหรับ .NET ไม่ใช่แค่ไลบรา ### [สร้าง PDF จาก HTML – คู่มือเต็มด้วย Aspose.HTML](./create-pdf-from-html-complete-guide-with-aspose-html/) เรียนรู้วิธีสร้าง PDF จากไฟล์ HTML อย่างละเอียดด้วย Aspose.HTML สำหรับ .NET ตามขั้นตอนครบถ้วน +### [บันทึก HTML เป็น ZIP ใน C# – คู่มือเต็ม](./save-html-as-zip-in-c-complete-guide/) +บันทึกไฟล์ HTML เป็น ZIP อย่างครบถ้วนด้วย C# ตามขั้นตอนของเรา + +### [วิธีบันทึก HTML เป็น zip ด้วย Aspose.HTML และรวมรูปภาพ](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +เรียนรู้วิธีบันทึกไฟล์ HTML เป็น ZIP พร้อมรูปภาพโดยใช้ Aspose.HTML สำหรับ .NET + ## บทสรุป โดยสรุป การขยายและการแปลง HTML เป็นองค์ประกอบสำคัญของการพัฒนาเว็บสมัยใหม่ Aspose.HTML สำหรับ .NET ทำให้กระบวนการนี้ง่ายขึ้นและทำให้ผู้พัฒนาทุกระดับสามารถเข้าถึงได้ หากทำตามบทช่วยสอนของเรา คุณจะก้าวไปสู่การเป็นนักพัฒนาเว็บที่เชี่ยวชาญและมีทักษะที่หลากหลาย diff --git a/html/thai/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/thai/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..918ae69eb6 --- /dev/null +++ b/html/thai/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,332 @@ +--- +category: general +date: 2026-10-02 +description: เรียนรู้วิธีบันทึก HTML เป็นไฟล์ zip โดยใช้ Aspose.HTML ใน C#. คู่มือนี้ยังแสดงวิธีบันทึก + HTML พร้อมรูปภาพในไฟล์เดียวกัน. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: th +lastmod: 2026-10-02 +og_description: บันทึก HTML เป็นไฟล์ zip ด้วย Aspose.HTML ใน C# ทำตามบทเรียนฉบับเต็มนี้เพื่อเรียนรู้วิธีบันทึก + HTML พร้อมรูปภาพเป็นไฟล์เก็บข้อมูลเดียว. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: บันทึก HTML เป็นไฟล์ zip ด้วย Aspose.HTML – คู่มือ C# ทีละขั้นตอน +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: วิธีบันทึก HTML เป็นไฟล์ zip ด้วย Aspose.HTML และรวมรูปภาพ +url: /th/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีบันทึก HTML เป็น zip ด้วย Aspose.HTML และรวมรูปภาพ + +หากคุณต้องการ **บันทึก HTML เป็น zip** เพื่อการแจกจ่ายที่ง่าย ด้านล่างนี้เป็นขั้นตอนที่ใช้ Aspose.HTML สำหรับ .NET อย่างละเอียด ไม่ว่าคุณจะส่งออกหน้าเว็บแบบคงที่, แม่แบบอีเมล, หรือรายงานที่มีรูปภาพ คุณจะได้เห็นวิธีการบรรจุไฟล์ HTML, CSS, และรูปภาพเข้าเป็นไฟล์ ZIP เดียวโดยไม่ต้องเขียนไฟล์ชั่วคราวลงดิสก์ + +นอกจากเป้าหมายหลักแล้ว เราจะตอบคำถามที่พบบ่อยต่อเนื่อง **วิธีบันทึก HTML พร้อมรูปภาพ** เพื่อให้ไฟล์ที่ได้สามารถเปิดได้ในทุกเบราว์เซอร์โดยไม่มีทรัพยากรหาย + +เมื่อจบคู่มือนี้ คุณจะมีการนำ `ResourceHandler` ไปใช้ซ้ำได้, โปรแกรม C# ที่สมบูรณ์ซึ่งสร้าง `output.zip`, และเคล็ดลับการจัดการรูปภาพขนาดใหญ่หรือโครงสร้างโฟลเดอร์แบบกำหนดเอง + +## ข้อกำหนดเบื้องต้น + +- .NET 6.0 หรือใหม่กว่า (API ทำงานกับ .NET Framework 4.6+ ด้วย) +- แพคเกจ NuGet ของ Aspose.HTML สำหรับ .NET (`Aspose.Html`) +- ความรู้พื้นฐานของ C# และสตรีม +- Visual Studio 2022 หรือ IDE ใด ๆ ที่รองรับการพัฒนา .NET + +> **เคล็ดลับมืออาชีพ:** ติดตั้งแพคเกจผ่าน CLI เพื่อให้ไฟล์โครงการของคุณสะอาด: +> `dotnet add package Aspose.Html` + +## ขั้นตอนที่ 1: ทำความเข้าใจโมเดลการส่งออกของ Aspose.HTML + +เมื่อ Aspose.HTML บันทึกเอกสาร มันจะถือทุกทรัพยากรภายนอก (ไฟล์ CSS, รูปภาพ, ฟอนต์ ฯลฯ) เป็น **resource** แยกกัน โดยค่าเริ่มต้นไลบรารีจะเขียนทรัพยากรเหล่านั้นลงในระบบไฟล์ เพื่อควบคุมตำแหน่งปลายทางคุณต้องให้ `ResourceHandler` ที่กำหนดเอง ตัวจัดการจะรับอ็อบเจ็กต์ `Resource` และต้องคืน `Stream` ที่สามารถเขียนได้ Aspose.HTML จะเขียนข้อมูลของทรัพยากรลงในสตรีมนั้น + +Using a custom handler lets you: + +- เขียนทรัพยากรโดยตรงลงใน `MemoryStream` ซึ่งต่อมาจะกลายเป็นรายการใน ZIP +- เก็บทรัพยากรในฐานข้อมูล, ที่เก็บบนคลาวด์, หรือสื่ออื่นใด +- ปรับชื่อไฟล์, ระดับการบีบอัด, หรือโครงสร้างโฟลเดอร์ + +## ขั้นตอนที่ 2: สร้าง `ResourceHandler` ที่เขียนลงในไฟล์ ZIP + +ด้านล่างเป็นตัวจัดการที่ทำงานเต็มรูปแบบซึ่งสร้าง `System.IO.Compression.ZipArchive` ในหน่วยความจำ แต่ละทรัพยากรถูกเพิ่มเป็นรายการใหม่โดยใช้ชื่อที่สะท้อนเส้นทาง URL ดั้งเดิม เพื่อให้เบราว์เซอร์สามารถแก้ไขลิงก์แบบสัมพันธ์เมื่อแตกไฟล์ ZIP + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### ทำไมวิธีนี้ถึงได้ผล + +- **การทำงานในหน่วยความจำ**: ไม่สร้างไฟล์ชั่วคราวบนดิสก์ ซึ่งเหมาะกับบริการเว็บหรือสภาพแวดล้อมแบบ sandbox +- **รักษาโครงสร้างโฟลเดอร์**: การใช้ URI ของทรัพยากรดั้งเดิมทำให้การอ้างอิงแบบสัมพันธ์ยังคงใช้ได้หลังจากการแตกไฟล์ +- **ขยายได้**: คุณสามารถแทนที่ `MemoryStream` ด้วย `FileStream` เพื่อเขียนโดยตรงลงไฟล์ หรือใช้สตรีมเครือข่ายสำหรับการเก็บบนคลาวด์ + +## ขั้นตอนที่ 3: โหลดหรือสร้างเอกสาร HTML + +เพื่อการสาธิต เราจะสร้างสตริง HTML ง่าย ๆ ที่อ้างอิงรูปภาพภายนอก ในโครงการจริงคุณจะโหลด HTML จากไฟล์, ฐานข้อมูล, หรือการตอบสนอง HTTP + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **หมายเหตุ:** หากคุณมีไฟล์ HTML จริง ให้ใช้ `new HTMLDocument("path/to/file.html")` แทน + +## ขั้นตอนที่ 4: เชื่อมตัวจัดการกับ `SaveOptions` และบันทึกเป็น ZIP + +ตอนนี้เราจะเชื่อม `ZipResourceHandler` กับ `SaveOptions.OutputStorage` เมื่อเรียก `document.Save` Aspose.HTML จะเรียก `HandleResource` สำหรับแต่ละทรัพยากร และตัวจัดการจะเติมข้อมูลลงในไฟล์ ZIP + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### ผลลัพธ์ที่คาดหวัง + +- `output.zip` มี: + - `index.html` (ไฟล์ HTML หลัก) + - `images/logo.png` (รูปภาพที่อ้างอิงใน markup) + - ไฟล์ CSS หรือฟอนต์เพิ่มเติมใด ๆ ที่ Aspose.HTML ตรวจจับอัตโนมัติ + +เมื่อคุณแตกไฟล์และเปิด `index.html` ในเบราว์เซอร์ รูปภาพจะแสดงอย่างถูกต้อง—แสดงให้เห็น **วิธีบันทึก HTML พร้อมรูปภาพ** ภายใน ZIP + +## ขั้นตอนที่ 5: ตรวจสอบไฟล์ ZIP และแก้ไขปัญหาที่พบบ่อย + +### สคริปต์ตรวจสอบอย่างรวดเร็ว + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +การรันสคริปต์ควรแสดงรายการ `index.html` และ `images/logo.png` หากทรัพยากรที่คาดหวังหายไป: + +- **ตรวจสอบ URL ของรูปภาพ**: ต้องเข้าถึงได้จากเอกสาร HTML เส้นทางแบบสัมพันธ์ทำงานดีที่สุด +- **ยืนยันว่าประเภททรัพยากรถูกสนับสนุน**: Aspose.HTML รองรับรูปแบบเว็บทั่วไป (PNG, JPEG, GIF, CSS, JS) รูปแบบที่ไม่ปกติอาจต้องเพิ่มด้วยตนเอง +- **ยืนยันว่า `HandleResource` ถูกเรียก**: เพิ่ม `Console.WriteLine(resource.Uri)` ภายใน `HandleResource` เพื่อดีบัก + +## ขั้นตอนที่ 6: วิธีการขั้นสูง + +### 6.1 บันทึกโดยตรงลงไฟล์โดยไม่ใช้ byte array กลาง + +หากการใช้หน่วยความจำเป็นปัญหาสำหรับเอกสารขนาดใหญ่มาก ให้แทนที่ `MemoryStream` ด้วย `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +จากนั้นใช้แบบนี้: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 ปรับแต่งชื่อรายการ + +หากคุณต้องการโครงสร้างแบบแบน (ไฟล์ทั้งหมดอยู่ที่ราก) ให้ปรับ `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 การเพิ่มไฟล์ manifest + +บางครั้งเครื่องมือ downstream คาดหวังไฟล์ `manifest.json` คุณสามารถเพิ่มได้หลังจากการบันทึกหลัก: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## ข้อผิดพลาดทั่วไปและวิธีหลีกเลี่ยง + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| รูปภาพแสดงเสียหลังจากการแตกไฟล์ | เส้นทางรูปภาพใน HTML ไม่ตรงกับชื่อรายการใน ZIP | รักษาเส้นทางสัมพันธ์ดั้งเดิมเมื่อสร้าง `ZipArchiveEntry` | +| รูปภาพขนาดใหญ่ทำให้เกิดข้อยกเว้น out‑of‑memory | การใช้ `MemoryStream` สำหรับไฟล์ขนาดใหญ่มากอาจเกินขีดจำกัดหน่วยความจำของกระบวนการ | เปลี่ยนเป็นตัวจัดการที่ใช้ `FileStream` (ดู 6.1) | +| URL ของ CSS หายไป | ไฟล์ CSS ภายนอกที่อ้างอิงผ่าน `@import` ไม่ถูกตรวจจับโดยอัตโนมัติ | เพิ่มไฟล์ CSS เหล่านั้นลงใน ZIP ด้วยตนเองหรือฝังไว้ในโค้ดก่อนบันทึก | +| อักขระ Unicode กลายเป็นอักขระผิด | การเข้ารหัสเริ่มต้นอาจแตกต่างระหว่างแหล่งที่มาของ HTML และสตรีม | ตรวจสอบให้แน่ใจว่าสตริง HTML เป็น UTF‑8; Aspose.HTML เคารพ charset ของเอกสาร | + +## ตัวอย่างทำงานเต็มรูปแบบ (พร้อมคัดลอกและวาง) + + + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดซึ่งต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการนำไปใช้แบบอื่นในโครงการของคุณ + +- [วิธีใช้ handler ใน Aspose.HTML – โหลด HTML, บันทึกเป็น ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [วิธีบันทึก HTML ใน C# – ตัวจัดการ Resource แบบกำหนดเอง & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [เรนเดอร์ HTML เป็น PNG และบันทึกเป็น ZIP ด้วย C# – คู่มือเต็ม](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 ecc52947ef..8df3023f22 100644 --- a/html/thai/net/rendering-html-documents/_index.md +++ b/html/thai/net/rendering-html-documents/_index.md @@ -53,7 +53,7 @@ Aspose.HTML สำหรับ .NET ถือเป็นตัวเลือ ### [วิธีการเรนเดอร์ HTML เป็น PNG – คู่มือแบบขั้นตอนต่อขั้นตอน](./how-to-render-html-to-png-step-by-step-guide/) เรียนรู้วิธีการเรนเดอร์ HTML เป็น PNG ด้วย Aspose.HTML สำหรับ .NET อย่างละเอียดในคู่มือขั้นตอนนี้! -### [วิธีใช้ Aspose เพื่อเรนเดอร์ HTML เป็น PNG ด้วย C#](./how-to-use-aspose-to-render-html-to-png-in-c/) +### [วิธีใช้ Aspose เพื่อเรนเดอร์ HTML เป็น PNG ด้วย C#](./how-to-use-aspose-to-render-html-to-png/) เรียนรู้วิธีใช้ Aspose.HTML กับ C# เพื่อแปลงไฟล์ HTML เป็น PNG อย่างง่ายดาย ### [สร้างภาพจาก HTML ด้วย C# – คู่มือขั้นตอนเต็มรูปแบบ](./create-image-from-html-in-c-complete-step-by-step-guide/) เรียนรู้วิธีสร้างภาพจาก HTML ด้วย C# อย่างละเอียดด้วย Aspose.HTML สำหรับ .NET @@ -99,6 +99,9 @@ Aspose.HTML สำหรับ .NET ถือเป็นตัวเลือ ### [วิธีเรนเดอร์ HTML เป็น PNG ใน C# – คู่มือแบบขั้นตอน](./how-to-render-html-as-png-in-c-step-by-step-guide/) เรียนรู้ขั้นตอนการเรนเดอร์ไฟล์ HTML เป็น PNG ด้วย C# อย่างละเอียดในคู่มือแบบขั้นตอนนี้! +### [วิธีใช้ Aspose เพื่อเรนเดอร์ HTML เป็น PNG ใน C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +เรียนรู้วิธีใช้ Aspose.HTML กับ C# เพื่อแปลง HTML เป็น PNG อย่างง่ายดาย + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/thai/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/thai/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..c36979bdf4 --- /dev/null +++ b/html/thai/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-10-02 +description: วิธีใช้ Aspose เพื่อเรนเดอร์ HTML เป็นภาพ PNG อย่างรวดเร็ว – เรียนรู้การแปลง + HTML เป็น PNG พร้อมการทำ anti‑aliasing และการทำ hinting ตัวอักษร +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: th +lastmod: 2026-10-02 +og_description: วิธีใช้ Aspose เพื่อแปลง HTML เป็นภาพ PNG. ทำตามบทเรียนฉบับเต็มนี้เพื่อแปลง + HTML เป็น PNG ด้วยการเรนเดอร์คุณภาพสูงใน C# +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: วิธีใช้ Aspose เพื่อแปลง HTML เป็นภาพ PNG – คู่มือขั้นตอนโดยละเอียด +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: วิธีใช้ Aspose เพื่อเรนเดอร์ HTML เป็นภาพ PNG ใน C# +url: /th/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีใช้ Aspose เพื่อแปลง HTML เป็นภาพ PNG ใน C# + +**วิธีใช้ Aspose เพื่อแปลง HTML เป็นภาพ PNG** เป็นความต้องการทั่วไปเมื่อคุณต้องการดูตัวอย่างแบบบิตแมพของหน้าเว็บ, รูปย่ออีเมล, หรือภาพสแนปชอตที่เหมาะกับ PDF. บทแนะนำนี้จะแสดงวิธีแก้ปัญหาแบบครบถ้วนพร้อมรันได้ทันทีที่ **render html to image** ด้วยการทำแอนติ‑อัลลายซิ่งและการให้คำแนะนำข้อความ (text hinting) เพื่อให้ผลลัพธ์คมชัดบนทุกแพลตฟอร์ม. + +คุณจะได้เรียนรู้วิธี **convert HTML to PNG**, การกำหนดค่าตัวเลือกการเรนเดอร์, และการจัดการกับปัญหาที่พบบ่อยเช่นการเรนเดอร์ฟอนต์บน Linux และสิทธิ์การเข้าถึงไฟล์ระบบ. ไม่ต้องใช้เครื่องมือภายนอก—เพียงแค่ไลบรารี Aspose.HTML for .NET และไม่กี่บรรทัดของ C#. + +## สิ่งที่ต้องเตรียม + +ก่อนเริ่ม, ตรวจสอบว่าคุณมี: + +* .NET 6.0 SDK หรือใหม่กว่า +* Visual Studio 2022 (หรือ IDE สำหรับ C# ใดก็ได้) +* การอ้างอิง NuGet ไปยัง **Aspose.HTML** (`Install-Package Aspose.HTML`) +* ความคุ้นเคยพื้นฐานกับไวยากรณ์ C# + +ข้อกำหนดเหล่านี้มีน้ำหนักเบา; บทแนะนำทำงานบน Windows, Linux, และ macOS เนื่องจาก Aspose.HTML รองรับหลายแพลตฟอร์ม. + +## ขั้นตอนที่ 1: ติดตั้ง Aspose.HTML และสร้างโปรเจกต์คอนโซลใหม่ + +เปิดเทอร์มินัลหรือ Package Manager Console แล้วรัน: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +การสร้างโปรเจกต์แยกช่วยแยกการพึ่งพาและทำให้รันตัวอย่างด้วย `dotnet run` ได้ง่ายขึ้น. + +## ขั้นตอนที่ 2: ตั้งค่าตัวเลือกการเรนเดอร์ภาพ (anti‑aliasing และ text hinting) + +Antialiasing ทำให้ขอบเรียบ, ส่วน text hinting ช่วยให้ตัวอักษรคมชัด, โดยเฉพาะบน Linux ที่การเรนเดอร์ฟอนต์แตกต่างจาก Windows. คลาส `ImageRenderingOptions` ให้คุณเปิดใช้คุณลักษณะทั้งสอง: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**ทำไมต้องสำคัญ:** หากไม่มี antialiasing เส้นทแยงมุมและโค้งจะดูหยัก. หากไม่มี text hinting ฟอนต์ขนาดเล็กอาจเบลอ, ซึ่งสังเกตได้เมื่อคุณ **save html as png** สำหรับรูปย่อ. + +## ขั้นตอนที่ 3: กำหนด CSS สำหรับฟอนต์และสไตล์หัวเรื่องที่สอดคล้องกัน + +การฝัง CSS ลงใน HTML โดยตรงทำให้ภาพที่เรนเดอร์ตรงกับการออกแบบที่คุณคาดหวัง. ในตัวอย่างนี้เราตั้งฟอนต์พื้นฐานและทำให้ `

` เป็นอิตาลิก: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +คุณสามารถขยายสไตล์ชีตด้วยสี, ระยะขอบ, หรือ media queries. CSS จะถูกแทรกเข้าไปในแท็ก ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**เคล็ดลับ:** หากต้องการ **render html as image** จากหน้าเว็บระยะไกล, ให้เปลี่ยนตัวสร้างสตริงเป็น `new HTMLDocument("https://example.com")`. Aspose จะดาวน์โหลดหน้า, แก้ไขทรัพยากร, และเรนเดอร์เลย์เอาต์สุดท้าย. + +## ขั้นตอนที่ 5: เรนเดอร์เอกสารเป็นไฟล์ PNG + +ตอนนี้เราจะเรียก `RenderToImage`, ส่งพาธผลลัพธ์และตัวเลือกที่กำหนดไว้ก่อนหน้า: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +ไฟล์ `output.png` ที่สร้างขึ้นจะมีการเรนเดอร์คมชัดขององค์ประกอบ `

` ที่มีสไตล์อิตาลิก, ขอบเรียบและข้อความคมชัดจากการตั้งค่า antialiasing และ hinting. + +## รายการโค้ดเต็ม + +คัดลอกโค้ดต่อไปนี้ไปยัง `Program.cs`. โค้ดจะคอมไพล์และทำงานได้ทันที: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +การรันโปรแกรมจะสร้าง `output.png` ในโฟลเดอร์โปรเจกต์. ภาพจะแสดงคำ **Sample** ในฟอนต์ Arial แบบอิตาลิก, เรนเดอร์ด้วยขอบเรียบและข้อความชัดเจน. เปิดไฟล์ด้วยโปรแกรมดูภาพใดก็ได้เพื่อยืนยันคุณภาพ. + +## ขั้นตอนที่ 6: ตัวแปรทั่วไปและการจัดการกรณีขอบ + +| สถานการณ์ | สิ่งที่ต้องปรับ | เหตุผล | +|-----------|----------------|--------| +| **HTML หน้าใหญ่** | ตั้งค่า `ImageRenderingOptions.Width` / `Height` หรือใช้ `PageSize` เพื่อควบคุมขนาดผลลัพธ์ | ป้องกันการใช้หน่วยความจำมากเกินไปและทำให้ PNG พอดีกับ UI ของคุณ | +| **ฟอนต์บน Linux ขาด** | ติดตั้งฟอนต์ที่ต้องการบนโฮสต์ (`apt-get install fonts‑arial` หรือใช้ไฟล์ฟอนต์กำหนดเอง) แล้วชี้ Aspose ไปที่มันผ่าน `FontSettings` | หากไม่มีฟอนต์, Aspose จะใช้ฟอนต์ทั่วไปแทน, ทำให้รูปลักษณ์เปลี่ยนไป | +| **ต้องการพื้นหลังโปร่งใส** | ตั้งค่า `imgOptions.BackgroundColor = Color.Transparent` | มีประโยชน์เมื่อฝัง PNG ลงในกราฟิกอื่น | +| **การแปลงเป็นชุด** | วนลูปผ่านรายการสตริง HTML หรือพาธไฟล์, ใช้ `ImageRenderingOptions` ตัวเดียวกัน | เพิ่มประสิทธิภาพและทำให้การตั้งค่าเรนเดอร์สอดคล้องกัน | + +## เคล็ดลับระดับมืออาชีพ: แคชตัวเลือกการเรนเดอร์ + +การสร้างอ็อบเจ็กต์ `ImageRenderingOptions` ใหม่สำหรับแต่ละการแปลงเพิ่มภาระงาน. ประกาศเป็น static หากคุณประมวลผล HTML จำนวนมากในบริการ: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +ใช้ `SharedOptions` ซ้ำในการเรียกเพื่อรักษาการใช้ CPU ให้ต่ำ. + +## คำถามที่พบบ่อย + +**ถาม: ทำงานกับ .NET Core บน macOS ได้หรือไม่?** +ตอบ: ได้. Aspose.HTML รองรับหลายแพลตฟอร์มเต็มรูปแบบ. ตรวจสอบให้แน่ใจว่าฟอนต์ที่ต้องการถูกติดตั้ง, และไดเรกทอรีผลลัพธ์สามารถเขียนได้. + +**ถาม: สามารถเรนเดอร์เป็น JPEG แทน PNG ได้หรือไม่?** +ตอบ: เปลี่ยน `RenderToImage("output.png", imgOptions)` เป็น `RenderToImage("output.jpg", imgOptions)`. คุณยังสามารถตั้งค่า `imgOptions.ImageFormat = ImageFormat.Jpeg` เพื่อควบคุมคุณภาพได้ละเอียดขึ้น. + +**ถาม: จะฝังไฟล์ CSS ภายนอกอย่างไร?** +ตอบ: โหลดเนื้อหา CSS เข้าเป็นสตริงและต่อเข้าด้วยกัน, หรืออ้างอิง stylesheet ระยะไกลในแท็ก ``. Aspose จะจัดการ `` อัตโนมัติเมื่อเอกสารถูกโหลดจาก URL. + +## สรุป + +ตอนนี้คุณรู้ **วิธีใช้ Aspose** เพื่อ **render HTML to PNG** (หรือรูปแบบเรสเตอร์อื่น) ด้วยการตั้งค่าคุณภาพสูง. บทแนะนำได้ครอบคลุมการติดตั้ง Aspose.HTML, การกำหนด antialiasing และ text hinting, การแทรก CSS, การโหลด HTML, และสุดท้าย **saving HTML as PNG**. ด้วยขั้นตอนเหล่านี้คุณสามารถ **convert HTML to PNG** อย่างเชื่อถือได้ในแอปพลิเคชัน .NET ใดก็ได้, ไม่ว่าจะทำงานบน Windows, Linux, หรือ macOS. + +### ขั้นตอนต่อไป + +* สำรวจรูปแบบผลลัพธ์อื่นเช่น **render html as image** JPEG หรือ BMP โดยเปลี่ยนส่วนขยายไฟล์. +* ผสานวิธีนี้กับ **Aspose.PDF** เพื่อฝัง PNG ลงในรายงาน PDF. +* ทดลองใช้ `ImageRenderingOptions.DpiX` และ `DpiY` สำหรับรูปย่อความละเอียดสูง. + +ปรับโค้ดให้เหมาะกับการประมวลผลเป็นชุด, การสร้าง HTML แบบไดนามิก, หรือการรวมเข้ากับเว็บเซอร์วิสที่ส่งคืน PNG preview ตามคำขอ. ขอให้สนุกกับการเรนเดอร์! + +## สิ่งที่คุณควรเรียนต่อไป + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคในคู่มือนี้. แต่ละแหล่งข้อมูลมีโค้ดตัวอย่างทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอนเพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่นในโปรเจกต์ของคุณ. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 9af9089740..1b9b6858d7 100644 --- a/html/turkish/net/html-extensions-and-conversions/_index.md +++ b/html/turkish/net/html-extensions-and-conversions/_index.md @@ -89,7 +89,7 @@ Aspose.HTML for .NET kullanarak özel kaynak işleyiciyle bellek içinden HTML'y ### [C#'ta HTML'yi ZIP'e Sıkıştırma – HTML'yi Yükle ve Özel İşleyici Kullan](./how-to-zip-html-in-c-load-html-use-custom-handler/) Aspose.HTML for .NET kullanarak HTML'yi yükleyip özel bir işleyiciyle ZIP arşivine dönüştürün. ### [C#'ta Özel Kaynak İşleyicisi – HTML'yi ZIP'e Dönüştürme Öğreticisi](./custom-resource-handler-in-c-convert-html-to-zip-tutorial/) -Aspose.HTML for .NET kullanarak C#'ta özel bir kaynak işleyicisi ile HTML dosyalarını ZIP arşivine dönüştürün. Adım adım kılavuz. +Aspose.HTML for .NET kullanarak C#'ta özel bir kaynak işleyicisi ile HTML dosalarını ZIP arşivine dönüştürün. Adım adım kılavuz. ### [C#'ta HTML'yi Zip'leme – Tam Adım‑Adım Kılavuz](./how-to-zip-html-in-c-complete-step-by-step-guide/) C# ve Aspose.HTML kullanarak HTML dosyalarını zip arşivine dönüştürmeyi adım adım öğrenin. ### [Aspose.HTML ile .NET'te HTML'yi ZIP olarak kaydedin](./save-html-as-zip-in-c-complete-step-by-step-guide/) @@ -104,7 +104,10 @@ Aspose.HTML for .NET kullanarak C# ile HTML'yi akışa kaydetmeyi adım adım ö ### [Aspose.HTML'de Handler Kullanımı – HTML Yükle ve ZIP Olarak Kaydet](./how-to-use-handler-in-aspose-html-load-html-save-as-zip/) Aspose.HTML for .NET ile bir handler aracılığıyla HTML dosyasını yükleyin ve ZIP arşivine kaydedin. Adım adım rehber. ### [C# ile HTML'yi ZIP Olarak Kaydet – Tam Kılavuz](./save-html-as-zip-in-c-complete-guide/) -Aspose.HTML for .NET ile C# içinde HTML dosyalarını ZIP arşivine kaydetmeyi adım adım öğrenin. +Aspose.HTML for .NET ile C# içinde HTML dosalarını ZIP arşivine kaydetmeyi adım adım öğrenin. +### [Aspose.HTML ile .NET'te HTML'yi ZIP'e dönüştürün](./convert-html-to-zip-in-c-complete-guide/) +### [Aspose.HTML ile HTML'yi zip olarak kaydedip resimleri dahil edin](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) +Aspose.HTML kullanarak HTML'yi zip arşivine kaydedip içinde resimleri de dahil etmeyi adım adım öğrenin. {{< /blocks/products/pf/tutorial-page-section >}} @@ -117,4 +120,4 @@ Aspose.HTML for .NET ile HTML'yi PDF'ye tam adım‑adım dönüştürün. Ayrı ### [C# ile Zip Dosyası Oluşturma – Bellekte HTML'yi Zip'lemek için Adım Adım Kılavuz](./create-zip-file-c-step-by-step-guide-to-zip-html-in-memory/) C# kullanarak bellek içindeki HTML içeriğini zip dosyasına dönüştürmeyi adım adım öğrenin. ### [Aspose.HTML ile .NET'te HTML'yi ZIP'e dönüştürün](./convert-html-to-zip-in-c-complete-guide/) -Aspose.HTML for .NET kullanarak HTML'yi ZIP arşivine dönüştürün. Adım adım kılavuz ve özelleştirilebilir seçenekler. +Aspose.HTML for .NET kullanarak HTML'yi ZIP arşivine dönüştürün. Adım adım kılavuz ve özelleştirilebilir seçenekler. \ No newline at end of file diff --git a/html/turkish/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/turkish/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..5856238fd2 --- /dev/null +++ b/html/turkish/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,344 @@ +--- +category: general +date: 2026-10-02 +description: Aspose.HTML'i C#'ta kullanarak HTML'yi zip olarak kaydetmeyi öğrenin. + Bu kılavuz ayrıca HTML'yi görsellerle birlikte tek bir arşivde kaydetmeyi gösterir. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: tr +lastmod: 2026-10-02 +og_description: Aspose.HTML'i C#'de kullanarak HTML'yi zip olarak kaydedin. Görselleriyle + birlikte HTML'yi tek bir arşivde nasıl kaydedeceğinizi öğrenmek için bu kapsamlı + öğreticiyi izleyin. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Aspose.HTML ile HTML'yi zip olarak kaydedin – adım adım C# rehberi +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Aspose.HTML ile HTML'yi zip olarak kaydetme ve resimleri ekleme +url: /tr/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.HTML ile HTML'yi zip olarak kaydetme ve resimleri dahil etme + +Eğer **HTML'yi zip olarak kaydetmek** istiyorsanız ve dağıtımı kolaylaştırmak istiyorsanız, bu öğretici Aspose.HTML for .NET kullanarak tam adımları gösterir. Statik bir sayfa, bir e‑posta şablonu ya da içinde resimler bulunan bir rapor dışa aktarırken, HTML, CSS ve resim dosyalarını tek bir ZIP arşivine nasıl paketleyeceğinizi, geçici dosyalar oluşturmadan göreceksiniz. + +Ana hedefin yanı sıra, yaygın bir takip sorusu olan **HTML'yi resimlerle birlikte nasıl kaydederim** sorusuna da yanıt vererek, oluşturulan arşivin herhangi bir tarayıcıda eksik kaynak olmadan açılmasını sağlayacağız. + +Bu rehberin sonunda yeniden kullanılabilir bir `ResourceHandler` uygulamanız, `output.zip` üreten tam bir C# programınız ve büyük resimler ya da özel klasör yapılarıyla çalışırken pratik ipuçlarınız olacak. + +## Gereksinimler + +- .NET 6.0 veya daha yeni bir sürüm (API .NET Framework 4.6+ ile de çalışır) +- Aspose.HTML for .NET NuGet paketi (`Aspose.Html`) +- C# ve akışlar (streams) hakkında temel bilgi +- Visual Studio 2022 veya .NET geliştirmeyi destekleyen herhangi bir IDE + +> **Pro ipucu:** Proje dosyanızı temiz tutmak için paketi CLI üzerinden kurun: +> `dotnet add package Aspose.Html` + +## Adım 1: Aspose.HTML’in çıktı modelini anlayın + +Aspose.HTML bir belgeyi kaydettiğinde, her dış kaynağı (CSS dosyaları, resimler, fontlar vb.) ayrı bir **resource** olarak ele alır. Varsayılan olarak kütüphane bu kaynakları dosya sistemine yazar. Hedefi kontrol etmek için özel bir `ResourceHandler` sağlarsınız. Handler bir `Resource` nesnesi alır ve yazılabilir bir `Stream` döndürmelidir. Aspose.HTML daha sonra kaynak verilerini bu akıma yazar. + +Özel bir handler kullanmanın avantajları: + +- Kaynakları doğrudan bir `MemoryStream` içine yazarak daha sonra ZIP girdisi haline getirir +- Kaynakları bir veritabanına, bulut depolamaya veya başka bir ortama kaydeder +- Dosya adlarını, sıkıştırma seviyelerini veya klasör hiyerarşilerini ayarlar + +## Adım 2: ZIP arşivine yazan bir `ResourceHandler` oluşturun + +Aşağıda, bellekte bir `System.IO.Compression.ZipArchive` oluşturan tam işlevsel bir handler örneği yer alıyor. Her kaynak, orijinal URL yolunu yansıtan bir giriş olarak eklenir; böylece ZIP açıldığında tarayıcı göreli bağlantıları çözebilir. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Bu yaklaşımın neden çalıştığı + +- **Bellek içi işlem**: Diskte geçici dosyalar oluşturulmaz; bu, web servisleri veya sandbox ortamları için idealdir. +- **Klasör hiyerarşisini korur**: Orijinal kaynak URI’si kullanılarak göreli referanslar çıkarma sonrası geçerli kalır. +- **Genişletilebilir**: `MemoryStream` yerine bir `FileStream` kullanarak doğrudan dosyaya yazabilir veya bulut depolama için bir ağ akışı (network stream) kullanabilirsiniz. + +## Adım 3: HTML belgesini yükleyin veya oluşturun + +Gösterim amacıyla dış bir resme referans veren basit bir HTML dizesi oluşturacağız. Gerçek bir projede HTML’i bir dosyadan, veritabanından veya bir HTTP yanıtından yüklersiniz. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Not:** Fiziksel bir HTML dosyanız varsa, `new HTMLDocument("path/to/file.html")` ifadesini kullanın. + +## Adım 4: Handler’ı `SaveOptions`’a bağlayın ve ZIP’i kaydedin + +Şimdi `ZipResourceHandler`’ı `SaveOptions.OutputStorage`’a bağlayacağız. `document.Save` çalıştığında, Aspose.HTML her kaynak için `HandleResource` metodunu çağırır ve handler ZIP arşivini doldurur. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Beklenen sonuç + +- `output.zip` şunları içerir: + - `index.html` (ana HTML dosyası) + - `images/logo.png` (işaretlemede kullanılan resim) + - Aspose.HTML tarafından otomatik algılanan ek CSS veya font dosyaları + +Arşivi çıkartıp `index.html` dosyasını bir tarayıcıda açtığınızda resim doğru şekilde görüntülenir—bu da **HTML'yi resimlerle birlikte zip içinde nasıl kaydederiz** sorusunun cevabıdır. + +## Adım 5: Arşivi doğrulayın ve yaygın sorunları giderin + +### Hızlı doğrulama betiği + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Betik çalıştırıldığında `index.html` ve `images/logo.png` listelenmelidir. Eğer beklenen bir kaynak eksikse: + +- **Resim URL’sini kontrol edin**: HTML belgesinden erişilebilir olmalı. Göreli yollar en iyi sonucu verir. +- **Kaynak türünün desteklendiğinden emin olun**: Aspose.HTML yaygın web formatlarını (PNG, JPEG, GIF, CSS, JS) işler. Alışılmadık formatlar manuel ekleme gerektirebilir. +- **`HandleResource`’un çağrıldığını doğrulayın**: `HandleResource` içinde `Console.WriteLine(resource.Uri)` ekleyerek hata ayıklayın. + +## Adım 6: İleri seviye varyasyonlar + +### 6.1 Ara bir bayt dizisi olmadan doğrudan dosyaya kaydetme + +Çok büyük belgeler için bellek kullanımı bir sorun ise, `MemoryStream` yerine bir `FileStream` kullanın: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Ardından şu şekilde kullanın: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Giriş (entry) adlarını özelleştirme + +Düz bir yapı (tüm dosyalar kök dizinde) istiyorsanız, `entryName` değerini şu şekilde ayarlayın: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Manifest dosyası ekleme + +Bazen sonraki araçlar bir `manifest.json` bekler. Ana kaydetme işleminden sonra bunu ekleyebilirsiniz: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Yaygın tuzaklar ve nasıl önlenir + +| Tuzak | Neden oluşur | Çözüm | +|-------|--------------|------| +| Çıkarıldıktan sonra resimler bozuk görünür | HTML içindeki resim yolu ZIP girdisi adıyla eşleşmez. | `ZipArchiveEntry` oluştururken orijinal göreli yolu koruyun. | +| Büyük resimler bellek dışı (out‑of‑memory) hatasına yol açar | `MemoryStream` çok büyük dosyalar için süreç belleğini aşabilir. | `FileStream`‑tabanlı handler’a geçin (bkz. 6.1). | +| CSS URL’leri eksik | `@import` ile referans verilen dış CSS dosyaları otomatik algılanmaz. | Bu CSS dosyalarını ZIP’e manuel ekleyin veya kaydetmeden önce satır içi (inline) yapın. | +| Unicode karakterler bozulur | Varsayılan kodlama HTML kaynağı ile akış arasında farklılık gösterebilir. | HTML dizesinin UTF‑8 olduğundan emin olun; Aspose.HTML belge charset’ini korur. | + +## Tam çalışan örnek (kopyala‑yapıştır hazır) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + + +## What Should You Learn Next? + + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanan yakın konuları kapsar. Her kaynak, adım adım açıklamalarla tam çalışan kod örnekleri içerir; böylece ek API özelliklerini öğrenebilir ve projelerinizde alternatif uygulama yaklaşımlarını keşfedebilirsiniz. + +- [Aspose.HTML’de handler nasıl kullanılır – HTML yükle, ZIP olarak kaydet](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [C#’ta HTML nasıl kaydedilir – Özel Resource Handler’lar & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [HTML’yi PNG’ye render et ve C# ile ZIP’e kaydet – Tam Kılavuz](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 140e766cb9..16004bd61a 100644 --- a/html/turkish/net/rendering-html-documents/_index.md +++ b/html/turkish/net/rendering-html-documents/_index.md @@ -86,6 +86,8 @@ Aspose.HTML for .NET ile C# kullanarak HTML'den görüntü oluşturmayı adım a Aspose.HTML for .NET kullanarak HTML dosyalarını PDF formatına dönüştürmeyi adım adım öğrenin. ### [C#'ta HTML'yi PNG Olarak İşleme – Adım Adım Kılavuz](./how-to-render-html-as-png-in-c-step-by-step-guide/) C# kullanarak HTML'yi PNG'ye dönüştürmeyi adım adım öğrenin. Örnek kodlar ve pratik ipuçlarıyla rehberiniz burada. +### [C#'ta Aspose kullanarak HTML'yi PNG görüntüsü olarak render etme](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +C# ile Aspose kullanarak HTML'yi PNG görüntüsüne dönüştürmeyi adım adım öğrenin. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/turkish/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/turkish/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..72f81049a2 --- /dev/null +++ b/html/turkish/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-10-02 +description: Aspose kullanarak HTML'yi hızlı bir şekilde PNG görüntüsüne nasıl render + ederiz – anti‑aliasing ve metin ipuçlarıyla HTML'yi PNG'ye dönüştürmeyi öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: tr +lastmod: 2026-10-02 +og_description: Aspose kullanarak HTML'yi PNG görüntüsüne nasıl render edersiniz. + C#'ta yüksek kaliteli render ile HTML'yi PNG'ye dönüştürmek için bu tam öğreticiyi + izleyin. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Aspose ile HTML'yi PNG görüntüsüne dönüştürme – adım adım rehber +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Aspose kullanarak C#’ta HTML’yi PNG görüntüsüne nasıl render ederiz +url: /tr/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose kullanarak C#'ta HTML'yi PNG görüntüsüne dönüştürme + +**Aspose kullanarak HTML'yi PNG görüntüsüne dönüştürme** genellikle bir web sayfasının bitmap önizlemesi, bir e‑posta küçük resmi veya PDF‑uyumlu bir anlık görüntü gerektiğinde ortaya çıkan bir ihtiyaçtır. Bu öğreticide, **render html to image** işlemini anti‑aliasing ve metin hinting ile gerçekleştiren, her platformda keskin görünen tam bir, çalıştırmaya hazır çözüm gösterilmektedir. + +HTML'yi PNG'ye **dönüştürmeyi**, render seçeneklerini yapılandırmayı ve Linux font render'ı ve dosya sistemi izinleri gibi tipik sorunları nasıl ele alacağınızı öğreneceksiniz. Harici bir araç gerekmez—sadece Aspose.HTML for .NET kütüphanesi ve birkaç satır C# yeterlidir. + +## Gereksinimler + +Başlamadan önce şunların yüklü olduğundan emin olun: + +* .NET 6.0 SDK veya daha yeni bir sürüm +* Visual Studio 2022 (veya herhangi bir C# IDE) +* **Aspose.HTML** NuGet referansı (`Install-Package Aspose.HTML`) +* C# sözdizimi hakkında temel bilgi + +Bu gereksinimler hafiftir; öğretici Windows, Linux ve macOS'ta çalışır çünkü Aspose.HTML çapraz‑platformdur. + +## Adım 1: Aspose.HTML'i kurun ve yeni bir konsol projesi oluşturun + +Bir terminal ya da Package Manager Console açın ve şu komutu çalıştırın: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Bağımlılıkları izole eden ve örneği `dotnet run` ile kolayca çalıştırmanızı sağlayan ayrı bir proje oluşturmuş olursunuz. + +## Adım 2: Görüntü render seçeneklerini ayarlayın (anti‑aliasing ve metin hinting) + +Antialiasing kenarları yumuşatırken, metin hinting özellikle Linux'ta font rasterizasyonu Windows'tan farklı olduğunda glif netliğini artırır. `ImageRenderingOptions` sınıfı her iki özelliği de etkinleştirmenizi sağlar: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Neden önemli:** Antialiasing olmadan çapraz çizgiler ve eğriler pikselli görünür. Metin hinting olmadan küçük font boyutları bulanıklaşabilir; bu durum **save html as png** işlemiyle küçük resimler oluştururken fark edilir. + +## Adım 3: Tutarlı fontlar ve başlık stilleri için CSS tanımlayın + +CSS'i doğrudan HTML'e gömmek, render edilen görüntünün tasarım beklentilerinize uymasını sağlar. Bu örnekte temel bir font belirliyor ve `

` etiketini italik yapıyoruz: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Stil sayfasını renkler, kenar boşlukları veya medya sorguları ekleyerek genişletebilirsiniz. CSS, HTML belgesinin ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**İpucu:** Uzaktaki bir sayfadan **render html as image** yapmanız gerekiyorsa, string oluşturucusunu `new HTMLDocument("https://example.com")` ile değiştirin. Aspose sayfayı indirir, kaynakları çözer ve nihai düzeni render eder. + +## Adım 5: Belgeyi PNG dosyasına render edin + +Şimdi `RenderToImage` metodunu çağırıp çıktı yolunu ve önceden yapılandırdığınız seçenekleri gönderiyoruz: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +Oluşturulan `output.png`, anti‑aliasing ve hinting ayarları sayesinde italik stil verilen `

` öğesinin net bir render'ını içerir. + +## Tam program listesi + +Aşağıdaki kodu `Program.cs` dosyanıza kopyalayın. Derlenir ve olduğu gibi çalışır: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Beklenen çıktı + +Programı çalıştırdığınızda proje klasöründe `output.png` oluşur. Görüntü, italik Arial ile **Sample** kelimesini yumuşak kenarlarla ve net metinle gösterir. Kaliteyi doğrulamak için dosyayı herhangi bir görüntü görüntüleyicide açın. + +## Adım 6: Yaygın varyasyonlar ve kenar‑durumu yönetimi + +| Durum | Ne ayarlanmalı | Sebep | +|-----------|----------------|--------| +| **Büyük HTML sayfaları** | `ImageRenderingOptions.Width` / `Height` ayarlayın veya `PageSize` kullanarak çıktı boyutlarını kontrol edin | Bellek aşımını önler ve PNG'nin UI'nize sığmasını sağlar | +| **Linux'ta font eksikliği** | Gerekli fontları hosta kurun (`apt-get install fonts‑arial` gibi) ve `FontSettings` ile Aspose'e gösterin | Font bulunamazsa Aspose genel bir fonta geçer, görünüm değişir | +| **Şeffaf arka plan gerekiyor** | `imgOptions.BackgroundColor = Color.Transparent` ayarlayın | PNG'yi başka grafiklere gömmek istediğinizde faydalıdır | +| **Toplu dönüşüm** | HTML stringleri veya dosya yolları listesini döngüye alın, aynı `ImageRenderingOptions` nesnesini yeniden kullanın | Performansı artırır ve render ayarlarının tutarlı kalmasını sağlar | + +## Pro ipucu: render seçeneklerini önbelleğe alma + +Her dönüşüm için yeni bir `ImageRenderingOptions` nesnesi oluşturmak ek yük getirir. Bir hizmette çok sayıda HTML snippet'i işliyorsanız statik bir örnek tanımlayın: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +CPU kullanımını düşük tutmak için `SharedOptions` nesnesini çağrılar arasında yeniden kullanın. + +## Sıkça sorulan sorular + +**S: Bu, macOS'ta .NET Core ile çalışır mı?** +C: Evet. Aspose.HTML tamamen çapraz‑platformdur. Gerekli fontların kurulu olduğundan ve çıktı dizininin yazılabilir olduğundan emin olun. + +**S: PNG yerine JPEG render edebilir miyim?** +C: `RenderToImage("output.png", imgOptions)` satırını `RenderToImage("output.jpg", imgOptions)` ile değiştirin. Kalite kontrolü için `imgOptions.ImageFormat = ImageFormat.Jpeg` de ayarlayabilirsiniz. + +**S: Harici CSS dosyalarını nasıl eklerim?** +C: CSS içeriğini bir string olarak yükleyip birleştirin veya `` etiketinde uzak bir stil sayfasına referans verin. Aspose, belge bir URL'den yüklendiğinde `` etiketlerini otomatik olarak çözer. + +## Sonuç + +Artık **Aspose kullanarak HTML'yi PNG'ye (veya başka bir raster formata) yüksek kalite ayarlarıyla render etme** konusunda bilgi sahibisiniz. Öğreticide Aspose.HTML'in kurulumu, anti‑aliasing ve metin hinting yapılandırması, CSS enjeksiyonu, HTML yükleme ve sonunda **HTML'yi PNG olarak kaydetme** adımları ele alındı. Bu adımları izleyerek Windows, Linux veya macOS üzerinde çalışan herhangi bir .NET uygulamasında güvenilir bir şekilde **HTML'yi PNG'ye dönüştürebilirsiniz**. + +### Sonraki adımlar + +* Dosya uzantısını değiştirerek **render html as image** JPEG veya BMP gibi diğer çıktı formatlarını keşfedin. +* Bu yaklaşımı **Aspose.PDF** ile birleştirerek PNG'yi PDF raporuna gömün. +* Yüksek çözünürlüklü küçük resimler için `ImageRenderingOptions.DpiX` ve `DpiY` ile deneyler yapın. + +Kodu toplu işleme, dinamik HTML üretimi veya talep üzerine PNG önizlemeleri döndüren bir web servisine entegrasyon için uyarlamaktan çekinmeyin. İyi renderlamalar! + +## Bir Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayalı olarak yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak tam çalışan kod örnekleri ve adım‑adım açıklamalar içerir. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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 055eaa664f..7d7d6e1d4f 100644 --- a/html/vietnamese/net/html-extensions-and-conversions/_index.md +++ b/html/vietnamese/net/html-extensions-and-conversions/_index.md @@ -129,6 +129,7 @@ Hướng dẫn cách sử dụng Aspose.HTML để lưu HTML trực tiếp vào Hướng dẫn chi tiết cách sử dụng handler trong Aspose.HTML để tải tài liệu HTML và lưu lại dưới dạng tệp ZIP. ### [Tạo tài liệu HTML và lưu dưới dạng zip – Hướng dẫn C# hoàn chỉnh](./create-html-document-and-save-as-zip-complete-c-guide/) Hướng dẫn chi tiết cách tạo tài liệu HTML và lưu nó dưới dạng tệp ZIP bằng C# và Aspose.HTML cho .NET. +### [Cách lưu HTML thành ZIP với Aspose.HTML và bao gồm hình ảnh](./how-to-save-html-as-zip-with-aspose-html-and-include-images/) ## Phần kết luận diff --git a/html/vietnamese/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md b/html/vietnamese/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md new file mode 100644 index 0000000000..fa4d07b026 --- /dev/null +++ b/html/vietnamese/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/_index.md @@ -0,0 +1,332 @@ +--- +category: general +date: 2026-10-02 +description: Tìm hiểu cách lưu HTML dưới dạng zip bằng Aspose.HTML trong C#. Hướng + dẫn này cũng chỉ cách lưu HTML kèm hình ảnh trong một tệp lưu trữ duy nhất. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html as zip +- how to save html with images +- Aspose.HTML zip export +- C# resource handler +- HTML to archive +language: vi +lastmod: 2026-10-02 +og_description: Lưu HTML dưới dạng zip bằng Aspose.HTML trong C#. Theo dõi hướng dẫn + đầy đủ này để học cách lưu HTML kèm hình ảnh vào một tệp lưu trữ duy nhất. +og_image_alt: Screenshot of C# code that saves HTML as zip using Aspose.HTML +og_title: Lưu HTML dưới dạng zip với Aspose.HTML – hướng dẫn C# từng bước +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + headline: How to save HTML as zip with Aspose.HTML and include images + type: TechArticle +- description: Learn how to save HTML as zip using Aspose.HTML in C#. This guide also + shows how to save HTML with images in a single archive. + name: How to save HTML as zip with Aspose.HTML and include images + steps: + - name: Why this approach works + text: '- **In‑memory operation**: No temporary files are created on disk, which + is ideal for web services or sandboxed environments. - **Preserves folder hierarchy**: + By using the original resource URI, relative references remain valid after extraction. + - **Extensible**: You can replace `MemoryStream` with' + - name: Expected result + text: '- `output.zip` contains: - `index.html` (the main HTML file) - `images/logo.png` + (the image referenced in the markup) - Any additional CSS or font files automatically + detected by Aspose.HTML' + - name: Quick verification script + text: '```csharp using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) { Console.WriteLine("Archive + contains the following entries:"); foreach (var entry in zip.Entries) Console.WriteLine($"- + {entry.FullName}"); } ```' + - name: 6.1 Saving directly to a file without an intermediate byte array + text: 'If memory usage is a concern for very large documents, replace `MemoryStream` + with a `FileStream`:' + - name: 6.2 Customizing entry names + text: 'If you prefer a flat structure (all files at the root), adjust `entryName`:' + - name: 6.3 Adding a manifest file + text: 'Sometimes downstream tools expect a `manifest.json`. You can add it after + the main save:' + type: HowTo +tags: +- Aspose.HTML +- C# +- zip +- HTML export +title: Cách lưu HTML dưới dạng zip với Aspose.HTML và bao gồm hình ảnh +url: /vi/net/html-extensions-and-conversions/how-to-save-html-as-zip-with-aspose-html-and-include-images/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách lưu HTML dưới dạng zip với Aspose.HTML và bao gồm hình ảnh + +Nếu bạn cần **lưu HTML dưới dạng zip** để phân phối dễ dàng, hướng dẫn này sẽ chỉ cho bạn các bước chính xác bằng cách sử dụng Aspose.HTML cho .NET. Dù bạn đang xuất một trang tĩnh, một mẫu email, hoặc một báo cáo chứa hình ảnh, bạn sẽ thấy cách gói HTML, CSS và các tệp hình ảnh vào một tệp ZIP duy nhất mà không cần ghi các tệp tạm thời lên đĩa. + +Ngoài mục tiêu chính, chúng tôi cũng sẽ trả lời câu hỏi thường gặp **cách lưu HTML có hình ảnh** để tệp lưu trữ kết quả có thể được mở bằng bất kỳ trình duyệt nào mà không thiếu tài nguyên. + +Khi kết thúc hướng dẫn này, bạn sẽ có một triển khai `ResourceHandler` có thể tái sử dụng, một chương trình C# hoàn chỉnh tạo ra `output.zip`, và các mẹo thực tế để xử lý hình ảnh lớn hoặc cấu trúc thư mục tùy chỉnh. + +## Yêu cầu trước + +- .NET 6.0 trở lên (API cũng hoạt động với .NET Framework 4.6+) +- Gói NuGet Aspose.HTML for .NET (`Aspose.Html`) +- Kiến thức cơ bản về C# và streams +- Visual Studio 2022 hoặc bất kỳ IDE nào hỗ trợ phát triển .NET + +> **Mẹo chuyên nghiệp:** Cài đặt gói qua CLI để giữ file dự án sạch sẽ: +> `dotnet add package Aspose.Html` + +## Bước 1: Hiểu mô hình đầu ra của Aspose.HTML + +Khi Aspose.HTML lưu một tài liệu, nó coi mỗi tài nguyên bên ngoài (tệp CSS, hình ảnh, phông chữ, v.v.) là một **resource** riêng biệt. Mặc định thư viện ghi các tài nguyên này vào hệ thống tệp. Để kiểm soát vị trí lưu, bạn cung cấp một `ResourceHandler` tùy chỉnh. Trình xử lý nhận một đối tượng `Resource` và phải trả về một `Stream` có thể ghi. Aspose.HTML sau đó sẽ ghi dữ liệu tài nguyên vào stream đó. + +Sử dụng trình xử lý tùy chỉnh cho phép bạn: + +- Ghi tài nguyên trực tiếp vào `MemoryStream` sau đó trở thành một mục ZIP +- Lưu tài nguyên vào cơ sở dữ liệu, lưu trữ đám mây, hoặc bất kỳ phương tiện nào khác +- Điều chỉnh tên tệp, mức nén, hoặc cấu trúc thư mục + +## Bước 2: Tạo một `ResourceHandler` ghi vào tệp ZIP + +Dưới đây là một trình xử lý hoạt động đầy đủ, xây dựng một `System.IO.Compression.ZipArchive` trong bộ nhớ. Mỗi tài nguyên được thêm như một mục mới với tên phản chiếu đường dẫn URL gốc, đảm bảo trình duyệt có thể giải quyết các liên kết tương đối khi ZIP được giải nén. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// A custom resource handler that writes every HTML resource into an in‑memory ZIP archive. +/// +class ZipResourceHandler : ResourceHandler, IDisposable +{ + private readonly MemoryStream _zipStream = new(); + private readonly ZipArchive _zipArchive; + + public ZipResourceHandler() + { + // Initialise a ZipArchive that will hold all resources. + _zipArchive = new ZipArchive(_zipStream, ZipArchiveMode.Create, leaveOpen: true); + } + + /// + /// Aspose.HTML calls this method for each resource (HTML, CSS, images, etc.). + /// + /// Information about the resource to be saved. + /// A writable stream that Aspose.HTML will fill with the resource data. + public override Stream HandleResource(Resource resource) + { + // Derive a safe entry name. For example, "/styles/main.css" becomes "styles/main.css". + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + if (string.IsNullOrWhiteSpace(entryName)) + entryName = "index.html"; + + // Create a new entry inside the ZIP. Use Deflate compression for smaller size. + var zipEntry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + // Return the entry's stream; Aspose.HTML writes directly into it. + return zipEntry.Open(); + } + + /// + /// Retrieves the final ZIP as a byte array. Call after document.Save(). + /// + public byte[] GetZipBytes() + { + // Ensure all entries are flushed. + _zipArchive.Dispose(); + return _zipStream.ToArray(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _zipStream?.Dispose(); + } +} +``` + +### Tại sao cách tiếp cận này hoạt động + +- **Hoạt động trong bộ nhớ**: Không tạo tệp tạm thời trên đĩa, rất thích hợp cho dịch vụ web hoặc môi trường sandbox. +- **Giữ nguyên cấu trúc thư mục**: Bằng cách sử dụng URI tài nguyên gốc, các tham chiếu tương đối vẫn hợp lệ sau khi giải nén. +- **Mở rộng**: Bạn có thể thay thế `MemoryStream` bằng `FileStream` để ghi trực tiếp vào tệp, hoặc bằng một network stream cho lưu trữ đám mây. + +## Bước 3: Tải hoặc tạo tài liệu HTML + +Để minh họa, chúng ta sẽ tạo một chuỗi HTML đơn giản tham chiếu đến một hình ảnh bên ngoài. Trong dự án thực tế, bạn sẽ tải HTML từ tệp, cơ sở dữ liệu, hoặc phản hồi HTTP. + +```csharp +// Example HTML that includes an image tag. +string htmlContent = @" + + + + Sample Page + + + +

Hello world!

+

This page demonstrates saving HTML with images.

+ Logo + +"; + +// Create an HTMLDocument instance from the string. +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +> **Lưu ý:** Nếu bạn có tệp HTML thực, hãy sử dụng `new HTMLDocument("path/to/file.html")` thay thế. + +## Bước 4: Kết nối trình xử lý với `SaveOptions` và lưu ZIP + +Bây giờ chúng ta kết nối `ZipResourceHandler` với `SaveOptions.OutputStorage`. Khi `document.Save` được thực thi, Aspose.HTML sẽ gọi `HandleResource` cho mỗi tài nguyên, và trình xử lý sẽ điền dữ liệu vào tệp ZIP. + +```csharp +// Instantiate the custom handler. +using var zipHandler = new ZipResourceHandler(); + +// Configure save options to use the handler. +SaveOptions saveOptions = new SaveOptions +{ + // OutputStorage tells Aspose.HTML where to write each resource. + OutputStorage = zipHandler, + // Set the target format to "zip". This tells the library to treat the ZIP as the container. + // The actual file name is irrelevant because we will retrieve the bytes ourselves. + OutputFileName = "output.zip" +}; + +// Save the document. No physical file is written yet. +document.Save(saveOptions); + +// Retrieve the completed ZIP as a byte array. +byte[] zipBytes = zipHandler.GetZipBytes(); + +// Write the ZIP to disk (or return it from a web API). +File.WriteAllBytes(@"C:\Temp\output.zip", zipBytes); + +Console.WriteLine("HTML and its resources have been saved to output.zip"); +``` + +### Kết quả mong đợi + +- `output.zip` chứa: + - `index.html` (tệp HTML chính) + - `images/logo.png` (hình ảnh được tham chiếu trong markup) + - Bất kỳ tệp CSS hoặc phông chữ bổ sung nào được Aspose.HTML tự động phát hiện + +Khi bạn giải nén tệp và mở `index.html` trong trình duyệt, hình ảnh sẽ hiển thị đúng—chứng minh **cách lưu HTML có hình ảnh** bên trong một ZIP. + +## Bước 5: Xác minh tệp và khắc phục các vấn đề thường gặp + +### Kịch bản kiểm tra nhanh + +```csharp +using (var zip = ZipFile.OpenRead(@"C:\Temp\output.zip")) +{ + Console.WriteLine("Archive contains the following entries:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName}"); +} +``` + +Chạy script sẽ liệt kê `index.html` và `images/logo.png`. Nếu một tài nguyên mong đợi bị thiếu: + +- **Kiểm tra URL hình ảnh**: Nó phải có thể truy cập được từ tài liệu HTML. Đường dẫn tương đối hoạt động tốt nhất. +- **Đảm bảo loại tài nguyên được hỗ trợ**: Aspose.HTML xử lý các định dạng web phổ biến (PNG, JPEG, GIF, CSS, JS). Các định dạng không thường gặp có thể cần thêm thủ công. +- **Xác nhận `HandleResource` được gọi**: Thêm `Console.WriteLine(resource.Uri)` trong `HandleResource` để gỡ lỗi. + +## Bước 6: Các biến thể nâng cao + +### 6.1 Lưu trực tiếp vào tệp mà không cần mảng byte trung gian + +Nếu việc sử dụng bộ nhớ là mối quan tâm đối với tài liệu rất lớn, thay thế `MemoryStream` bằng `FileStream`: + +```csharp +class FileZipHandler : ResourceHandler, IDisposable +{ + private readonly ZipArchive _zipArchive; + private readonly FileStream _fileStream; + + public FileZipHandler(string zipPath) + { + _fileStream = new FileStream(zipPath, FileMode.Create); + _zipArchive = new ZipArchive(_fileStream, ZipArchiveMode.Create); + } + + public override Stream HandleResource(Resource resource) + { + string entryName = resource.Uri.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); + var entry = _zipArchive.CreateEntry(entryName, CompressionLevel.Optimal); + return entry.Open(); + } + + public void Dispose() + { + _zipArchive?.Dispose(); + _fileStream?.Dispose(); + } +} +``` + +Sau đó sử dụng như sau: + +```csharp +using var handler = new FileZipHandler(@"C:\Temp\output.zip"); +document.Save(new SaveOptions { OutputStorage = handler }); +``` + +### 6.2 Tùy chỉnh tên mục + +Nếu bạn muốn cấu trúc phẳng (tất cả tệp ở gốc), điều chỉnh `entryName`: + +```csharp +string entryName = Path.GetFileName(resource.Uri); +``` + +### 6.3 Thêm tệp manifest + +Đôi khi các công cụ downstream mong đợi một `manifest.json`. Bạn có thể thêm nó sau khi lưu chính: + +```csharp +using (var manifest = zipHandler._zipArchive.CreateEntry("manifest.json")) +using (var writer = new StreamWriter(manifest.Open())) +{ + writer.Write("{ \"description\": \"HTML archive generated by Aspose.HTML\" }"); +} +``` + +## Những cạm bẫy thường gặp và cách tránh + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| Hình ảnh bị hỏng sau khi giải nén | Đường dẫn hình ảnh trong HTML không khớp với tên mục trong ZIP. | Giữ nguyên đường dẫn tương đối gốc khi tạo `ZipArchiveEntry`. | +| Hình ảnh lớn gây lỗi hết bộ nhớ | Sử dụng `MemoryStream` cho các tệp rất lớn có thể vượt quá giới hạn bộ nhớ của tiến trình. | Chuyển sang trình xử lý dựa trên `FileStream` (xem 6.1). | +| URL CSS bị thiếu | Các tệp CSS bên ngoài được tham chiếu qua `@import` không được tự động phát hiện. | Thêm thủ công các tệp CSS vào ZIP hoặc nhúng chúng inline trước khi lưu. | +| Ký tự Unicode bị lỗi | Mã hoá mặc định có thể khác nhau giữa nguồn HTML và stream. | Đảm bảo chuỗi HTML là UTF‑8; Aspose.HTML tôn trọng charset của tài liệu. | + +## Ví dụ đầy đủ hoạt động (sẵn sàng sao chép‑dán) + + + +## Bạn nên học gì tiếp theo? + +Những hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã đầy đủ hoạt động với giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [cách sử dụng handler trong Aspose.HTML – Load HTML, Save as ZIP](/html/english/net/html-extensions-and-conversions/how-to-use-handler-in-aspose-html-load-html-save-as-zip/) +- [Cách lưu HTML trong C# – Custom Resource Handlers & ZIP](/html/english/net/working-with-html-documents/how-to-save-html-in-c-custom-resource-handlers-zip/) +- [Render HTML sang PNG và lưu vào ZIP với C# – Hướng dẫn đầy đủ](/html/english/net/rendering-html-documents/render-html-to-png-and-save-to-zip-with-c-complete-guide/) + +{{< /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 e85efdbe86..6716ba5a42 100644 --- a/html/vietnamese/net/rendering-html-documents/_index.md +++ b/html/vietnamese/net/rendering-html-documents/_index.md @@ -66,7 +66,7 @@ Hướng dẫn chi tiết cách render HTML thành PNG bằng Aspose.HTML cho .N Học cách chuyển đổi HTML sang PNG bằng C# với Aspose.HTML, bao gồm các bước chi tiết và mẹo thực tiễn. ### [Cách sử dụng Aspose để render HTML thành PNG – Hướng dẫn từng bước](./how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) 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. -### [Cách render HTML thành PNG với Aspose – Hướng dẫn toàn diện](./how-to-render-html-to-png-complete-guide/) +### [Cách render HTML thành PNG – Hướng dẫn Toàn Diện với Aspose](./how-to-render-html-to-png-complete-guide/) 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. ### [Cách render HTML thành PNG với Aspose – Hướng dẫn toàn diện](./how-to-render-html-to-png-with-aspose-complete-guide/) @@ -79,6 +79,8 @@ Tìm hiểu cách chuyển đổi HTML sang PNG bằng Aspose.HTML cho .NET vớ Học cách tạo tài liệu HTML bằng C# và render thành PNG với phông chữ in đậm, nghiêng sử dụng Aspose.HTML cho .NET. ### [Cách sử dụng Aspose để render HTML thành PNG trong C#](./how-to-use-aspose-to-render-html-to-png-in-c/) Hướng dẫn chi tiết cách sử dụng Aspose.HTML để chuyển đổi tài liệu HTML thành PNG bằng C#. +### [Cách sử dụng Aspose để render HTML thành ảnh PNG trong C#](./how-to-use-aspose-to-render-html-to-png-image-in-c/) +Học cách chuyển đổi HTML sang ảnh PNG trong C# bằng Aspose.HTML, với hướng dẫn chi tiết các bước thực hiện. ### [Cách render HTML thành hình ảnh với C# – Hướng dẫn toàn diện](./how-to-render-html-to-an-image-with-c-complete-guide/) Hướng dẫn chi tiết cách chuyển đổi HTML thành hình ảnh bằng C# sử dụng Aspose.HTML, bao gồm các bước và ví dụ thực tế. ### [Cách render HTML thành PNG trong C# – Hướng dẫn từng bước](./how-to-render-html-to-png-in-c-step-by-step-guide/) diff --git a/html/vietnamese/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md b/html/vietnamese/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md new file mode 100644 index 0000000000..518915400b --- /dev/null +++ b/html/vietnamese/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-10-02 +description: Cách sử dụng Aspose để chuyển đổi HTML sang ảnh PNG nhanh chóng – học + cách chuyển HTML sang PNG với tính năng chống răng cưa và gợi ý văn bản. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to use aspose +- render html to image +- convert html to png +- render html as image +- save html as png +language: vi +lastmod: 2026-10-02 +og_description: Cách sử dụng Aspose để chuyển đổi HTML sang ảnh PNG. Theo dõi hướng + dẫn đầy đủ này để chuyển đổi HTML sang PNG với việc render chất lượng cao trong + C#. +og_image_alt: Screenshot showing how to use Aspose to render HTML to PNG image +og_title: Cách sử dụng Aspose để chuyển đổi HTML thành ảnh PNG – hướng dẫn từng bước +schemas: +- author: Aspose + dateModified: '2026-10-02' + description: How to use Aspose to render HTML to PNG image quickly – learn to convert + HTML to PNG with anti‑aliasing and text hinting. + headline: How to use Aspose to render HTML to PNG image in C# + type: TechArticle +- questions: + - answer: Yes. Aspose.HTML is fully cross‑platform. Ensure the required fonts are + installed, and the output directory is writable. + question: Does this work with .NET Core on macOS? + - answer: Replace `RenderToImage("output.png", imgOptions)` with `RenderToImage("output.jpg", + imgOptions)`. You can also set `imgOptions.ImageFormat = ImageFormat.Jpeg` for + finer control over quality. + question: Can I render to JPEG instead of PNG? + - answer: 'Load the CSS content into a string and concatenate it, or reference a + remote stylesheet in the `` tag. Aspose resolves `` tags automatically + when the document is loaded from a URL. ## Conclusion You now know **how to + use Aspose** to **render HTML to PNG** (or any other raster format) wit' + question: How do I embed external CSS files? + type: FAQPage +tags: +- Aspose +- HTML rendering +- C# +- PNG conversion +- Image processing +title: Cách sử dụng Aspose để chuyển đổi HTML sang ảnh PNG trong C# +url: /vi/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách sử dụng Aspose để render HTML thành ảnh PNG trong C# + +**How to use Aspose to render HTML to PNG image** là một yêu cầu phổ biến khi bạn cần bản xem trước bitmap của một trang web, một hình thu nhỏ email, hoặc một ảnh chụp thân thiện với PDF. Hướng dẫn này cho bạn một giải pháp hoàn chỉnh, sẵn sàng chạy mà **render html to image** với anti‑aliasing và text hinting, vì vậy kết quả trông sắc nét trên mọi nền tảng. + +Bạn sẽ học cách **convert HTML to PNG**, cấu hình các tùy chọn render, và xử lý các vấn đề thường gặp như render font trên Linux và quyền truy cập hệ thống tệp. Không cần công cụ bên ngoài—chỉ cần thư viện Aspose.HTML cho .NET và một vài dòng C#. + +## Yêu cầu trước + +* .NET 6.0 SDK hoặc phiên bản mới hơn đã được cài đặt +* Visual Studio 2022 (hoặc bất kỳ IDE C# nào) +* Tham chiếu NuGet tới **Aspose.HTML** (`Install-Package Aspose.HTML`) +* Kiến thức cơ bản về cú pháp C# + +Các yêu cầu này nhẹ nhàng; hướng dẫn hoạt động trên Windows, Linux và macOS vì Aspose.HTML là đa nền tảng. + +## Bước 1: Cài đặt Aspose.HTML và tạo một dự án console mới + +Mở terminal hoặc Package Manager Console và chạy: + +```bash +dotnet new console -n HtmlToPngDemo +cd HtmlToPngDemo +dotnet add package Aspose.HTML +``` + +Tạo một dự án riêng biệt giúp cô lập các phụ thuộc và dễ dàng chạy mẫu với `dotnet run`. + +## Bước 2: Thiết lập các tùy chọn render ảnh (anti‑aliasing và text hinting) + +Antialiasing làm mịn các cạnh, trong khi text hinting cải thiện độ rõ của glyph, đặc biệt trên Linux nơi rasterization font khác với Windows. Lớp `ImageRenderingOptions` cho phép bạn bật cả hai tính năng: + +```csharp +using Aspose.Html.Rendering.Image; + +// Configure rendering to produce a high‑quality PNG +var imgOptions = new ImageRenderingOptions +{ + // Improves visual quality on Linux and high‑DPI displays + UseAntialiasing = true, + + // Makes text appear sharper by applying hinting algorithms + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +**Tại sao điều này quan trọng:** Nếu không có antialiasing, các đường chéo và đường cong sẽ trông răng cưa. Nếu không có text hinting, các kích thước font nhỏ có thể bị mờ, điều này dễ nhận thấy khi bạn **save html as png** cho các hình thu nhỏ. + +## Bước 3: Định nghĩa CSS cho font đồng nhất và kiểu tiêu đề + +Nhúng CSS trực tiếp vào HTML đảm bảo hình ảnh render khớp với mong đợi thiết kế của bạn. Trong ví dụ này chúng tôi đặt font cơ bản và làm cho `

` in nghiêng: + +```csharp +var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; +``` + +Bạn có thể mở rộng stylesheet bằng màu sắc, lề, hoặc media queries. CSS được chèn vào thẻ ` +

Sample

+"; + +// Create an HTMLDocument instance from the string +var doc = new HTMLDocument(html); +``` + +**Mẹo:** Nếu bạn cần **render html as image** từ một trang từ xa, thay thế constructor chuỗi bằng `new HTMLDocument("https://example.com")`. Aspose sẽ tải trang, giải quyết các tài nguyên và render bố cục cuối cùng. + +## Bước 5: Render tài liệu thành tệp PNG + +Bây giờ chúng ta gọi `RenderToImage`, truyền đường dẫn đầu ra và các tùy chọn chúng ta đã cấu hình trước đó: + +```csharp +// Choose an output directory that exists on the host machine +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + +// Perform the rendering +doc.RenderToImage(outputPath, imgOptions); +Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); +``` + +Tệp `output.png` được tạo sẽ chứa một bản render sắc nét của phần tử `

` với kiểu in nghiêng, nhờ các cài đặt anti‑aliasing và hinting. + +## Danh sách chương trình đầy đủ + +Sao chép đoạn mã sau vào `Program.cs`. Nó sẽ biên dịch và chạy ngay: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + // ---------- Step 2: Rendering options ---------- + var imgOptions = new ImageRenderingOptions + { + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } + }; + + // ---------- Step 3: CSS definition ---------- + var css = @" + body { font-family: 'Arial'; font-style: normal; font-weight: normal; } + h1 { font-style: italic; }"; + + // ---------- Step 4: Load HTML ---------- + string html = $@" + + +

Sample

+ "; + + var doc = new HTMLDocument(html); + + // ---------- Step 5: Render to PNG ---------- + string outputPath = Path.Combine(Environment.CurrentDirectory, "output.png"); + doc.RenderToImage(outputPath, imgOptions); + + Console.WriteLine($"HTML successfully rendered to PNG at: {outputPath}"); + } +} +``` + +### Kết quả mong đợi + +Chạy chương trình sẽ tạo `output.png` trong thư mục dự án. Hình ảnh hiển thị từ **Sample** bằng font Arial in nghiêng, được render với các cạnh mượt và văn bản rõ ràng. Mở tệp bằng bất kỳ trình xem ảnh nào để kiểm tra chất lượng. + +## Bước 6: Các biến thể phổ biến và xử lý trường hợp đặc biệt + +| Situation | What to adjust | Reason | +|-----------|----------------|--------| +| **Các trang HTML lớn** | Đặt `ImageRenderingOptions.Width` / `Height` hoặc sử dụng `PageSize` để kiểm soát kích thước đầu ra | Ngăn ngừa việc tiêu tốn bộ nhớ và đảm bảo PNG phù hợp với giao diện người dùng của bạn | +| **Font Linux thiếu** | Cài đặt các font cần thiết trên máy chủ (`apt-get install fonts‑arial` hoặc sử dụng tệp font tùy chỉnh) và chỉ định cho Aspose qua `FontSettings` | Nếu không có font, Aspose sẽ dùng font chung, làm thay đổi giao diện | +| **Cần nền trong suốt** | Đặt `imgOptions.BackgroundColor = Color.Transparent` | Hữu ích khi nhúng PNG vào các đồ họa khác | +| **Chuyển đổi hàng loạt** | Lặp qua danh sách các chuỗi HTML hoặc đường dẫn tệp, tái sử dụng cùng một đối tượng `ImageRenderingOptions` | Cải thiện hiệu năng và giữ các cài đặt render nhất quán | + +## Mẹo chuyên nghiệp: lưu cache các tùy chọn render + +Tạo một đối tượng `ImageRenderingOptions` mới cho mỗi lần chuyển đổi sẽ tăng chi phí. Khai báo một thể hiện tĩnh nếu bạn xử lý nhiều đoạn HTML trong một dịch vụ: + +```csharp +private static readonly ImageRenderingOptions SharedOptions = new() +{ + UseAntialiasing = true, + TextOptions = new TextOptions { UseHinting = true } +}; +``` + +Tái sử dụng `SharedOptions` trong các lần gọi để giảm mức sử dụng CPU. + +## Câu hỏi thường gặp + +**Q: Điều này có hoạt động với .NET Core trên macOS không?** +A: Có. Aspose.HTML hoàn toàn đa nền tảng. Đảm bảo các font cần thiết đã được cài đặt và thư mục đầu ra có quyền ghi. + +**Q: Tôi có thể render thành JPEG thay vì PNG không?** +A: Thay thế `RenderToImage("output.png", imgOptions)` bằng `RenderToImage("output.jpg", imgOptions)`. Bạn cũng có thể đặt `imgOptions.ImageFormat = ImageFormat.Jpeg` để kiểm soát chi tiết hơn về chất lượng. + +**Q: Làm thế nào để nhúng các tệp CSS bên ngoài?** +A: Tải nội dung CSS vào một chuỗi và nối lại, hoặc tham chiếu một stylesheet từ xa trong thẻ ``. Aspose tự động giải quyết các thẻ `` khi tài liệu được tải từ URL. + +## Kết luận + +Bây giờ bạn đã biết **cách sử dụng Aspose** để **render HTML thành PNG** (hoặc bất kỳ định dạng raster nào khác) với các cài đặt chất lượng cao. Hướng dẫn đã đề cập đến việc cài đặt Aspose.HTML, cấu hình anti‑aliasing và text hinting, chèn CSS, tải HTML, và cuối cùng **lưu HTML dưới dạng PNG**. Bằng cách làm theo các bước, bạn có thể đáng tin cậy **chuyển đổi HTML sang PNG** trong bất kỳ ứng dụng .NET nào, dù chạy trên Windows, Linux hay macOS. + +### Các bước tiếp theo + +* Khám phá các định dạng đầu ra khác như **render html as image** JPEG hoặc BMP bằng cách thay đổi phần mở rộng tệp. +* Kết hợp cách tiếp cận này với **Aspose.PDF** để nhúng PNG vào báo cáo PDF. +* Thử nghiệm với `ImageRenderingOptions.DpiX` và `DpiY` để tạo các hình thu nhỏ độ phân giải cao. + +Bạn có thể tự do điều chỉnh mã cho việc xử lý hàng loạt, tạo HTML động, hoặc tích hợp vào dịch vụ web trả về các bản xem trước PNG theo yêu cầu. Chúc bạn render vui vẻ! + +## Bạn nên học gì tiếp theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh với giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [How to Use Aspose to Render HTML to PNG – Step‑by‑Step Guide](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/) +- [How to Render HTML to PNG with Aspose – Complete Guide](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/) +- [html to image tutorial – Render HTML to PNG with Aspose.HTML in C#](/html/english/net/generate-jpg-and-png-images/html-to-image-tutorial-render-html-to-png-with-aspose-html-i/) + +{{< /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