From d2317cd0aafa18829f3d1a81943baa64824f308c Mon Sep 17 00:00:00 2001 From: Muhammad Adil Date: Sun, 9 Aug 2026 22:09:56 +0000 Subject: [PATCH] Add 1 html net tutorials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Categories: generate-jpg-and-png-images, html-extensions-and-conversions Source: AI Search API Tutorials: - Save HTML to ZIP with Aspose.HTML – complete guide Auto-generated by Professionalize.Tutorials Agent --- .../html-extensions-and-conversions/_index.md | 4 +- .../_index.md | 251 ++++++++++++++ .../html-extensions-and-conversions/_index.md | 3 + .../_index.md | 265 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 267 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 1 + .../_index.md | 267 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 319 ++++++++++++++++++ .../og-image.png | Bin 0 -> 47478 bytes .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 268 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 267 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 4 +- .../_index.md | 267 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 8 +- .../_index.md | 267 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 4 +- .../_index.md | 265 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 1 + .../_index.md | 267 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 1 + .../_index.md | 318 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 267 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 4 + .../_index.md | 287 ++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 250 ++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 267 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 3 +- .../_index.md | 267 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 267 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 267 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 318 +++++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 266 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 2 + .../_index.md | 267 +++++++++++++++ .../html-extensions-and-conversions/_index.md | 6 +- .../_index.md | 267 +++++++++++++++ 47 files changed, 6328 insertions(+), 13 deletions(-) create mode 100644 html/arabic/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/chinese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/czech/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/dutch/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/english/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/english/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/og-image.png create mode 100644 html/french/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/german/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/greek/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/hindi/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/hongkong/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/hungarian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/indonesian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/italian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/japanese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/korean/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/polish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/portuguese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/russian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/spanish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/swedish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/thai/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/turkish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md create mode 100644 html/vietnamese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md diff --git a/html/arabic/net/html-extensions-and-conversions/_index.md b/html/arabic/net/html-extensions-and-conversions/_index.md index 980eb70131..c2d0f955d2 100644 --- a/html/arabic/net/html-extensions-and-conversions/_index.md +++ b/html/arabic/net/html-extensions-and-conversions/_index.md @@ -70,9 +70,11 @@ url: /ar/net/html-extensions-and-conversions/ ### [كيفية ضغط HTML في C# – حفظ HTML إلى ملف Zip](./how-to-zip-html-in-c-save-html-to-zip/) تعلم كيفية ضغط ملفات HTML وحفظها كملف Zip باستخدام C# ومكتبة Aspose.HTML. ### [حفظ HTML كملف ZIP – دليل C# كامل](./save-html-as-zip-complete-c-tutorial/) -تعلم كيفية حفظ مستند HTML كملف ZIP باستخدام Aspose.HTML في C# خطوة بخطوة. +تعلم كيفية حفظ مستند HTML كملف ZIP في C# باستخدام Aspose.HTML. ### [حفظ HTML إلى ZIP في C# – مثال كامل في الذاكرة](./save-html-to-zip-in-c-complete-in-memory-example/) تعلم كيفية حفظ مستند HTML كملف ZIP في الذاكرة باستخدام C# ومكتبة Aspose.HTML. +### [حفظ HTML إلى ZIP باستخدام Aspose.HTML – دليل كامل](./save-html-to-zip-with-aspose-html-complete-guide/) +دليل شامل لحفظ ملفات HTML كملفات ZIP باستخدام Aspose.HTML في .NET. ## خاتمة diff --git a/html/arabic/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/arabic/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..9152856a95 --- /dev/null +++ b/html/arabic/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,251 @@ +--- +category: general +date: 2026-08-09 +description: احفظ HTML كملف ZIP باستخدام Aspose.HTML ومعالج موارد مخصص. تعلم كيفية + تحويل HTML إلى ZIP، حفظ HTML كملف ZIP، وإنشاء ZIP من HTML في بضع خطوات. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: ar +lastmod: 2026-08-09 +og_description: احفظ HTML إلى ZIP باستخدام Aspose.HTML ومعالج موارد مخصص. يوضح هذا + الدرس كيفية تحويل HTML إلى ZIP، حفظ HTML كملف ZIP، وإنشاء ملف ZIP من HTML بفعالية. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: حفظ HTML إلى ZIP باستخدام Aspose.HTML – دليل خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: حفظ HTML إلى ZIP باستخدام Aspose.HTML – دليل كامل +url: /ar/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# حفظ HTML إلى ZIP باستخدام Aspose.HTML – دليل كامل + +إذا كنت بحاجة إلى **save HTML to ZIP** بسرعة، يوضح لك هذا الدرس بالضبط كيفية القيام بذلك باستخدام Aspose.HTML لـ .NET. بحلول نهاية الجملتين الأوليين ستفهم كيف يتيح لك **custom resource handler** التحكم في مكان وضع كل مورد، مما يسمح لك **convert HTML to ZIP**، **save HTML as ZIP**، أو **create ZIP from HTML** ببضع أسطر من الشيفرة فقط. + +سنستعرض سيناريو واقعي: لديك مقطع HTML (أو صفحة كاملة) وتحتاج إلى تجميعه مع صوره، وملفات CSS، وJavaScript في ملف ZIP واحد يمكن إرساله عبر الشبكة أو تخزينه للاستخدام لاحقًا. لا أدوات خارجية، لا نسخ ملفات يدويًا—فقط C# صافي وAspose.HTML. + +سوف تتعلم: + +* كيفية تنفيذ `ResourceHandler` يكتب كل مورد في `MemoryStream` (أو أي تدفق تختاره). +* كيفية تحميل مستند HTML من سلسلة نصية أو ملف. +* كيفية تكوين `HTMLSaveOptions` لاستخدام المعالج الخاص بك. +* كيفية التحقق من أن الأرشيف ZIP الناتج يحتوي على الملفات المتوقعة. + +## المتطلبات المسبقة + +* .NET 6.0 أو أحدث (الكود يعمل أيضًا مع .NET Framework 4.6+). +* ترخيص صالح لـ Aspose.HTML for .NET (الإصدار التجريبي المجاني يكفي للتطوير). +* إلمام أساسي بتدفقات C# وعمليات I/O للملفات. + +--- + +## الخطوة 1: إنشاء معالج موارد مخصص + +قلب الحل هو فئة ترث من `Aspose.Html.ResourceHandler`. +Aspose.HTML يستدعي `HandleResource` لكل أصل خارجي يصادفه (صور، CSS، خطوط، إلخ). بإرجاع `Stream` تقرر بالضبط كيف يُخزن الأصل. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**لماذا هذا مهم** – بدون معالج مخصص، يقوم Aspose.HTML بكتابة الموارد إلى نظام الملفات في مجلد مؤقت، ثم عليك نقلها إلى ZIP يدويًا. المعالج يمنحك تحكمًا كاملاً، يلغي الملفات الوسيطة، ويعمل بنفس الفاعلية مع الملفات الكبيرة عندما تستبدل `MemoryStream` بـ `FileStream`. + +## الخطوة 2: تحميل مستند HTML + +يمكنك تحميل HTML من سلسلة نصية، ملف، أو أي `Stream`. المثال أدناه يستخدم سلسلة داخلية للسهولة، لكن نفس الشيفرة تعمل مع `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**نصيحة** – إذا كان HTML الخاص بك يشير إلى ملفات محلية، تأكد من أن خاصية `BaseUrl` في `HTMLDocument` تشير إلى المجلد الذي يحتوي على تلك الأصول. هذا يساعد المعالج على حل عناوين URI النسبية بشكل صحيح. + +## الخطوة 3: تكوين خيارات الحفظ لاستخدام المعالج المخصص + +`HTMLSaveOptions` يتيح لك تحديد صيغة الإخراج وآلية التخزين. ضبط `OutputStorage` على نسخة من `MyHandler` يخبر Aspose.HTML باستدعاء معالجك لكل مورد خارجي. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**لماذا نحدد `FileName`؟** – عند الحفظ كـ ZIP، ينشئ Aspose.HTML حاوية تشمل ملف HTML الأساسي (المسمى `index.html` افتراضيًا) بالإضافة إلى جميع الموارد. تسمية الإدخال صراحة تجعل بنية ZIP متوقعة، وهو مفيد للمعالجة اللاحقة. + +## الخطوة 4: حفظ المستند في أرشيف ZIP + +الآن ما عليك سوى استدعاء `doc.Save`، مع تمرير مسار الهدف والخيارات المكوَّنة. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### النتيجة المتوقعة + +بعد انتهاء البرنامج، يحتوي `demo.zip` على: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +يمكنك فتح ZIP بأي عارض أرشيف للتحقق من أن ملف HTML يشير إلى الصورة باستخدام المسار النسبي `assets/logo.png`. فتح `index.html` في المتصفح سيعرض الصفحة كما كانت قبل التعبئة. + +## التعامل مع الموارد الكبيرة ومراعاة الذاكرة + +المثال يستخدم `MemoryStream` لكل مورد، وهو مناسب للصور الصغيرة أو ملفات CSS. بالنسبة للأصول الأكبر (مثل الصور عالية الدقة أو ملفات الفيديو) يجب التحول إلى `FileStream` لتجنب استهلاك الذاكرة الزائد: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +بعد انتهاء `doc.Save`، يمكنك حذف الملفات المؤقتة بتكرار `resource.CustomData["TempPath"]`. هذا النمط يضمن أن **save html as zip** يعمل بثبات حتى مع أصول بحجم ميغابايت. + +## إضافة ملفات إضافية إلى ZIP (مثل README) + +أحيانًا تريد تضمين وثائق إضافية إلى جانب HTML. يمكنك تحقيق ذلك باستخدام `ZipArchive` مباشرة بعد أن ينشئ Aspose.HTML الأرشيف الأولي. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +الآن يحتوي الأرشيف أيضًا على `README.txt`، موضحًا كيفية **create zip from html** مع إثرائه بمحتوى مخصص. + +## المشكلات الشائعة وكيفية تجنبها + +| المشكلة | الأعراض | الحل | +|---------|----------|------| +| الموارد غير موجودة في ZIP | يظهر فقط `index.html`؛ الصور مفقودة. | تأكد من ضبط `OutputStorage` على نسخة من `MyHandler`. تحقق من أن `HandleResource` تُعيد تدفقًا قابلًا للكتابة. | +| روابط الصور مكسورة | المتصفح يظهر “صورة مفقودة” بعد استخراج ZIP. | يجب أن يتطابق `CustomData["ZipEntryName"]` مع المسار المستخدم في HTML. استخدم مجلدًا أساسيًا ثابتًا (`assets/`) في المعالج. | +| استثناء نفاد الذاكرة للملفات الكبيرة | يتعطل التطبيق عند معالجة فيديو بحجم 50 MB. | انتقل من `MemoryStream` إلى `FileStream` في `HandleResource`. نظّف الملفات المؤقتة بعد الحفظ. | +| ملف ZIP مقفل بعد الإنشاء | الفترات اللاحقة تفشل برسالة “الملف قيد الاستخدام”. | حرّر `HTMLDocument` (`doc.Dispose()`) وأي كائنات `FileStream` قبل إعادة فتح ZIP. | + +## مثال كامل قابل للتنفيذ + +فيما يلي برنامج وحدة تحكم بملف واحد يمكنك نسخه، لصقه، وتشغيله. يتضمن جميع الأجزاء التي نوقشت أعلاه. + + + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة شيفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Save HTML as ZIP – Complete C# Tutorial](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 a6c24babf2..9ca2065e0d 100644 --- a/html/chinese/net/html-extensions-and-conversions/_index.md +++ b/html/chinese/net/html-extensions-and-conversions/_index.md @@ -75,6 +75,9 @@ Aspose.HTML for .NET 不仅仅是一个库;它是 Web 开发领域的变革者 ### [在 C# 中将 HTML 保存为 ZIP – 完整内存示例](./save-html-to-zip-in-c-complete-in-memory-example/) 演示如何使用 Aspose.HTML for .NET 在 C# 中将 HTML 内容压缩为 ZIP 文件,完整的内存操作示例。 +### [使用 Aspose.HTML 将 HTML 保存为 ZIP – 完整指南](./save-html-to-zip-with-aspose-html-complete-guide/) +使用 Aspose.HTML for .NET 完整指南,展示如何将 HTML 打包并保存为 ZIP 文件。 + ## 结论 总之,HTML 扩展和转换是现代 Web 开发的基本要素。Aspose.HTML for .NET 简化了该过程,使各个级别的开发人员都可以使用它。通过学习我们的教程,您将成为一名拥有广泛技能的熟练 Web 开发人员。 diff --git a/html/chinese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/chinese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..e61825dcd7 --- /dev/null +++ b/html/chinese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2026-08-09 +description: 使用 Aspose.HTML 和自定义资源处理程序将 HTML 保存为 ZIP。了解如何将 HTML 转换为 ZIP、将 HTML 保存为 + ZIP,以及在几步操作中从 HTML 创建 ZIP。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: zh +lastmod: 2026-08-09 +og_description: 使用 Aspose.HTML 和自定义资源处理程序将 HTML 保存为 ZIP。本教程展示了如何将 HTML 转换为 ZIP、将 HTML + 保存为 ZIP,以及如何高效地从 HTML 创建 ZIP。 +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: 使用 Aspose.HTML 将 HTML 保存为 ZIP – 逐步指南 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: 使用 Aspose.HTML 将 HTML 保存为 ZIP 的完整指南 +url: /zh/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< 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 for .NET 完成此操作。阅读完前两句话后,您将了解 **自定义资源处理程序** 如何让您控制每个资源的存放位置,从而仅用几行代码就能 **将 HTML 转换为 ZIP**、**将 HTML 保存为 ZIP**,或 **从 HTML 创建 ZIP**。 + +我们将通过一个真实场景进行演示:您拥有一个 HTML 片段(或完整页面),需要将其连同图片、CSS 和 JavaScript 打包成一个 ZIP 文件,以便在网络上传输或后续存储。无需外部工具,无需手动复制文件——仅使用纯 C# 和 Aspose.HTML。 + +您将学习: + +* 如何实现一个 `ResourceHandler`,将每个资源写入 `MemoryStream`(或您选择的任何流)。 +* 如何从字符串或文件加载 HTML 文档。 +* 如何配置 `HTMLSaveOptions` 以使用您的处理程序。 +* 如何验证生成的 ZIP 包含预期的文件。 + +## 前置条件 + +* .NET 6.0 或更高版本(代码同样适用于 .NET Framework 4.6+)。 +* 有效的 Aspose.HTML for .NET 许可证(免费试用版可用于开发)。 +* 对 C# 流和文件 I/O 有基本了解。 + +--- + +## 步骤 1:创建自定义资源处理程序 + +解决方案的核心是一个继承自 `Aspose.Html.ResourceHandler` 的类。 +Aspose.HTML 会为它遇到的每个外部资源(图片、CSS、字体等)调用 `HandleResource`。通过返回一个 `Stream`,您可以精确决定资源的存储方式。 + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**为什么这很重要** – 如果没有自定义处理程序,Aspose.HTML 会将资源写入临时文件夹,然后您必须手动将其移动到 ZIP 中。使用处理程序可以完全控制资源存储,消除中间文件,并且在处理大二进制文件时,只需将 `MemoryStream` 替换为 `FileStream` 即可。 + +--- + +## 步骤 2:加载 HTML 文档 + +您可以从字符串、文件或任意 `Stream` 加载 HTML。下面的示例为简化起见使用内联字符串,但相同代码同样适用于 `new HTMLDocument("path/to/file.html")`。 + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**提示** – 如果您的 HTML 引用了本地文件,请确保 `HTMLDocument` 的 `BaseUrl` 属性指向包含这些资源的文件夹。这样处理程序才能正确解析相对 URI。 + +--- + +## 步骤 3:配置保存选项以使用自定义处理程序 + +`HTMLSaveOptions` 允许您指定输出格式和存储机制。将 `OutputStorage` 设置为 `MyHandler` 的实例,即可让 Aspose.HTML 为每个外部资源调用您的处理程序。 + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**为什么要设置 `FileName`?** – 保存为 ZIP 时,Aspose.HTML 会创建一个容器,其中包含主 HTML 文件(默认名为 `index.html`)以及所有资源。显式命名条目可以让 ZIP 结构可预测,便于后续处理。 + +--- + +## 步骤 4:将文档保存为 ZIP 包 + +现在只需调用 `doc.Save`,传入目标路径和已配置的选项。 + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### 预期结果 + +程序执行完毕后,`demo.zip` 包含: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +您可以使用任意压缩文件查看器打开 ZIP,验证 HTML 文件使用相对路径 `assets/logo.png` 引用图片。将 `index.html` 在浏览器中打开,即可看到与打包前完全相同的页面效果。 + +--- + +## 处理大资源与内存考虑 + +示例对每个资源使用 `MemoryStream`,这对小图片或 CSS 文件非常适用。对于更大的资产(例如高分辨率照片或视频文件),应改用 `FileStream` 以避免内存占用过高: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +`doc.Save` 完成后,您可以遍历 `resource.CustomData["TempPath"]` 删除临时文件。此模式可确保 **save html as zip** 在处理兆字节级资产时仍然可靠。 + +--- + +## 向 ZIP 中添加额外文件(例如 README) + +有时您需要在 HTML 之外捆绑额外的文档。可以在 Aspose.HTML 创建初始归档后,直接使用 `ZipArchive` 添加文件。 + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +现在归档中还包含 `README.txt`,演示了如何在 **create zip from html** 的同时加入自定义内容。 + +--- + +## 常见陷阱及规避方法 + +| 问题 | 症状 | 解决方案 | +|------|------|----------| +| 资源未出现在 ZIP 中 | 只看到 `index.html`,图片缺失。 | 确保 `OutputStorage` 设置为 `MyHandler` 实例。检查 `HandleResource` 是否返回可写流。 | +| 图片链接失效 | 在浏览器中解压后显示 “missing image”。 | `CustomData["ZipEntryName"]` 必须与 HTML 中使用的路径匹配。处理程序中使用统一的基文件夹(如 `assets/`)。 | +| 大文件导致内存不足异常 | 处理 50 MB 视频时程序崩溃。 | 在 `HandleResource` 中将 `MemoryStream` 换成 `FileStream`。保存后清理临时文件。 | +| ZIP 文件创建后被锁定 | 后续运行时报 “file in use”。 | 在重新打开 ZIP 前,先 `Dispose` `HTMLDocument`(`doc.Dispose()`)以及所有 `FileStream` 对象。 | + +--- + +## 完整可运行示例 + +下面是一个单文件控制台程序,您可以直接复制、粘贴并运行。它包含了上述所有要点。 + + + +## 接下来您可以学习什么? + +以下教程涵盖了与本指南密切相关的主题,帮助您进一步掌握 API 功能并探索替代实现方式。 + +- [如何在 C# 中保存 HTML – 使用自定义资源处理程序的完整指南](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [如何在 C# 中压缩 HTML – 将 HTML 保存为 Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [将 HTML 保存为 ZIP – 完整 C# 教程](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 dc8f6f072d..3977f27db5 100644 --- a/html/czech/net/html-extensions-and-conversions/_index.md +++ b/html/czech/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Naučte se vytvořit HTML dokument se stylovaným textem a převést jej do PDF Naučte se, jak uložit HTML soubor jako ZIP archiv pomocí Aspose.HTML pro .NET v kompletním C# tutoriálu. ### [Uložte HTML do ZIP v C# – Kompletní příklad v paměti](./save-html-to-zip-in-c-complete-in-memory-example/) Naučte se, jak uložit HTML soubor do ZIP archivu v paměti pomocí Aspose.HTML pro .NET v C#. +### [Uložte HTML do ZIP pomocí Aspose.HTML – kompletní průvodce](./save-html-to-zip-with-aspose-html-complete-guide/) +Naučte se, jak pomocí Aspose.HTML pro .NET uložit HTML do ZIP archivu – kompletní průvodce. ## Závěr diff --git a/html/czech/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/czech/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..a814892885 --- /dev/null +++ b/html/czech/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Uložte HTML do ZIP pomocí Aspose.HTML a vlastního správce zdrojů. Naučte + se, jak převést HTML do ZIP, uložit HTML jako ZIP a vytvořit ZIP z HTML během několika + kroků. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: cs +lastmod: 2026-08-09 +og_description: Uložte HTML do ZIP pomocí Aspose.HTML a vlastního manipulátoru zdrojů. + Tento tutoriál vám ukáže, jak převést HTML do ZIP, uložit HTML jako ZIP a efektivně + vytvořit ZIP z HTML. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Uložte HTML do ZIP s Aspose.HTML – průvodce krok za krokem +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Uložení HTML do ZIP pomocí Aspose.HTML – kompletní průvodce +url: /cs/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Uložení HTML do ZIP pomocí Aspose.HTML – kompletní průvodce + +Pokud potřebujete **rychle uložit HTML do ZIP**, tento tutoriál vám přesně ukáže, jak to provést pomocí Aspose.HTML pro .NET. Po přečtení prvních dvou vět pochopíte, jak **vlastní manipulátor zdrojů** umožňuje řídit, kam se každý zdroj uloží, a tím **převést HTML do ZIP**, **uložit HTML jako ZIP** nebo **vytvořit ZIP z HTML** pomocí několika řádků kódu. + +Provedeme vás reálným scénářem: máte úryvek HTML (nebo celou stránku) a musíte jej zabalit spolu s obrázky, CSS a JavaScriptem do jediného ZIP souboru, který lze poslat po síti nebo uložit pro pozdější použití. Žádné externí nástroje, žádné ruční kopírování souborů – pouze čistý C# a Aspose.HTML. + +Dozvíte se: + +* Jak implementovat `ResourceHandler`, který zapisuje každý zdroj do `MemoryStream` (nebo libovolného proudu, který zvolíte). +* Jak načíst HTML dokument ze řetězce nebo souboru. +* Jak nakonfigurovat `HTMLSaveOptions` tak, aby používal váš manipulátor. +* Jak ověřit, že výsledný ZIP archiv obsahuje očekávané soubory. + +Předpoklady + +* .NET 6.0 nebo novější (kód funguje také s .NET Framework 4.6+). +* Platná licence Aspose.HTML pro .NET (bezplatná zkušební verze stačí pro vývoj). +* Základní znalost C# proudů a souborového I/O. + +--- + +## Krok 1: Vytvoření vlastního manipulátoru zdrojů + +Jádrem řešení je třída, která dědí z `Aspose.Html.ResourceHandler`. +Aspose.HTML volá `HandleResource` pro každý externí asset, na který narazí (obrázky, CSS, fonty atd.). Vrácením `Stream` určíte přesně, jak bude asset uložen. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Proč je to důležité** – Bez vlastního manipulátoru Aspose.HTML zapisuje zdroje do souborového systému do dočasné složky, kterou pak musíte ručně přesunout do ZIP. Manipulátor vám dává plnou kontrolu, eliminuje mezisoubory a funguje stejně dobře i pro velké binární soubory, pokud `MemoryStream` nahradíte `FileStream`. + +--- + +## Krok 2: Načtení HTML dokumentu + +HTML můžete načíst ze řetězce, souboru nebo libovolného `Stream`. V příkladu níže používáme vložený řetězec pro jednoduchost, ale stejný kód funguje s `new HTMLDocument("cesta/k/souboru.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tip** – Pokud vaše HTML odkazuje na lokální soubory, ujistěte se, že vlastnost `BaseUrl` objektu `HTMLDocument` ukazuje na složku obsahující tyto assety. To pomáhá manipulátoru správně řešit relativní URI. + +--- + +## Krok 3: Konfigurace možností uložení pro použití vlastního manipulátoru + +`HTMLSaveOptions` umožňuje určit výstupní formát a mechanismus ukládání. Nastavením `OutputStorage` na instanci `MyHandler` řeknete Aspose.HTML, aby pro každý externí zdroj volal váš manipulátor. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Proč nastavit `FileName`?** – Při ukládání jako ZIP Aspose.HTML vytvoří kontejner, který zahrnuje hlavní HTML soubor (ve výchozím nastavení `index.html`) plus všechny zdroje. Explicitní pojmenování položky dělá strukturu ZIP předvídatelnou, což je užitečné pro následné zpracování. + +--- + +## Krok 4: Uložení dokumentu do ZIP archivu + +Nyní stačí zavolat `doc.Save`, předat cílovou cestu a nakonfigurované možnosti. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Očekávaný výsledek + +Po dokončení programu `demo.zip` obsahuje: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +ZIP můžete otevřít libovolným archivátorem a ověřit, že HTML soubor odkazuje na obrázek pomocí relativní cesty `assets/logo.png`. Otevřením `index.html` v prohlížeči se stránka zobrazí přesně tak, jak vypadala před zabalením. + +--- + +## Zpracování velkých zdrojů a úvahy o paměti + +Příklad používá `MemoryStream` pro každý zdroj, což funguje dobře pro malé obrázky nebo CSS soubory. Pro větší assety (např. fotografie ve vysokém rozlišení nebo video soubory) byste měli přejít na `FileStream`, abyste předešli nadměrnému využití paměti: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +Po dokončení `doc.Save` můžete dočasné soubory smazat iterací přes `resource.CustomData["TempPath"]`. Tento vzor zajišťuje, že **save html as zip** funguje spolehlivě i při megabajtových assetech. + +--- + +## Přidání dalších souborů do ZIP (např. README) + +Někdy chcete ke HTML přibalit i další dokumentaci. To lze dosáhnout použitím `ZipArchive` přímo po tom, co Aspose.HTML vytvoří počáteční archiv. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Nyní archiv také obsahuje `README.txt`, což demonstruje, jak **create zip from html** obohatit o vlastní obsah. + +--- + +## Časté problémy a jak se jim vyhnout + +| Problém | Příznaky | Řešení | +|-------|----------|-----| +| Zdroje se neobjevují v ZIP | Je jen `index.html`; obrázky chybí. | Ujistěte se, že `OutputStorage` je nastaven na instanci `MyHandler`. Ověřte, že `HandleResource` vrací zapisovatelný proud. | +| Rozbité odkazy na obrázky | Prohlížeč zobrazuje „missing image“ po rozbalení ZIP. | `CustomData["ZipEntryName"]` musí odpovídat cestě použité v HTML. Používejte konzistentní základní složku (`assets/`) v manipulátoru. | +| Výjimka Out‑of‑memory pro velké soubory | Aplikace spadne při zpracování 50 MB videa. | Přepněte z `MemoryStream` na `FileStream` v `HandleResource`. Po uložení vyčistěte dočasné soubory. | +| ZIP soubor uzamčen po vytvoření | Následující běhy selhávají s „file in use“. | Uvolněte (`Dispose`) `HTMLDocument` (`doc.Dispose()`) a všechny `FileStream` objekty před opětovným otevřením ZIP. | + +--- + +## Kompletní, spustitelný příklad + +Níže je jednosouborový konzolový program, který můžete zkopírovat, vložit a spustit. Obsahuje všechny části probírané výše. + + + +## 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ým krok‑za‑krokem vysvětlením, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní přístupy ve vašich projektech. + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Save HTML as ZIP – Complete C# Tutorial](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 fd924a78c2..31cefafe48 100644 --- a/html/dutch/net/html-extensions-and-conversions/_index.md +++ b/html/dutch/net/html-extensions-and-conversions/_index.md @@ -72,6 +72,7 @@ Leer hoe u met Aspose.HTML voor .NET PDF's genereert vanuit HTML met een duideli ### [HTML opslaan als ZIP – Complete C#-tutorial](./save-html-as-zip-complete-c-tutorial/) ### [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#. +### [HTML opslaan als ZIP – volledige gids](./save-html-to-zip-with-aspose-html-complete-guide/) ## Conclusie diff --git a/html/dutch/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/dutch/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..ecb156ad81 --- /dev/null +++ b/html/dutch/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: HTML opslaan in ZIP met Aspose.HTML en een aangepaste resourcehandler. + Leer hoe je HTML naar ZIP converteert, HTML als ZIP opslaat en een ZIP maakt van + HTML in een paar stappen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: nl +lastmod: 2026-08-09 +og_description: Sla HTML op als ZIP met Aspose.HTML en een aangepaste resourcehandler. + Deze tutorial laat zien hoe je HTML naar ZIP converteert, HTML opslaat als ZIP en + efficiënt een ZIP maakt van HTML. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: HTML opslaan naar ZIP met Aspose.HTML – stapsgewijze handleiding +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: HTML opslaan naar ZIP met Aspose.HTML – volledige gids +url: /nl/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML opslaan naar ZIP met Aspose.HTML – volledige gids + +Als je snel **HTML naar ZIP** wilt **opslaan**, laat deze tutorial precies zien hoe je dat doet met Aspose.HTML voor .NET. Aan het einde van de eerste twee zinnen begrijp je hoe een **custom resource handler** je in staat stelt te bepalen waar elke bron terechtkomt, waardoor je **HTML naar ZIP kunt converteren**, **HTML als ZIP kunt opslaan**, of **ZIP vanuit HTML kunt maken** met slechts een paar regels code. + +We lopen een real‑world scenario door: je hebt een HTML‑fragment (of een volledige pagina) en je moet het samen met de afbeeldingen, CSS en JavaScript in één ZIP‑bestand verpakken dat over een netwerk kan worden verzonden of later kan worden opgeslagen. Geen externe tools, geen handmatig bestanden kopiëren—alleen pure C# en Aspose.HTML. + +Je leert: + +* Hoe je een `ResourceHandler` implementeert die elke bron schrijft naar een `MemoryStream` (of elke stream die je kiest). +* Hoe je een HTML‑document laadt vanuit een string of een bestand. +* Hoe je `HTMLSaveOptions` configureert om je handler te gebruiken. +* Hoe je verifieert dat het resulterende ZIP‑archief de verwachte bestanden bevat. + +Prerequisites + +* .NET 6.0 of later (de code werkt ook met .NET Framework 4.6+). +* Een geldige Aspose.HTML for .NET‑licentie (de gratis proefversie werkt voor ontwikkeling). +* Basiskennis van C#‑streams en bestands‑I/O. + +--- + +## Stap 1: Maak een aangepaste resource handler + +Het hart van de oplossing is een klasse die erft van `Aspose.Html.ResourceHandler`. +Aspose.HTML roept `HandleResource` aan voor elk extern asset dat het tegenkomt (afbeeldingen, CSS, lettertypen, enz.). Door een `Stream` terug te geven bepaal je precies hoe het asset wordt opgeslagen. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Waarom dit belangrijk is** – Zonder een aangepaste handler schrijft Aspose.HTML bronnen naar het bestandssysteem in een tijdelijke map, die je vervolgens handmatig naar een ZIP moet verplaatsen. De handler geeft je volledige controle, elimineert tussenliggende bestanden, en werkt even goed voor grote binaries wanneer je `MemoryStream` vervangt door een `FileStream`. + +--- + +## Stap 2: Laad het HTML‑document + +Je kunt HTML laden vanuit een string, een bestand, of elke `Stream`. Het voorbeeld hieronder gebruikt een inline string voor de eenvoud, maar dezelfde code werkt met `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tip** – Als je HTML verwijst naar lokale bestanden, zorg er dan voor dat de `BaseUrl`‑eigenschap van `HTMLDocument` naar de map wijst die die assets bevat. Dit helpt de handler om relatieve URI's correct te resolven. + +--- + +## Stap 3: Configureer opslaanopties om de aangepaste handler te gebruiken + +`HTMLSaveOptions` stelt je in staat het uitvoerformaat en het opslagmechanisme op te geven. Het instellen van `OutputStorage` op een instantie van `MyHandler` vertelt Aspose.HTML om je handler aan te roepen voor elk extern resource. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Waarom `FileName` instellen?** – Bij het opslaan als ZIP maakt Aspose.HTML een container die het primaire HTML‑bestand (standaard `index.html`) plus alle resources bevat. Het expliciet benoemen van de entry maakt de ZIP‑structuur voorspelbaar, wat nuttig is voor downstream verwerking. + +--- + +## Stap 4: Sla het document op in een ZIP‑archief + +Nu roep je simpelweg `doc.Save` aan, waarbij je het doelpad en de geconfigureerde opties doorgeeft. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Verwacht resultaat + +Na afloop van het programma bevat `demo.zip`: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +Je kunt de ZIP openen met elke archiefviewer om te verifiëren dat het HTML‑bestand de afbeelding verwijst via het relatieve pad `assets/logo.png`. Het openen van `index.html` in een browser toont de pagina precies zoals die vóór het verpakken werd weergegeven. + +--- + +## Omgaan met grote resources en geheugenoverwegingen + +Het voorbeeld gebruikt `MemoryStream` voor elke resource, wat goed werkt voor kleine afbeeldingen of CSS‑bestanden. Voor grotere assets (bijv. foto’s met hoge resolutie of videobestanden) moet je overschakelen naar een `FileStream` om overmatig geheugenverbruik te voorkomen: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +Nadat `doc.Save` is voltooid, kun je de tijdelijke bestanden verwijderen door te itereren over `resource.CustomData["TempPath"]`. Dit patroon zorgt ervoor dat **save html as zip** betrouwbaar werkt, zelfs met assets van megabyte‑grootte. + +--- + +## Extra bestanden toevoegen aan de ZIP (bijv. een README) + +Soms wil je extra documentatie bundelen naast de HTML. Dit kun je bereiken door direct `ZipArchive` te gebruiken nadat Aspose.HTML het initiële archief heeft aangemaakt. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Nu bevat het archief ook `README.txt`, wat laat zien hoe je **create zip from html** kunt uitvoeren terwijl je het verrijkt met aangepaste inhoud. + +--- + +## Veelvoorkomende valkuilen en hoe ze te vermijden + +| Probleem | Symptomen | Oplossing | +|----------|-----------|-----------| +| Resources verschijnen niet in de ZIP | Alleen `index.html` is aanwezig; afbeeldingen ontbreken. | Zorg ervoor dat `OutputStorage` is ingesteld op een instantie van `MyHandler`. Verifieer dat `HandleResource` een schrijfbare stream retourneert. | +| Gebroken afbeeldingslinks | Browser toont “missing image” na het uitpakken van de ZIP. | `CustomData["ZipEntryName"]` moet overeenkomen met het pad dat in de HTML wordt gebruikt. Gebruik een consistente basismap (`assets/`) in de handler. | +| Out‑of‑memory‑exception voor grote bestanden | Applicatie crasht bij het verwerken van een video van 50 MB. | Schakel over van `MemoryStream` naar `FileStream` in `HandleResource`. Ruim tijdelijke bestanden op na het opslaan. | +| ZIP‑bestand vergrendeld na creatie | Volgende runs falen met “file in use”. | Dispose `HTMLDocument` (`doc.Dispose()`) en eventuele `FileStream`‑objecten voordat je de ZIP opnieuw opent. | + +--- + +## Volledig, uitvoerbaar voorbeeld + +Hieronder staat een één‑bestand console‑programma dat je kunt kopiëren, plakken en uitvoeren. Het bevat alle onderdelen die hierboven zijn besproken. + + + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stapsgewijze uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe HTML op te slaan in C# – Complete gids met een aangepaste resource handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Hoe HTML te zippen in C# – HTML opslaan naar Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [HTML opslaan als ZIP – Complete C# tutorial](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 a50bc9ccba..57ce944e60 100644 --- a/html/english/net/html-extensions-and-conversions/_index.md +++ b/html/english/net/html-extensions-and-conversions/_index.md @@ -79,6 +79,8 @@ Learn how to convert EPUB to PDF using Aspose.HTML for .NET. This step-by-step g Learn how to convert EPUB to XPS in .NET using Aspose.HTML for .NET. Follow our step-by-step guide for effortless conversions. ### [Save HTML to ZIP in C# – Complete In‑Memory Example](./save-html-to-zip-in-c-complete-in-memory-example/) Learn how to save HTML content into a ZIP archive in memory using C# and Aspose.HTML for .NET in this step-by-step tutorial. +### [Save HTML to ZIP with Aspose.HTML – complete guide](./save-html-to-zip-with-aspose-html-complete-guide/) +Learn how to save HTML files as a ZIP archive using Aspose.HTML for .NET in this complete guide. ## Conclusion diff --git a/html/english/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/english/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..addfc65e3d --- /dev/null +++ b/html/english/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,319 @@ +--- +category: general +date: 2026-08-09 +description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: en +lastmod: 2026-08-09 +og_description: Save HTML to ZIP with Aspose.HTML and a custom resource handler. This + tutorial shows you how to convert HTML to ZIP, save HTML as ZIP, and create ZIP + from HTML efficiently. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Save HTML to ZIP with Aspose.HTML – step‑by‑step guide +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Save HTML to ZIP with Aspose.HTML – complete guide +url: /net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Save HTML to ZIP with Aspose.HTML – complete guide + +If you need to **save HTML to ZIP** quickly, this tutorial shows you exactly how to do it with Aspose.HTML for .NET. By the end of the first two sentences you’ll understand how a **custom resource handler** lets you control where each resource ends up, letting you **convert HTML to ZIP**, **save HTML as ZIP**, or **create ZIP from HTML** with just a few lines of code. + +We’ll walk through a real‑world scenario: you have an HTML snippet (or a full page) and you must package it together with its images, CSS, and JavaScript into a single ZIP file that can be sent over a network or stored for later use. No external tools, no manual file copying—just pure C# and Aspose.HTML. + +You’ll learn: + +* How to implement a `ResourceHandler` that writes each resource into a `MemoryStream` (or any stream you choose). +* How to load an HTML document from a string or a file. +* How to configure `HTMLSaveOptions` to use your handler. +* How to verify the resulting ZIP archive contains the expected files. + +Prerequisites + +* .NET 6.0 or later (the code also works with .NET Framework 4.6+). +* A valid Aspose.HTML for .NET license (the free trial works for development). +* Basic familiarity with C# streams and file I/O. + +--- + +## Step 1: Create a custom resource handler + +The heart of the solution is a class that inherits from `Aspose.Html.ResourceHandler`. +Aspose.HTML calls `HandleResource` for every external asset it encounters (images, CSS, fonts, etc.). By returning a `Stream` you decide exactly how the asset is stored. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Why this matters** – Without a custom handler, Aspose.HTML writes resources to the file system in a temporary folder, which you then have to move into a ZIP manually. The handler gives you full control, eliminates intermediate files, and works equally well for large binaries when you replace `MemoryStream` with a `FileStream`. + +--- + +## Step 2: Load the HTML document + +You can load HTML from a string, a file, or any `Stream`. The example below uses an inline string for simplicity, but the same code works with `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tip** – If your HTML references local files, make sure the `BaseUrl` property of `HTMLDocument` points to the folder containing those assets. This helps the handler resolve relative URIs correctly. + +--- + +## Step 3: Configure save options to use the custom handler + +`HTMLSaveOptions` lets you specify the output format and the storage mechanism. Setting `OutputStorage` to an instance of `MyHandler` tells Aspose.HTML to invoke your handler for every external resource. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Why set `FileName`?** – When saving as ZIP, Aspose.HTML creates a container that includes the primary HTML file (named `index.html` by default) plus all resources. Explicitly naming the entry makes the ZIP structure predictable, which is useful for downstream processing. + +--- + +## Step 4: Save the document into a ZIP archive + +Now you simply call `doc.Save`, passing the target path and the configured options. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Expected result + +After the program finishes, `demo.zip` contains: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +You can open the ZIP with any archive viewer to verify that the HTML file references the image using the relative path `assets/logo.png`. Opening `index.html` in a browser will display the page exactly as it appeared before packaging. + +--- + +## Handling large resources and memory considerations + +The example uses `MemoryStream` for every resource, which works well for small images or CSS files. For larger assets (e.g., high‑resolution photos or video files) you should switch to a `FileStream` to avoid excessive memory usage: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +After `doc.Save` completes, you can delete the temporary files by iterating over `resource.CustomData["TempPath"]`. This pattern ensures **save html as zip** works reliably even with megabyte‑size assets. + +--- + +## Adding additional files to the ZIP (e.g., a README) + +Sometimes you want to bundle extra documentation alongside the HTML. You can achieve this by using `ZipArchive` directly after Aspose.HTML creates the initial archive. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Now the archive also contains `README.txt`, demonstrating how to **create zip from html** while enriching it with custom content. + +--- + +## Common pitfalls and how to avoid them + +| Issue | Symptoms | Fix | +|-------|----------|-----| +| Resources not appearing in the ZIP | Only `index.html` is present; images are missing. | Ensure `OutputStorage` is set to an instance of `MyHandler`. Verify that `HandleResource` returns a writable stream. | +| Broken image links | Browser shows “missing image” after extracting the ZIP. | The `CustomData["ZipEntryName"]` must match the path used in the HTML. Use a consistent base folder (`assets/`) in the handler. | +| Out‑of‑memory exception for large files | Application crashes when processing a 50 MB video. | Switch from `MemoryStream` to `FileStream` in `HandleResource`. Clean up temporary files after saving. | +| ZIP file locked after creation | Subsequent runs fail with “file in use”. | Dispose `HTMLDocument` (`doc.Dispose()`) and any `FileStream` objects before re‑opening the ZIP. | + +--- + +## Full, runnable example + +Below is a single‑file console program that you can copy, paste, and run. It includes all the pieces discussed above. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyHandler : ResourceHandler +{ + private readonly string _basePath; + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + entryName = Guid.NewGuid().ToString() + ".bin"; + + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + resource.CustomData["ZipEntryName"] = zipPath; + return new MemoryStream(); // replace with FileStream for large assets + } +} + +class Program +{ + static void Main() + { + // 1️⃣ HTML content (could also be loaded from a file) + string html = @" + + + + Demo + + + +

Hello, world!

+ Logo + + "; + + // 2️⃣ Load the document + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Configure the custom handler and save options + var handler = new MyHandler("assets"); + HTMLSaveOptions + + +## 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 Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Save HTML as ZIP – Complete C# Tutorial](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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/save-html-to-zip-with-aspose-html-complete-guide/og-image.png b/html/english/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/og-image.png new file mode 100644 index 0000000000000000000000000000000000000000..f08886a3428931f3cc5ac0abad4d3759664bd069 GIT binary patch literal 47478 zcmbq)1yogC*DeMP5`svVNJvO`NF&`KB@L2Nheni66{JI28bLaa(%qfX-F*&l?n2-9 z8~4Be_{SZ0+|3??eKv=^*P3gsIp;HxOn0 z-1$kfgNcMxD=a7ZLc@J}XU=$|8sSr zUuh`JBAdTPW1bxm`-Rcm_#oiVcWy@T?aq1Cq`PHxht#G2z9O?q(tL(Os#}(r5#rGO zKfLap7P(j1N6qv{;9In-dy2$=TN5%t@x@M_fRWZbd$y5L{i|lb6F%RsBXPn4slQF4 z3!?w0mH)$o!Pov*=xB%)oct&FKwPruHQ+kshZ_QuprJnmA(=-zN+q1u>7}Rt1=2X<$FQC31 zzItBszqhFjy)>#=RKcxJPUpD_{+a5DBpTs=T7>ixOZlI9@^Aaa9GX?S8$H>@9|k}2 z#9=f#DDh5Qkmq>W@slhE8T`{%7CLY75G!0yQtNK-{ZJIInf}`;c+&n3cZiDWspPu= z0~GLiBk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iWY~;8@4t5h;gvj$cXo~J3@iXj8b_z(X$e#YaF=nbr_B0L)Pu3Z$@Kk;D#J|ks zb4^;2;Wx`3>m?g_7>ZfY&C}?mBaK~kO|C5}v%lxi4tI4WtysInvMY*;8iu66;i?mc}PPb!0({-P}I%E1z7QdeS^_7^Exp}<#YMx3D=CJ0NcC%D(?X;7J1R7wUx+$;fAEJ?H)9G=Z0q=%-hyTh2zj zGh|R3x*Iu5xc+WsmJ z-&+VN%f57W8iXEyQ(t9zdXf_RCs`u@$s2zM)p?#Cq^`jJPy4+8Mc?#4_Pqb&1{YTd ZXKptwvngLlp*|k2k~~B%Pv*s6{{eJ}$JhV> literal 0 HcmV?d00001 diff --git a/html/french/net/html-extensions-and-conversions/_index.md b/html/french/net/html-extensions-and-conversions/_index.md index f4e02735c9..cf5296db83 100644 --- a/html/french/net/html-extensions-and-conversions/_index.md +++ b/html/french/net/html-extensions-and-conversions/_index.md @@ -74,6 +74,8 @@ Apprenez à compresser du HTML en un fichier zip avec C# grâce à notre guide d Apprenez à enregistrer un document HTML dans un fichier ZIP en C# avec Aspose.HTML pour .NET. Guide complet étape par étape. ### [Enregistrer HTML en ZIP en C# – Exemple complet en mémoire](./save-html-to-zip-in-c-complete-in-memory-example/) Enregistrez du HTML dans un fichier ZIP en mémoire avec Aspose.HTML pour .NET. +### [Enregistrer le HTML en ZIP avec Aspose.HTML – guide complet](./save-html-to-zip-with-aspose-html-complete-guide/) +Apprenez à enregistrer un document HTML dans un fichier ZIP avec Aspose.HTML, guide complet étape par étape. ## Conclusion diff --git a/html/french/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/french/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..6230a3842e --- /dev/null +++ b/html/french/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-08-09 +description: Enregistrez le HTML au format ZIP à l'aide d'Aspose.HTML et d'un gestionnaire + de ressources personnalisé. Apprenez comment convertir le HTML en ZIP, enregistrer + le HTML en tant que ZIP et créer un ZIP à partir du HTML en quelques étapes. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: fr +lastmod: 2026-08-09 +og_description: Enregistrez le HTML au format ZIP avec Aspose.HTML et un gestionnaire + de ressources personnalisé. Ce tutoriel vous montre comment convertir du HTML en + ZIP, enregistrer le HTML en tant que ZIP et créer un ZIP à partir du HTML de manière + efficace. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Enregistrez le HTML en ZIP avec Aspose.HTML – guide étape par étape +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Enregistrer HTML en ZIP avec Aspose.HTML – guide complet +url: /fr/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Enregistrer le HTML en ZIP avec Aspose.HTML – guide complet + +Si vous devez **enregistrer du HTML en ZIP** rapidement, ce tutoriel vous montre exactement comment le faire avec Aspose.HTML pour .NET. À la fin des deux premières phrases, vous comprendrez comment un **gestionnaire de ressources personnalisé** vous permet de contrôler où chaque ressource se retrouve, vous permettant de **convertir du HTML en ZIP**, **enregistrer du HTML en ZIP**, ou **créer un ZIP à partir du HTML** avec seulement quelques lignes de code. + +Nous allons parcourir un scénario réel : vous avez un extrait HTML (ou une page complète) et vous devez le regrouper avec ses images, CSS et JavaScript dans un seul fichier ZIP qui peut être envoyé sur un réseau ou stocké pour une utilisation ultérieure. Aucun outil externe, aucune copie manuelle de fichiers — juste du pur C# et Aspose.HTML. + +Vous apprendrez : + +* Comment implémenter un `ResourceHandler` qui écrit chaque ressource dans un `MemoryStream` (ou tout autre flux que vous choisissez). +* Comment charger un document HTML à partir d’une chaîne ou d’un fichier. +* Comment configurer `HTMLSaveOptions` pour utiliser votre gestionnaire. +* Comment vérifier que l’archive ZIP résultante contient les fichiers attendus. + +## Prérequis + +* .NET 6.0 ou ultérieur (le code fonctionne également avec .NET Framework 4.6+). +* Une licence valide d’Aspose.HTML pour .NET (l’essai gratuit suffit pour le développement). +* Une connaissance de base des flux C# et des opérations d’E/S de fichiers. + +--- + +## Étape 1 : Créer un gestionnaire de ressources personnalisé + +Le cœur de la solution est une classe qui hérite de `Aspose.Html.ResourceHandler`. +Aspose.HTML appelle `HandleResource` pour chaque ressource externe qu’il rencontre (images, CSS, polices, etc.). En retournant un `Stream`, vous décidez exactement comment la ressource est stockée. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Pourquoi c’est important** – Sans gestionnaire personnalisé, Aspose.HTML écrit les ressources sur le système de fichiers dans un dossier temporaire, que vous devez ensuite déplacer manuellement dans un ZIP. Le gestionnaire vous donne un contrôle total, élimine les fichiers intermédiaires et fonctionne tout aussi bien pour les gros binaires lorsque vous remplacez `MemoryStream` par un `FileStream`. + +--- + +## Étape 2 : Charger le document HTML + +Vous pouvez charger du HTML à partir d’une chaîne, d’un fichier ou de n’importe quel `Stream`. L’exemple ci‑dessous utilise une chaîne en ligne pour plus de simplicité, mais le même code fonctionne avec `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Astuce** – Si votre HTML fait référence à des fichiers locaux, assurez‑vous que la propriété `BaseUrl` de `HTMLDocument` pointe vers le dossier contenant ces ressources. Cela aide le gestionnaire à résoudre correctement les URI relatives. + +--- + +## Étape 3 : Configurer les options d’enregistrement pour utiliser le gestionnaire personnalisé + +`HTMLSaveOptions` vous permet de spécifier le format de sortie et le mécanisme de stockage. Définir `OutputStorage` sur une instance de `MyHandler` indique à Aspose.HTML d’invoquer votre gestionnaire pour chaque ressource externe. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Pourquoi définir `FileName` ?** – Lors de l’enregistrement en ZIP, Aspose.HTML crée un conteneur qui inclut le fichier HTML principal (nommé `index.html` par défaut) ainsi que toutes les ressources. Nommer explicitement l’entrée rend la structure du ZIP prévisible, ce qui est utile pour le traitement en aval. + +--- + +## Étape 4 : Enregistrer le document dans une archive ZIP + +Il vous suffit maintenant d’appeler `doc.Save`, en passant le chemin cible et les options configurées. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Résultat attendu + +Après l’exécution du programme, `demo.zip` contient : + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +Vous pouvez ouvrir le ZIP avec n’importe quel visualiseur d’archives pour vérifier que le fichier HTML référence l’image en utilisant le chemin relatif `assets/logo.png`. Ouvrir `index.html` dans un navigateur affichera la page exactement comme elle était avant l’empaquetage. + +--- + +## Gestion des ressources volumineuses et considérations mémoire + +L’exemple utilise `MemoryStream` pour chaque ressource, ce qui fonctionne bien pour de petites images ou fichiers CSS. Pour des actifs plus lourds (par ex., des photos haute résolution ou des fichiers vidéo) vous devez passer à un `FileStream` afin d’éviter une consommation excessive de mémoire : + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +Après la fin de `doc.Save`, vous pouvez supprimer les fichiers temporaires en parcourant `resource.CustomData["TempPath"]`. Ce schéma garantit que **save html as zip** fonctionne de manière fiable même avec des actifs de plusieurs mégaoctets. + +--- + +## Ajouter des fichiers supplémentaires au ZIP (par ex., un README) + +Parfois, vous souhaitez regrouper une documentation supplémentaire avec le HTML. Vous pouvez y parvenir en utilisant directement `ZipArchive` après qu’Aspose.HTML ait créé l’archive initiale. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +L’archive contient désormais également `README.txt`, démontrant comment **create zip from html** tout en l’enrichissant avec du contenu personnalisé. + +--- + +## Pièges courants et comment les éviter + +| Problème | Symptômes | Solution | +|----------|-----------|----------| +| Les ressources n’apparaissent pas dans le ZIP | Seul `index.html` est présent ; les images sont manquantes. | Assurez‑vous que `OutputStorage` est défini sur une instance de `MyHandler`. Vérifiez que `HandleResource` renvoie un flux en écriture. | +| Liens d’image cassés | Le navigateur indique « image manquante » après extraction du ZIP. | `CustomData["ZipEntryName"]` doit correspondre au chemin utilisé dans le HTML. Utilisez un dossier de base cohérent (`assets/`) dans le gestionnaire. | +| Exception out‑of‑memory pour les gros fichiers | L’application plante lors du traitement d’une vidéo de 50 Mo. | Passez de `MemoryStream` à `FileStream` dans `HandleResource`. Nettoyez les fichiers temporaires après l’enregistrement. | +| Fichier ZIP verrouillé après création | Les exécutions suivantes échouent avec « fichier en cours d’utilisation ». | Disposez `HTMLDocument` (`doc.Dispose()`) et tout objet `FileStream` avant de rouvrir le ZIP. | + +--- + +## Exemple complet et exécutable + +Voici un programme console monofichier que vous pouvez copier, coller et exécuter. Il inclut toutes les pièces abordées ci‑dessus. + + + +## 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 inclut des exemples de code complets et fonctionnels 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. + +- [Comment enregistrer du HTML en C# – Guide complet utilisant un gestionnaire de ressources personnalisé](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Comment zipper du HTML en C# – Enregistrer du HTML en Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Enregistrer du HTML en ZIP – Tutoriel complet C#](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 607896d28b..a62990d1f4 100644 --- a/html/german/net/html-extensions-and-conversions/_index.md +++ b/html/german/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Erstellen Sie PDF aus HTML mit C# – eine detaillierte Schritt‑für‑Schritt 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. +### [HTML in ZIP speichern – vollständige Anleitung](./save-html-to-zip-with-aspose-html-complete-guide/) +Erfahren Sie, wie Sie HTML-Inhalte mit Aspose.HTML in ein ZIP-Archiv speichern – vollständige Schritt‑für‑Schritt‑Anleitung. ## Abschluss diff --git a/html/german/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/german/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..8760f8fcd7 --- /dev/null +++ b/html/german/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Speichern Sie HTML als ZIP mit Aspose.HTML und einem benutzerdefinierten + Ressourcen‑Handler. Erfahren Sie, wie Sie HTML in ZIP konvertieren, HTML als ZIP + speichern und ZIP aus HTML in wenigen Schritten erstellen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: de +lastmod: 2026-08-09 +og_description: Speichern Sie HTML als ZIP mit Aspose.HTML und einem benutzerdefinierten + Ressourcen‑Handler. Dieses Tutorial zeigt Ihnen, wie Sie HTML in ZIP konvertieren, + HTML als ZIP speichern und ZIP effizient aus HTML erstellen. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: HTML in ZIP mit Aspose.HTML speichern – Schritt‑für‑Schritt‑Anleitung +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: HTML in ZIP mit Aspose.HTML speichern – vollständiger Leitfaden +url: /de/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML in ZIP speichern mit Aspose.HTML – vollständige Anleitung + +Wenn Sie **HTML in ZIP** schnell speichern müssen, zeigt Ihnen dieses Tutorial genau, wie Sie dies mit Aspose.HTML für .NET erledigen. Am Ende der ersten beiden Sätze verstehen Sie, wie ein **custom resource handler** Ihnen die Kontrolle darüber gibt, wo jede Ressource landet, sodass Sie **convert HTML to ZIP**, **save HTML as ZIP**, oder **create ZIP from HTML** können, und das mit nur wenigen Codezeilen. + +Wir gehen ein reales Szenario durch: Sie haben ein HTML‑Snippet (oder eine komplette Seite) und müssen es zusammen mit seinen Bildern, CSS und JavaScript in einer einzigen ZIP‑Datei verpacken, die über ein Netzwerk gesendet oder für spätere Verwendung gespeichert werden kann. Keine externen Werkzeuge, kein manuelles Kopieren von Dateien – nur reines C# und Aspose.HTML. + +Sie lernen: + +* Wie man einen `ResourceHandler` implementiert, der jede Ressource in einen `MemoryStream` (oder einen beliebigen von Ihnen gewählten Stream) schreibt. +* Wie man ein HTML‑Dokument aus einem String oder einer Datei lädt. +* Wie man `HTMLSaveOptions` konfiguriert, um Ihren Handler zu verwenden. +* Wie man überprüft, dass das resultierende ZIP‑Archiv die erwarteten Dateien enthält. + +Voraussetzungen + +* .NET 6.0 oder höher (der Code funktioniert auch mit .NET Framework 4.6+). +* Eine gültige Aspose.HTML für .NET Lizenz (die kostenlose Testversion funktioniert für die Entwicklung). +* Grundlegende Kenntnisse von C#‑Streams und Datei‑I/O. + +--- + +## Schritt 1: Einen benutzerdefinierten Resource‑Handler erstellen + +Der Kern der Lösung ist eine Klasse, die von `Aspose.Html.ResourceHandler` erbt. +Aspose.HTML ruft `HandleResource` für jede externe Ressource auf, die sie findet (Bilder, CSS, Schriftarten usw.). Indem Sie einen `Stream` zurückgeben, entscheiden Sie exakt, wie die Ressource gespeichert wird. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Warum das wichtig ist** – Ohne einen benutzerdefinierten Handler schreibt Aspose.HTML Ressourcen in ein temporäres Verzeichnis im Dateisystem, das Sie dann manuell in ein ZIP verschieben müssen. Der Handler gibt Ihnen die volle Kontrolle, eliminiert Zwischendateien und funktioniert ebenso gut für große Binärdateien, wenn Sie `MemoryStream` durch einen `FileStream` ersetzen. + +--- + +## Schritt 2: Das HTML‑Dokument laden + +Sie können HTML aus einem String, einer Datei oder einem beliebigen `Stream` laden. Das untenstehende Beispiel verwendet aus Gründen der Einfachheit einen Inline‑String, aber derselbe Code funktioniert auch mit `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tipp** – Wenn Ihr HTML lokale Dateien referenziert, stellen Sie sicher, dass die `BaseUrl`‑Eigenschaft von `HTMLDocument` auf den Ordner zeigt, der diese Ressourcen enthält. Das hilft dem Handler, relative URIs korrekt aufzulösen. + +--- + +## Schritt 3: Speicheroptionen konfigurieren, um den benutzerdefinierten Handler zu verwenden + +`HTMLSaveOptions` ermöglicht es Ihnen, das Ausgabeformat und den Speichermechanismus festzulegen. Wenn Sie `OutputStorage` auf eine Instanz von `MyHandler` setzen, weist das Aspose.HTML an, Ihren Handler für jede externe Ressource aufzurufen. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Warum `FileName` setzen?** – Beim Speichern als ZIP erstellt Aspose.HTML einen Container, der die primäre HTML‑Datei (standardmäßig `index.html`) sowie alle Ressourcen enthält. Durch das explizite Benennen des Eintrags wird die ZIP‑Struktur vorhersehbar, was für nachgelagerte Verarbeitung nützlich ist. + +--- + +## Schritt 4: Das Dokument in ein ZIP‑Archiv speichern + +Jetzt rufen Sie einfach `doc.Save` auf und übergeben den Zielpfad sowie die konfigurierten Optionen. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Erwartetes Ergebnis + +Nachdem das Programm beendet ist, enthält `demo.zip`: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +Sie können das ZIP mit jedem Archivbetrachter öffnen, um zu überprüfen, dass die HTML‑Datei das Bild über den relativen Pfad `assets/logo.png` referenziert. Das Öffnen von `index.html` in einem Browser zeigt die Seite exakt so, wie sie vor dem Verpacken aussah. + +--- + +## Umgang mit großen Ressourcen und Speicherüberlegungen + +Das Beispiel verwendet `MemoryStream` für jede Ressource, was bei kleinen Bildern oder CSS‑Dateien gut funktioniert. Für größere Assets (z. B. hochauflösende Fotos oder Videodateien) sollten Sie zu einem `FileStream` wechseln, um übermäßigen Speicherverbrauch zu vermeiden: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +Nachdem `doc.Save` abgeschlossen ist, können Sie die temporären Dateien löschen, indem Sie über `resource.CustomData["TempPath"]` iterieren. Dieses Muster stellt sicher, dass **save html as zip** zuverlässig funktioniert, selbst bei Assets von Megabyte‑Größe. + +--- + +## Zusätzliche Dateien zum ZIP hinzufügen (z. B. eine README) + +Manchmal möchten Sie zusätzliche Dokumentation zusammen mit dem HTML bündeln. Das können Sie erreichen, indem Sie `ZipArchive` direkt nach dem Erstellen des initialen Archivs durch Aspose.HTML verwenden. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Jetzt enthält das Archiv außerdem `README.txt`, was demonstriert, wie man **create zip from html** umsetzt und es gleichzeitig mit benutzerdefiniertem Inhalt anreichert. + +--- + +## Häufige Fallstricke und wie man sie vermeidet + +| Issue | Symptoms | Fix | +|-------|----------|-----| +| Resources not appearing in the ZIP | Only `index.html` is present; images are missing. | Ensure `OutputStorage` is set to an instance of `MyHandler`. Verify that `HandleResource` returns a writable stream. | +| Broken image links | Browser shows “missing image” after extracting the ZIP. | The `CustomData["ZipEntryName"]` must match the path used in the HTML. Use a consistent base folder (`assets/`) in the handler. | +| Out‑of‑memory exception for large files | Application crashes when processing a 50 MB video. | Switch from `MemoryStream` to `FileStream` in `HandleResource`. Clean up temporary files after saving. | +| ZIP file locked after creation | Subsequent runs fail with “file in use”. | Dispose `HTMLDocument` (`doc.Dispose()`) and any `FileStream` objects before re‑opening the ZIP. | + +--- + +## Vollständiges, ausführbares Beispiel + +Unten finden Sie ein ein‑Datei‑Konsolenprogramm, das Sie kopieren, einfügen und ausführen können. Es enthält alle oben besprochenen Komponenten. + + + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Wie man HTML in C# speichert – Vollständiger Leitfaden mit einem benutzerdefinierten Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Wie man HTML in C# zippt – HTML in ZIP speichern](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [HTML als ZIP speichern – Vollständiges C#‑Tutorial](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 013b0ec4b6..ce71915a60 100644 --- a/html/greek/net/html-extensions-and-conversions/_index.md +++ b/html/greek/net/html-extensions-and-conversions/_index.md @@ -68,11 +68,13 @@ url: /el/net/html-extensions-and-conversions/ ### [Πώς να συμπιέσετε HTML σε C# – Αποθήκευση HTML σε Zip](./how-to-zip-html-in-c-save-html-to-zip/) Μάθετε πώς να συμπιέσετε αρχεία HTML σε αρχείο ZIP χρησιμοποιώντας το Aspose.HTML για .NET σε C#. ### [Δημιουργία εγγράφου HTML με μορφοποιημένο κείμενο και εξαγωγή σε PDF – Πλήρης οδηγός](./create-html-document-with-styled-text-and-export-to-pdf-full/) -Μάθετε πώς να δημιουργήσετε ένα έγγραφο HTML με μορφοποιημένο κείμενο και να το εξάγετε σε PDF χρησιμοποιώντας το Aspose.HTML για .NET. +Μάθετε πώς να δημιουργήσετε ένα έγγραφο HTML με μορφοποιμένο κείμενο και να το εξάγετε σε PDF χρησιμοποιώντας το Aspose.HTML για .NET. ### [Αποθήκευση HTML ως ZIP – Πλήρης Εκπαιδευτικό C#](./save-html-as-zip-complete-c-tutorial/) Μάθετε πώς να αποθηκεύετε HTML σε αρχείο ZIP με C# και Aspose.HTML. ### [Αποθήκευση HTML σε ZIP σε C# – Πλήρες Παράδειγμα Εντός Μνήμης](./save-html-to-zip-in-c-complete-in-memory-example/) Μάθετε πώς να αποθηκεύετε HTML σε αρχείο ZIP με C# χρησιμοποιώντας πλήρες παράδειγμα εντός μνήμης. +### [Αποθήκευση HTML σε ZIP με Aspose.HTML – πλήρης οδηγός](./save-html-to-zip-with-aspose-html-complete-guide/) +Μάθετε πώς να αποθηκεύετε αρχεία HTML σε αρχείο ZIP χρησιμοποιώντας το Aspose.HTML για .NET σε πλήρη οδηγό. ## Σύναψη diff --git a/html/greek/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/greek/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..0fd7e0bf46 --- /dev/null +++ b/html/greek/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Αποθηκεύστε HTML σε ZIP χρησιμοποιώντας το Aspose.HTML και έναν προσαρμοσμένο + διαχειριστή πόρων. Μάθετε πώς να μετατρέψετε HTML σε ZIP, να αποθηκεύσετε HTML ως + ZIP και να δημιουργήσετε ZIP από HTML σε λίγα βήματα. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: el +lastmod: 2026-08-09 +og_description: Αποθηκεύστε HTML σε ZIP με το Aspose.HTML και έναν προσαρμοσμένο διαχειριστή + πόρων. Αυτό το σεμινάριο σας δείχνει πώς να μετατρέψετε HTML σε ZIP, να αποθηκεύσετε + HTML ως ZIP και να δημιουργήσετε ZIP από HTML αποδοτικά. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Αποθήκευση HTML σε ZIP με το Aspose.HTML – οδηγός βήμα‑προς‑βήμα +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Αποθήκευση HTML σε ZIP με το Aspose.HTML – πλήρης οδηγός +url: /el/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< 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. Μέχρι το τέλος των πρώτων δύο προτάσεων θα καταλάβετε πώς ένας **custom resource handler** σας επιτρέπει να ελέγχετε πού καταλήγει κάθε πόρος, επιτρέποντάς σας να **μετατρέψετε HTML σε ZIP**, **αποθηκεύσετε HTML ως ZIP**, ή **δημιουργήσετε ZIP από HTML** με μόνο λίγες γραμμές κώδικα. + +Θα περάσουμε από ένα πραγματικό σενάριο: έχετε ένα απόσπασμα HTML (ή μια πλήρη σελίδα) και πρέπει να το συσκευάσετε μαζί με τις εικόνες, το CSS και το JavaScript του σε ένα ενιαίο αρχείο ZIP που μπορεί να σταλεί μέσω δικτύου ή να αποθηκευτεί για μελλοντική χρήση. Χωρίς εξωτερικά εργαλεία, χωρίς χειροκίνητη αντιγραφή αρχείων — μόνο καθαρό C# και Aspose.HTML. + +Θα μάθετε: + +* Πώς να υλοποιήσετε ένα `ResourceHandler` που γράφει κάθε πόρο σε ένα `MemoryStream` (ή σε οποιοδήποτε stream επιλέξετε). +* Πώς να φορτώσετε ένα έγγραφο HTML από μια συμβολοσειρά ή ένα αρχείο. +* Πώς να ρυθμίσετε το `HTMLSaveOptions` ώστε να χρησιμοποιεί τον διαχειριστή σας. +* Πώς να επαληθεύσετε ότι το παραγόμενο αρχείο ZIP περιέχει τα αναμενόμενα αρχεία. + +**Προαπαιτούμενα** + +* .NET 6.0 ή νεότερη (ο κώδικας λειτουργεί επίσης με .NET Framework 4.6+). +* Ένα έγκυρο license του Aspose.HTML for .NET (η δωρεάν δοκιμή λειτουργεί για ανάπτυξη). +* Βασική εξοικείωση με streams C# και I/O αρχείων. + +--- + +## Βήμα 1: Δημιουργία προσαρμοσμένου διαχειριστή πόρων + +Η καρδιά της λύσης είναι μια κλάση που κληρονομεί από `Aspose.Html.ResourceHandler`. +Το Aspose.HTML καλεί το `HandleResource` για κάθε εξωτερικό στοιχείο που εντοπίζει (εικόνες, CSS, γραμματοσειρές κ.λπ.). Επιστρέφοντας ένα `Stream` αποφασίζετε ακριβώς πώς θα αποθηκευτεί το στοιχείο. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Γιατί είναι σημαντικό** – Χωρίς προσαρμοσμένο διαχειριστή, το Aspose.HTML γράφει τους πόρους στο σύστημα αρχείων σε έναν προσωρινό φάκελο, τον οποίο πρέπει να μετακινήσετε χειροκίνητα σε ένα ZIP. Ο διαχειριστής σας δίνει πλήρη έλεγχο, εξαλείφει τα ενδιάμεσα αρχεία και λειτουργεί εξίσου καλά για μεγάλα δυαδικά αρχεία όταν αντικαταστήσετε το `MemoryStream` με ένα `FileStream`. + +--- + +## Βήμα 2: Φόρτωση του εγγράφου HTML + +Μπορείτε να φορτώσετε HTML από μια συμβολοσειρά, ένα αρχείο ή οποιοδήποτε `Stream`. Το παρακάτω παράδειγμα χρησιμοποιεί μια ενσωματωμένη συμβολοσειρά για απλότητα, αλλά ο ίδιος κώδικας λειτουργεί με `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Συμβουλή** – Αν το HTML σας αναφέρει τοπικά αρχεία, βεβαιωθείτε ότι η ιδιότητα `BaseUrl` του `HTMLDocument` δείχνει στο φάκελο που περιέχει αυτά τα στοιχεία. Αυτό βοηθά τον διαχειριστή να επιλύει σωστά τα σχετικά URIs. + +--- + +## Βήμα 3: Ρύθμιση επιλογών αποθήκευσης για χρήση του προσαρμοσμένου διαχειριστή + +Το `HTMLSaveOptions` σας επιτρέπει να καθορίσετε τη μορφή εξόδου και τον μηχανισμό αποθήκευσης. Ορίζοντας το `OutputStorage` σε μια παρουσία του `MyHandler`, το Aspose.HTML καλεί τον διαχειριστή σας για κάθε εξωτερικό πόρο. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Γιατί ορίζεται το `FileName`;** – Κατά την αποθήκευση ως ZIP, το Aspose.HTML δημιουργεί ένα κοντέινερ που περιλαμβάνει το κύριο αρχείο HTML (με όνομα `index.html` εξ ορισμού) συν όλους τους πόρους. Η ρητή ονομασία της καταχώρισης κάνει τη δομή του ZIP προβλέψιμη, κάτι που είναι χρήσιμο για επεξεργασία σε επόμενα στάδια. + +--- + +## Βήμα 4: Αποθήκευση του εγγράφου σε αρχείο ZIP + +Τώρα απλώς καλείτε το `doc.Save`, περνώντας τη διαδρομή προορισμού και τις ρυθμισμένες επιλογές. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Αναμενόμενο αποτέλεσμα + +Μετά την ολοκλήρωση του προγράμματος, το `demo.zip` περιέχει: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +Μπορείτε να ανοίξετε το ZIP με οποιονδήποτε προβολέα αρχείων για να επαληθεύσετε ότι το αρχείο HTML αναφέρει την εικόνα χρησιμοποιώντας τη σχετική διαδρομή `assets/logo.png`. Το άνοιγμα του `index.html` σε έναν περιηγητή θα εμφανίσει τη σελίδα ακριβώς όπως ήταν πριν τη συσκευασία. + +--- + +## Διαχείριση μεγάλων πόρων και considerations μνήμης + +Το παράδειγμα χρησιμοποιεί `MemoryStream` για κάθε πόρο, κάτι που λειτουργεί καλά για μικρές εικόνες ή αρχεία CSS. Για μεγαλύτερα στοιχεία (π.χ. φωτογραφίες υψηλής ανάλυσης ή βίντεο) θα πρέπει να μεταβείτε σε `FileStream` ώστε να αποφύγετε υπερβολική χρήση μνήμης: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +Μετά το `doc.Save`, μπορείτε να διαγράψετε τα προσωρινά αρχεία επαναλαμβάνοντας το `resource.CustomData["TempPath"]`. Αυτό το πρότυπο εξασφαλίζει ότι η **save html as zip** λειτουργεί αξιόπιστα ακόμη και με πόρους μεγέθους megabyte. + +--- + +## Προσθήκη επιπλέον αρχείων στο ZIP (π.χ., README) + +Μερικές φορές θέλετε να συμπεριλάβετε επιπλέον τεκμηρίωση μαζί με το HTML. Μπορείτε να το πετύχετε χρησιμοποιώντας το `ZipArchive` απευθείας μετά το Aspose.HTML δημιουργήσει το αρχικό αρχείο. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Τώρα το αρχείο περιλαμβάνει επίσης το `README.txt`, δείχνοντας πώς να **create zip from html** ενώ το εμπλουτίζετε με προσαρμοσμένο περιεχόμενο. + +--- + +## Συνηθισμένα προβλήματα και πώς να τα αποφύγετε + +| Πρόβλημα | Συμπτώματα | Διόρθωση | +|----------|------------|----------| +| Οι πόροι δεν εμφανίζονται στο ZIP | Παρουσιάζεται μόνο το `index.html`; λείπουν οι εικόνες. | Βεβαιωθείτε ότι το `OutputStorage` είναι ορισμένο σε μια παρουσία του `MyHandler`. Επαληθεύστε ότι το `HandleResource` επιστρέφει ένα εγγράψιμο stream. | +| Σπασμένοι σύνδεσμοι εικόνων | Ο περιηγητής εμφανίζει “missing image” μετά την εξαγωγή του ZIP. | Το `CustomData["ZipEntryName"]` πρέπει να ταιριάζει με τη διαδρομή που χρησιμοποιείται στο HTML. Χρησιμοποιήστε έναν συνεπή φάκελο βάσης (`assets/`) στον διαχειριστή. | +| Εξαίρεση out‑of‑memory για μεγάλα αρχεία | Η εφαρμογή καταρρέει κατά την επεξεργασία ενός βίντεο 50 MB. | Μεταβείτε από `MemoryStream` σε `FileStream` στο `HandleResource`. Καθαρίστε τα προσωρινά αρχεία μετά την αποθήκευση. | +| Το αρχείο ZIP κλειδώνεται μετά τη δημιουργία | Οι επόμενες εκτελέσεις αποτυγχάνουν με “file in use”. | Κλείστε (`Dispose`) το `HTMLDocument` (`doc.Dispose()`) και τυχόν αντικείμενα `FileStream` πριν ανοίξετε ξανά το ZIP. | + +--- + +## Πλήρες, εκτελέσιμο παράδειγμα + +Παρακάτω υπάρχει ένα πρόγραμμα κονσόλας μονού αρχείου που μπορείτε να αντιγράψετε, να επικολλήσετε και να εκτελέσετε. Περιλαμβάνει όλα τα τμήματα που συζητήθηκαν παραπάνω. + + + +## Τι Θα Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικά παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κυριαρχήσετε πρόσθετες δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να Αποθηκεύσετε HTML σε C# – Πλήρης Οδηγός Χρήσης Προσαρμοσμένου Διαχειριστή Πόρων](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Πώς να Συμπιέσετε HTML σε C# – Αποθήκευση HTML σε Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Αποθήκευση HTML ως ZIP – Πλήρης Επίδειξη C#](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 45408d5a1f..71d119da50 100644 --- a/html/hindi/net/html-extensions-and-conversions/_index.md +++ b/html/hindi/net/html-extensions-and-conversions/_index.md @@ -77,19 +77,19 @@ Aspose.HTML के साथ .NET में HTML को MHTML में बद .NET के लिए Aspose.HTML के साथ HTML को TIFF में कैसे बदलें, यह जानें। कुशल वेब सामग्री अनुकूलन के लिए हमारे चरण-दर-चरण मार्गदर्शिका का पालन करें। ### [Aspose.HTML के साथ .NET में HTML को XPS में बदलें](./convert-html-to-xps/) -.NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को XPS में आसानी से बदलें। पूर्वापेक्षाएँ, चरण-दर-चरण मार्गदर्शिका और FAQ शामिल हैं। +.NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को XPS में आसानी से बदलें। पूर्वापेक्षाएँ, चरण-दर-स्टेप मार्गदर्शिका और FAQ शामिल हैं। ### [HTML को ZIP के रूप में सहेजें – पूर्ण C# ट्यूटोरियल](./save-html-as-zip-complete-c-tutorial/) HTML को ZIP फ़ाइल में सहेजने के चरण-दर-चरण मार्गदर्शन, C# कोड उदाहरण और अनुकूलन विकल्प। ### [C# में HTML को ज़िप कैसे करें – HTML को ज़िप में सहेजें](./how-to-zip-html-in-c-save-html-to-zip/) .NET के लिए Aspose.HTML का उपयोग करके C# में HTML को ज़िप फ़ाइल में सहेजने का तरीका सीखें। -### [स्टाइल्ड टेक्स्ट के साथ HTML दस्तावेज़ बनाएं और PDF में निर्यात करें – पूर्ण गाइड](./create-html-document-with-styled-text-and-export-to-pdf-full/) -Aspose.HTML for .NET का उपयोग करके स्टाइल्ड टेक्ट वाले HTML दस्तावेज़ को बनाएं और उसे PDF में निर्यात करने की पूरी गाइड। -.NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को XPS में आसानी से बदलें। पूर्वापेक्षाएँ, चरण-दर-स्टेप मार्गदर्शिका और FAQ शामिल हैं। ### [C# में HTML को ZIP में सहेजें – पूर्ण इन‑मेमोरी उदाहरण](./save-html-to-zip-in-c-complete-in-memory-example/) C# में इन‑मेमोरी में HTML को ZIP फ़ाइल में सहेजने का पूरा उदाहरण देखें। +### [Aspose.HTML के साथ HTML को ZIP में सहेजें – पूर्ण गाइड](./save-html-to-zip-with-aspose-html-complete-guide/) +Aspose.HTML का उपयोग करके HTML को ZIP फ़ाइल में सहेजने की पूरी प्रक्रिया सीखें। चरण‑दर‑स्टेप कोड उदाहरण और विकल्प। + ## निष्कर्ष निष्कर्ष में, HTML एक्सटेंशन और रूपांतरण आधुनिक वेब विकास के आवश्यक तत्व हैं। .NET के लिए Aspose.HTML प्रक्रिया को सरल बनाता है और इसे सभी स्तरों के डेवलपर्स के लिए सुलभ बनाता है। हमारे ट्यूटोरियल का पालन करके, आप एक व्यापक कौशल सेट के साथ एक कुशल वेब डेवलपर बनने के अपने रास्ते पर अच्छी तरह से आगे बढ़ेंगे। diff --git a/html/hindi/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/hindi/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..4b960fdd6b --- /dev/null +++ b/html/hindi/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Aspose.HTML और एक कस्टम रिसोर्स हैंडलर का उपयोग करके HTML को ZIP में + सहेजें। जानिए कैसे HTML को ZIP में बदलें, HTML को ZIP के रूप में सहेजें, और कुछ + चरणों में HTML से ZIP बनाएं। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: hi +lastmod: 2026-08-09 +og_description: Aspose.HTML और एक कस्टम रिसोर्स हैंडलर के साथ HTML को ZIP में सहेजें। + यह ट्यूटोरियल दिखाता है कि HTML को ZIP में कैसे बदलें, HTML को ZIP के रूप में कैसे + सहेजें, और HTML से ZIP को प्रभावी ढंग से कैसे बनाएं। +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Aspose.HTML के साथ HTML को ZIP में सहेजें – चरण‑दर‑चरण मार्गदर्शिका +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Aspose.HTML के साथ HTML को ZIP में सहेजें – पूर्ण मार्गदर्शिका +url: /hi/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< 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 के साथ यह बिल्कुल कैसे करना है दिखाता है। पहले दो वाक्यों के अंत तक आप समझ जाएंगे कि एक **custom resource handler** कैसे आपको प्रत्येक रिसोर्स के स्थान को नियंत्रित करने देता है, जिससे आप कुछ ही कोड लाइनों के साथ **HTML को ZIP में बदल सकते** हैं, **HTML को ZIP के रूप में सहेज सकते** हैं, या **HTML से ZIP बना सकते** हैं। + +हम एक वास्तविक‑दुनिया परिदृश्य पर चलेंगे: आपके पास एक HTML स्निपेट (या पूरा पेज) है और आपको इसे उसकी इमेजेज़, CSS, और JavaScript के साथ एक ही ZIP फ़ाइल में पैकेज करना है जिसे नेटवर्क पर भेजा सके या बाद में उपयोग के लिए संग्रहीत किया जा सके। कोई बाहरी टूल नहीं, कोई मैन्युअल फ़ाइल कॉपी नहीं—सिर्फ शुद्ध C# और Aspose.HTML। + +आप सीखेंगे: + +* कैसे एक `ResourceHandler` लागू करें जो प्रत्येक रिसोर्स को एक `MemoryStream` (या आपकी पसंद का कोई भी स्ट्रीम) में लिखता है। +* कैसे एक HTML दस्तावेज़ को स्ट्रिंग या फ़ाइल से लोड करें। +* कैसे `HTMLSaveOptions` को कॉन्फ़िगर करें ताकि आपका हैंडलर उपयोग हो। +* कैसे सत्यापित करें कि परिणामी ZIP आर्काइव में अपेक्षित फ़ाइलें मौजूद हैं। + +आवश्यकताएँ + +* .NET 6.0 या बाद का संस्करण (कोड .NET Framework 4.6+ के साथ भी काम करता है)। +* एक वैध Aspose.HTML for .NET लाइसेंस (डेवलपमेंट के लिए फ्री ट्रायल काम करता है)। +* C# स्ट्रीम्स और फ़ाइल I/O की बुनियादी परिचितता। + +--- + +## चरण 1: एक कस्टम रिसोर्स हैंडलर बनाएं + +समाधान का मूल भाग एक क्लास है जो `Aspose.Html.ResourceHandler` से विरासत में लेती है। +Aspose.HTML प्रत्येक बाहरी एसेट (इमेजेज़, CSS, फ़ॉन्ट्स, आदि) के लिए `HandleResource` को कॉल करता है। एक `Stream` लौटाकर आप तय करते हैं कि एसेट कैसे संग्रहीत किया जाए। + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**यह क्यों महत्वपूर्ण है** – बिना कस्टम हैंडलर के, Aspose.HTML रिसोर्सेज़ को फ़ाइल सिस्टम में एक अस्थायी फ़ोल्डर में लिखता है, जिसे आपको फिर मैन्युअली ZIP में ले जाना पड़ता है। हैंडलर आपको पूर्ण नियंत्रण देता है, मध्यवर्ती फ़ाइलों को समाप्त करता है, और जब आप `MemoryStream` को `FileStream` से बदलते हैं तो बड़े बाइनरीज़ के लिए भी समान रूप से काम करता है। + +--- + +## चरण 2: HTML दस्तावेज़ लोड करें + +आप HTML को स्ट्रिंग, फ़ाइल, या किसी भी `Stream` से लोड कर सकते हैं। नीचे दिया गया उदाहरण सरलता के लिए एक इनलाइन स्ट्रिंग का उपयोग करता है, लेकिन वही कोड `new HTMLDocument("path/to/file.html")` के साथ भी काम करता है। + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**टिप** – यदि आपका HTML स्थानीय फ़ाइलों को संदर्भित करता है, तो सुनिश्चित करें कि `HTMLDocument` की `BaseUrl` प्रॉपर्टी उन एसेट्स वाले फ़ोल्डर की ओर इशारा करती है। यह हैंडलर को रिलेटिव URI को सही ढंग से हल करने में मदद करता है। + +--- + +## चरण 3: कस्टम हैंडलर का उपयोग करने के लिए सेव ऑप्शन कॉन्फ़िगर करें + +`HTMLSaveOptions` आपको आउटपुट फ़ॉर्मेट और स्टोरेज मेकैनिज़्म निर्दिष्ट करने देता है। `OutputStorage` को `MyHandler` की एक इंस्टेंस पर सेट करने से Aspose.HTML प्रत्येक बाहरी रिसोर्स के लिए आपका हैंडलर कॉल करता है। + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**`FileName` क्यों सेट करें?** – जब ZIP के रूप में सहेजा जाता है, तो Aspose.HTML एक कंटेनर बनाता है जिसमें मुख्य HTML फ़ाइल (`index.html` डिफ़ॉल्ट रूप से) और सभी रिसोर्सेज़ शामिल होते हैं। एंट्री को स्पष्ट रूप से नाम देने से ZIP संरचना पूर्वानुमेय बनती है, जो डाउनस्ट्रीम प्रोसेसिंग के लिए उपयोगी है। + +--- + +## चरण 4: दस्तावेज़ को ZIP आर्काइव में सहेजें + +अब आप बस `doc.Save` को कॉल करते हैं, लक्ष्य पथ और कॉन्फ़िगर किए गए विकल्प पास करते हैं। + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### अपेक्षित परिणाम + +प्रोग्राम समाप्त होने के बाद, `demo.zip` में शामिल हैं: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +आप किसी भी आर्काइव व्यूअर से ZIP खोल सकते हैं यह सत्यापित करने के लिए कि HTML फ़ाइल इमेज को रिलेटिव पाथ `assets/logo.png` से संदर्भित करती है। ब्राउज़र में `index.html` खोलने पर पेज बिल्कुल उसी तरह दिखेगा जैसा पैकेजिंग से पहले था। + +--- + +## बड़े रिसोर्सेज़ और मेमोरी विचारों को संभालना + +उदाहरण प्रत्येक रिसोर्स के लिए `MemoryStream` का उपयोग करता है, जो छोटे इमेजेज़ या CSS फ़ाइलों के लिए उपयुक्त है। बड़े एसेट्स (जैसे हाई‑रेज़ोल्यूशन फ़ोटो या वीडियो फ़ाइलें) के लिए आपको `FileStream` पर स्विच करना चाहिए ताकि अत्यधिक मेमोरी उपयोग से बचा जा सके: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +`doc.Save` पूरा होने के बाद, आप `resource.CustomData["TempPath"]` पर इटररेट करके अस्थायी फ़ाइलों को हटा सकते हैं। यह पैटर्न सुनिश्चित करता है कि **save html as zip** मेगाबाइट‑साइज़ एसेट्स के साथ भी विश्वसनीय रूप से काम करे। + +--- + +## ZIP में अतिरिक्त फ़ाइलें जोड़ना (जैसे, README) + +कभी-कभी आप HTML के साथ अतिरिक्त दस्तावेज़ीकरण बंडल करना चाहते हैं। आप इसे Aspose.HTML द्वारा प्रारंभिक आर्काइव बनाने के बाद सीधे `ZipArchive` का उपयोग करके प्राप्त कर सकते हैं। + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +अब आर्काइव में `README.txt` भी शामिल है, जो दिखाता है कि कैसे **create zip from html** किया जाता है जबकि इसे कस्टम कंटेंट से समृद्ध किया गया है। + +--- + +## सामान्य समस्याएँ और उन्हें कैसे टालें + +| समस्या | लक्षण | समाधान | +|-------|----------|-----| +| ZIP में रिसोर्सेज़ नहीं दिख रहे हैं | `index.html` ही मौजूद है; इमेजेज़ गायब हैं। | `OutputStorage` को `MyHandler` की एक इंस्टेंस पर सेट करना सुनिश्चित करें। यह जांचें कि `HandleResource` एक लिखने योग्य स्ट्रीम लौटाता है। | +| टूटी हुई इमेज लिंक | ZIP निकालने के बाद ब्राउज़र “missing image” दिखाता है। | `CustomData["ZipEntryName"]` को HTML में उपयोग किए गए पाथ से मेल खाना चाहिए। हैंडलर में एक सुसंगत बेस फ़ोल्डर (`assets/`) उपयोग करें। | +| बड़ी फ़ाइलों के लिए Out‑of‑memory अपवाद | 50 MB वीडियो प्रोसेस करते समय एप्लिकेशन क्रैश हो जाता है। | `HandleResource` में `MemoryStream` से `FileStream` पर स्विच करें। सहेजने के बाद अस्थायी फ़ाइलों को साफ़ करें। | +| सृजन के बाद ZIP फ़ाइल लॉक हो गई | अगले रन “file in use” त्रुटि के साथ विफल होते हैं। | `HTMLDocument` (`doc.Dispose()`) और किसी भी `FileStream` ऑब्जेक्ट को ZIP को पुनः खोलने से पहले डिस्पोज़ करें। | + +--- + +## पूर्ण, चलाने योग्य उदाहरण + +नीचे एक सिंगल‑फ़ाइल कंसोल प्रोग्राम है जिसे आप कॉपी, पेस्ट और रन कर सकते हैं। इसमें ऊपर चर्चा किए गए सभी भाग शामिल हैं। + + + +## अब आपको आगे क्या सीखना चाहिए? + +निम्नलिखित ट्यूटोरियल्स उन निकट-संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण-दर-चरण व्याख्याएँ शामिल हैं ताकि आप अतिरिक्त API फीचर्स में माहिर हो सकें और अपने प्रोजेक्ट्स में वैकल्पिक कार्यान्वयन दृष्टिकोणों का अन्वेषण कर सकें। + +- [HTML को C# में सहेजने का तरीका – कस्टम रिसोर्स हैंडलर का उपयोग करके पूर्ण गाइड](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [C# में HTML को ज़िप करने का तरीका – HTML को ZIP में सहेजें](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [HTML को ZIP के रूप में सहेजें – पूर्ण C# ट्यूटोरियल](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 3d146ada27..474f750334 100644 --- a/html/hongkong/net/html-extensions-and-conversions/_index.md +++ b/html/hongkong/net/html-extensions-and-conversions/_index.md @@ -67,12 +67,12 @@ Aspose.HTML for .NET 不只是一個函式庫;它還是一個函式庫。它 探索 Aspose.HTML for .NET 的強大功能:輕鬆將 HTML 轉換為 XPS。包括先決條件、逐步指南和常見問題。 ### [如何在 C# 中壓縮 HTML – 將 HTML 保存為 Zip](./how-to-zip-html-in-c-save-html-to-zip/) 了解如何使用 Aspose.HTML for .NET 在 C# 中將 HTML 壓縮為 Zip 檔案,並保存以便分發。 -### [建立具樣式文字的 HTML 文件並匯出為 PDF – 完整指南](./create-html-document-with-styled-text-and-export-to-pdf-full/) -使用 Aspose.HTML for .NET 建立帶樣式文字的 HTML 文件,並將其匯出為 PDF 的完整步驟指南。 ### [使用 Aspose.HTML 將 HTML 儲存為 ZIP – 完整 C# 教學](./save-html-as-zip-complete-c-tutorial/) 使用 Aspose.HTML for .NET 將 HTML 文件壓縮為 ZIP 檔案,提供完整的 C# 範例與步驟說明。 ### [在 C# 中將 HTML 儲存為 ZIP – 完整的記憶體內示例](./save-html-to-zip-in-c-complete-in-memory-example/) 示範如何在 C# 中使用 Aspose.HTML 將 HTML 內容直接壓縮成 ZIP 檔案,全部在記憶體中完成。 +### [使用 Aspose.HTML 將 HTML 儲存為 ZIP – 完整指南](./save-html-to-zip-with-aspose-html-complete-guide/) +使用 Aspose.HTML for .NET 完整示範如何將 HTML 壓縮為 ZIP 檔案,包含程式碼範例與步驟說明。 ## 結論 diff --git a/html/hongkong/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/hongkong/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..cc1b31878c --- /dev/null +++ b/html/hongkong/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2026-08-09 +description: 使用 Aspose.HTML 及自訂資源處理程式將 HTML 儲存為 ZIP。了解如何將 HTML 轉換為 ZIP、將 HTML 儲存為 + ZIP,以及在幾個步驟內從 HTML 建立 ZIP。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: zh-hant +lastmod: 2026-08-09 +og_description: 使用 Aspose.HTML 及自訂資源處理程式將 HTML 儲存為 ZIP。本教學示範如何將 HTML 轉換為 ZIP、將 HTML + 儲存為 ZIP,以及高效地從 HTML 建立 ZIP。 +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: 使用 Aspose.HTML 將 HTML 儲存為 ZIP – 一步一步指南 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: 使用 Aspose.HTML 將 HTML 儲存為 ZIP – 完整指南 +url: /zh-hant/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose.HTML 將 HTML 儲存為 ZIP – 完整指南 + +如果您需要快速 **save HTML to ZIP**,本教學會精確示範如何使用 Aspose.HTML for .NET 完成。閱讀前兩句後,您將了解 **custom resource handler** 如何讓您控制每個資源的儲存位置,從而只需幾行程式碼即可 **convert HTML to ZIP**、**save HTML as ZIP** 或 **create ZIP from HTML**。 + +我們將以真實情境示範:您有一段 HTML 片段(或完整頁面),必須將其與圖片、CSS 與 JavaScript 一併打包成單一 ZIP 檔,以便透過網路傳輸或日後儲存。無需外部工具、無需手動複製檔案——僅使用純 C# 與 Aspose.HTML。 + +您將學習: + +* 如何實作一個 `ResourceHandler`,將每個資源寫入 `MemoryStream`(或您選擇的任何串流)。 +* 如何從字串或檔案載入 HTML 文件。 +* 如何設定 `HTMLSaveOptions` 以使用您的處理程式。 +* 如何驗證產生的 ZIP 壓縮檔包含預期的檔案。 + +## 前置條件 + +* .NET 6.0 或更新版本(程式碼亦相容 .NET Framework 4.6+)。 +* 有效的 Aspose.HTML for .NET 授權(免費試用版可用於開發)。 +* 基本了解 C# 串流與檔案 I/O。 + +--- + +## Step 1: Create a custom resource handler + +解決方案的核心是一個繼承自 `Aspose.Html.ResourceHandler` 的類別。 +Aspose.HTML 會對每個遇到的外部資源(圖片、CSS、字型等)呼叫 `HandleResource`。回傳 `Stream` 後,即可自行決定資源的儲存方式。 + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Why this matters** – 若未使用自訂處理程式,Aspose.HTML 會將資源寫入暫存資料夾,之後您必須手動將它們移入 ZIP。自訂處理程式讓您完全掌控,省去中間檔案,且在將 `MemoryStream` 換成 `FileStream` 後,同樣適用於大型二進位檔。 + +--- + +## Step 2: Load the HTML document + +您可以從字串、檔案或任何 `Stream` 載入 HTML。下例為了簡化使用內嵌字串,但相同程式碼亦可配合 `new HTMLDocument("path/to/file.html")` 使用。 + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tip** – 若您的 HTML 參照本機檔案,請確保 `HTMLDocument` 的 `BaseUrl` 屬性指向包含這些資產的資料夾。這可協助處理程式正確解析相對 URI。 + +--- + +## Step 3: Configure save options to use the custom handler + +`HTMLSaveOptions` 允許您指定輸出格式與儲存機制。將 `OutputStorage` 設為 `MyHandler` 的實例,即可告訴 Aspose.HTML 為每個外部資源呼叫您的處理程式。 + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Why set `FileName`?** – 以 ZIP 格式儲存時,Aspose.HTML 會建立一個容器,內含主要的 HTML 檔(預設為 `index.html`)以及所有資源。明確命名條目可使 ZIP 結構可預測,對後續處理十分有用。 + +--- + +## Step 4: Save the document into a ZIP archive + +現在只要呼叫 `doc.Save`,並傳入目標路徑與先前設定好的選項即可。 + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Expected result + +程式執行完畢後,`demo.zip` 內包含: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +您可以使用任何壓縮檔檢視器開啟 ZIP,驗證 HTML 檔案是否以相對路徑 `assets/logo.png` 參照圖片。於瀏覽器開啟 `index.html`,即可看到與打包前完全相同的頁面。 + +--- + +## Handling large resources and memory considerations + +範例對每個資源皆使用 `MemoryStream`,對小型圖片或 CSS 檔案相當適合。若資產較大(例如高解析度照片或影片檔),建議改用 `FileStream` 以避免記憶體過度使用: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +`doc.Save` 完成後,您可以透過遍歷 `resource.CustomData["TempPath"]` 刪除暫存檔案。此模式確保 **save html as zip** 即使面對 MB 級資產也能穩定運作。 + +--- + +## Adding additional files to the ZIP (e.g., a README) + +有時您希望在 HTML 之外再加入額外文件(如說明文件)。可在 Aspose.HTML 產生初始壓縮檔後,直接使用 `ZipArchive` 加入這些檔案。 + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +現在壓縮檔亦包含 `README.txt`,示範如何在 **create zip from html** 的同時加入自訂內容。 + +--- + +## Common pitfalls and how to avoid them + +| Issue | Symptoms | Fix | +|-------|----------|-----| +| Resources not appearing in the ZIP | Only `index.html` is present; images are missing. | Ensure `OutputStorage` is set to an instance of `MyHandler`. Verify that `HandleResource` returns a writable stream. | +| Broken image links | Browser shows “missing image” after extracting the ZIP. | The `CustomData["ZipEntryName"]` must match the path used in the HTML. Use a consistent base folder (`assets/`) in the handler. | +| Out‑of‑memory exception for large files | Application crashes when processing a 50 MB video. | Switch from `MemoryStream` to `FileStream` in `HandleResource`. Clean up temporary files after saving. | +| ZIP file locked after creation | Subsequent runs fail with “file in use”. | Dispose `HTMLDocument` (`doc.Dispose()`) and any `FileStream` objects before re‑opening the ZIP. | + +--- + +## Full, runnable example + +Below is a single‑file console program that you can copy, paste, and run. It includes all the pieces discussed above. + + + +## What Should You Learn Next? + +以下教學與本指南所示技術緊密相關,能進一步深化您的應用。每篇資源皆提供完整可執行的程式碼範例與逐步說明,協助您掌握更多 API 功能,並在自己的專案中探索替代實作方式。 + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Save HTML as ZIP – Complete C# Tutorial](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 53dd8b575e..10cbccc777 100644 --- a/html/hungarian/net/html-extensions-and-conversions/_index.md +++ b/html/hungarian/net/html-extensions-and-conversions/_index.md @@ -59,6 +59,7 @@ Hozzon létre HTML-dokumentumot formázott szöveggel, majd exportálja PDF-be a 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 mentése ZIP-ként – Teljes C# oktatóanyag](./save-html-as-zip-complete-c-tutorial/) ### [HTML mentése ZIP-be C#‑ban – Teljes memória‑beli példa](./save-html-to-zip-in-c-complete-in-memory-example/) +### [HTML mentése ZIP-be az Aspose.HTML-lel – teljes útmutató](./save-html-to-zip-with-aspose-html-complete-guide/) Mentse a HTML-t közvetlenül memóriában ZIP-archívumba az Aspose.HTML for .NET C#‑ban. ## Következtetés diff --git a/html/hungarian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/hungarian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..8e30f1bb23 --- /dev/null +++ b/html/hungarian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: HTML mentése ZIP-be az Aspose.HTML és egy egyéni erőforráskezelő használatával. + Ismerje meg, hogyan konvertálhatja az HTML-t ZIP-be, mentheti az HTML-t ZIP-ként, + és hozhat létre ZIP-et HTML-ből néhány lépésben. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: hu +lastmod: 2026-08-09 +og_description: HTML mentése ZIP-be az Aspose.HTML és egy egyéni erőforráskezelő segítségével. + Ez az útmutató megmutatja, hogyan konvertálhatja a HTML-t ZIP-be, hogyan mentheti + a HTML-t ZIP-ként, és hogyan hozhat létre ZIP-et HTML-ből hatékonyan. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: HTML mentése ZIP-be az Aspose.HTML segítségével – lépésről‑lépésre útmutató +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: HTML mentése ZIP-be az Aspose.HTML segítségével – teljes útmutató +url: /hu/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML mentése ZIP-be az Aspose.HTML segítségével – teljes útmutató + +Ha gyorsan szeretne **HTML-t ZIP-be menteni**, ez az útmutató pontosan megmutatja, hogyan teheti ezt meg az Aspose.HTML for .NET segítségével. Az első két mondat végére megérti, hogyan teszi lehetővé egy **egyedi erőforráskezelő**, hogy szabályozza, hová kerül minden erőforrás, így **HTML-t ZIP-be konvertálhat**, **HTML-t ZIP-ként menthet**, vagy **ZIP-et hozhat létre HTML-ből** néhány kódsorral. + +Egy valós példán keresztül vezetjük végig: van egy HTML részlet (vagy egy teljes oldal), és azt a képekkel, CSS-sel és JavaScript‑tel együtt egyetlen ZIP‑fájlba kell csomagolni, amely hálózaton keresztül elküldhető vagy későbbi felhasználásra tárolható. Nincs külső eszköz, nincs manuális fájlmásolás – csak tiszta C# és Aspose.HTML. + +Tanulni fogja: + +* Hogyan valósítsunk meg egy `ResourceHandler`‑t, amely minden erőforrást egy `MemoryStream`‑be (vagy bármely általunk választott streambe) ír. +* Hogyan töltsünk be egy HTML dokumentumot egy karakterláncból vagy fájlból. +* Hogyan konfiguráljuk a `HTMLSaveOptions`‑t, hogy a saját kezelőnket használja. +* Hogyan ellenőrizzük, hogy a létrejött ZIP-archívum tartalmazza-e a várt fájlokat. + +Előfeltételek + +* .NET 6.0 vagy újabb (a kód .NET Framework 4.6+‑tal is működik). +* Érvényes Aspose.HTML for .NET licenc (az ingyenes próba verzió fejlesztéshez használható). +* Alapvető ismeretek a C# streamekkel és fájl‑I/O‑val kapcsolatban. + +--- + +## 1. lépés: Egyedi erőforráskezelő létrehozása + +Az megoldás központja egy olyan osztály, amely örökli a `Aspose.Html.ResourceHandler`‑t. +Az Aspose.HTML minden külső erőforrásra (képek, CSS, betűkészletek stb.) meghívja a `HandleResource`‑t. Ha egy `Stream`‑et ad vissza, pontosan meghatározhatja, hogyan tárolódik az erőforrás. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Miért fontos ez** – Egyedi kezelő nélkül az Aspose.HTML az erőforrásokat egy ideiglenes mappába írja a fájlrendszerre, amelyet aztán manuálisan kell áthelyezni egy ZIP‑be. A kezelő teljes irányítást biztosít, megszünteti a köztes fájlokat, és nagy binárisok esetén is egyformán jól működik, ha a `MemoryStream`‑et `FileStream`‑re cseréli. + +--- + +## 2. lépés: A HTML dokumentum betöltése + +HTML‑t betölthet egy karakterláncból, fájlból vagy bármely `Stream`‑ből. Az alábbi példa egyszerűség kedvéért egy beágyazott karakterláncot használ, de ugyanaz a kód működik a `new HTMLDocument("path/to/file.html")`‑vel is. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tipp** – Ha a HTML helyi fájlokra hivatkozik, győződjön meg róla, hogy a `HTMLDocument` `BaseUrl` tulajdonsága a megfelelő mappára mutat, amely tartalmazza ezeket az erőforrásokat. Ez segít a kezelőnek a relatív URI‑k helyes feloldásában. + +--- + +## 3. lépés: A mentési beállítások konfigurálása az egyedi kezelő használatához + +A `HTMLSaveOptions` lehetővé teszi a kimeneti formátum és a tárolási mechanizmus megadását. Az `OutputStorage` beállítása egy `MyHandler` példányra azt mondja az Aspose.HTML‑nek, hogy minden külső erőforrás esetén hívja meg az Ön kezelőjét. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Miért állítjuk be a `FileName`‑t?** – ZIP‑ként mentéskor az Aspose.HTML egy konténert hoz létre, amely tartalmazza az elsődleges HTML‑fájlt (alapértelmezés szerint `index.html` néven) és az összes erőforrást. Az elem explicit elnevezése előre láthatóvá teszi a ZIP‑szerkezetet, ami hasznos a további feldolgozáshoz. + +--- + +## 4. lépés: A dokumentum mentése ZIP archívumba + +Most egyszerűen meghívja a `doc.Save`‑t, megadva a célútvonalat és a konfigurált beállításokat. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Várható eredmény + +A program befejezése után a `demo.zip` tartalmazza: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +A ZIP‑et bármely archívum‑megtekintővel megnyithatja, hogy ellenőrizze, a HTML‑fájl a `assets/logo.png` relatív útvonalat használja a kép hivatkozásához. Az `index.html` böngészőben történő megnyitása pontosan úgy jeleníti meg az oldalt, ahogy a csomagolás előtt volt. + +--- + +## Nagy erőforrások kezelése és memória megfontolások + +A példa minden erőforráshoz `MemoryStream`‑et használ, ami kis képek vagy CSS‑fájlok esetén jól működik. Nagyobb eszközök (pl. nagy felbontású fényképek vagy videófájlok) esetén `FileStream`‑re kell váltani a túlzott memóriahasználat elkerülése érdekében: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +A `doc.Save` befejezése után a `resource.CustomData["TempPath"]` elemein végig iterálva törölheti az ideiglenes fájlokat. Ez a minta biztosítja, hogy a **save html as zip** megbízhatóan működjön még megabájt méretű eszközök esetén is. + +--- + +## További fájlok hozzáadása a ZIP‑hez (pl. README) + +Néha szeretne további dokumentációt csomagolni a HTML mellé. Ezt úgy érheti el, hogy a `ZipArchive`‑t közvetlenül az Aspose.HTML által létrehozott kezdeti archívum után használja. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Most az archívum tartalmazza a `README.txt`‑t is, bemutatva, hogyan **create zip from html** miközben egyedi tartalommal bővíti. + +--- + +## Gyakori buktatók és azok elkerülése + +| Probléma | Tünetek | Megoldás | +|----------|----------|----------| +| Az erőforrások nem jelennek meg a ZIP-ben | Csak az `index.html` van jelen; a képek hiányoznak. | Győződjön meg róla, hogy az `OutputStorage` egy `MyHandler` példányra van beállítva. Ellenőrizze, hogy a `HandleResource` írható streamet ad vissza. | +| Törött képhivatkozások | A böngésző a ZIP kibontása után “missing image” (hiányzó kép) üzenetet mutat. | A `CustomData["ZipEntryName"]`-nek meg kell egyeznie a HTML-ben használt úttal. Használjon egységes alapmappát (`assets/`) a kezelőben. | +| Memóriahiányos kivétel nagy fájlok esetén | Az alkalmazás összeomlik egy 50 MB-os videó feldolgozásakor. | Cserélje a `MemoryStream`‑et `FileStream`‑re a `HandleResource`‑ben. Takarítsa el az ideiglenes fájlokat a mentés után. | +| ZIP fájl zárolva a létrehozás után | A későbbi futtatások “file in use” (fájl használatban) hibát adnak. | Felszabadítsa a `HTMLDocument`‑et (`doc.Dispose()`) és minden `FileStream` objektumot a ZIP újranyitása előtt. | + +--- + +## Teljes, futtatható példa + +Az alábbi egy egyfájlos konzolprogram, amelyet másolhat, beilleszthet és futtathat. Tartalmazza a fent tárgyalt összes részt. + + + +## Mit érdemes következőként megtanulni? + +A következő útmutató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 segítsenek elsajátítani további API‑funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeiben. + +- [Hogyan mentse a HTML-t C#‑ban – Teljes útmutató egyedi erőforráskezelő használatával](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Hogyan zip‑eljük a HTML-t C#‑ban – HTML mentése ZIP‑be](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [HTML mentése ZIP‑ként – Teljes C# tutorial](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 6ac5368fff..c72cdab9dd 100644 --- a/html/indonesian/net/html-extensions-and-conversions/_index.md +++ b/html/indonesian/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,7 @@ Pelajari cara membuat dokumen HTML dengan teks berformat dan mengekspornya ke PD Pelajari cara menyimpan file HTML sebagai arsip ZIP menggunakan Aspose.HTML untuk .NET dengan contoh kode C# lengkap. ### [Simpan HTML ke ZIP di C# – Contoh In‑Memory Lengkap](./save-html-to-zip-in-c-complete-in-memory-example/) Pelajari cara menyimpan file HTML ke dalam arsip ZIP secara langsung di memori menggunakan C# dan Aspose.HTML. +### [Simpan HTML ke ZIP dengan Aspose.HTML – panduan lengkap](./save-html-to-zip-with-aspose-html-complete-guide/) ## Kesimpulan diff --git a/html/indonesian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/indonesian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..c6761bf1a0 --- /dev/null +++ b/html/indonesian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,318 @@ +--- +category: general +date: 2026-08-09 +description: Simpan HTML ke ZIP menggunakan Aspose.HTML dan handler sumber daya khusus. + Pelajari cara mengonversi HTML ke ZIP, menyimpan HTML sebagai ZIP, dan membuat ZIP + dari HTML dalam beberapa langkah. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: id +lastmod: 2026-08-09 +og_description: Simpan HTML ke ZIP dengan Aspose.HTML dan penangan sumber daya khusus. + Tutorial ini menunjukkan cara mengonversi HTML ke ZIP, menyimpan HTML sebagai ZIP, + dan membuat ZIP dari HTML secara efisien. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Simpan HTML ke ZIP dengan Aspose.HTML – panduan langkah demi langkah +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Menyimpan HTML ke ZIP dengan Aspose.HTML – panduan lengkap +url: /id/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Simpan HTML ke ZIP dengan Aspose.HTML – panduan lengkap + +Jika Anda perlu **save HTML to ZIP** dengan cepat, tutorial ini menunjukkan secara tepat cara melakukannya dengan Aspose.HTML untuk .NET. Pada akhir dua kalimat pertama Anda akan memahami bagaimana **custom resource handler** memungkinkan Anda mengontrol ke mana setiap sumber daya disimpan, memungkinkan Anda **convert HTML to ZIP**, **save HTML as ZIP**, atau **create ZIP from HTML** dengan hanya beberapa baris kode. + +Kami akan membahas skenario dunia nyata: Anda memiliki potongan HTML (atau halaman lengkap) dan harus mengemasnya bersama dengan gambar, CSS, dan JavaScript ke dalam satu file ZIP yang dapat dikirim melalui jaringan atau disimpan untuk penggunaan nanti. Tanpa alat eksternal, tanpa menyalin file secara manual—hanya C# murni dan Aspose.HTML. + +Anda akan belajar: + +* Cara mengimplementasikan `ResourceHandler` yang menulis setiap sumber daya ke dalam `MemoryStream` (atau stream apa pun yang Anda pilih). +* Cara memuat dokumen HTML dari string atau file. +* Cara mengonfigurasi `HTMLSaveOptions` untuk menggunakan handler Anda. +* Cara memverifikasi arsip ZIP yang dihasilkan berisi file yang diharapkan. + +**Prasyarat** + +* .NET 6.0 atau lebih baru (kode juga berfungsi dengan .NET Framework 4.6+). +* Lisensi Aspose.HTML untuk .NET yang valid (versi percobaan gratis dapat digunakan untuk pengembangan). +* Familiaritas dasar dengan stream C# dan I/O file. + +--- + +## Langkah 1: Buat custom resource handler + +Inti dari solusi adalah kelas yang mewarisi dari `Aspose.Html.ResourceHandler`. +Aspose.HTML memanggil `HandleResource` untuk setiap aset eksternal yang ditemukannya (gambar, CSS, font, dll.). Dengan mengembalikan sebuah `Stream` Anda menentukan secara tepat bagaimana aset tersebut disimpan. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Why this matters** – Tanpa custom handler, Aspose.HTML menulis sumber daya ke sistem file dalam folder sementara, yang kemudian harus Anda pindahkan ke ZIP secara manual. Handler memberikan kontrol penuh, menghilangkan file perantara, dan bekerja sama baiknya untuk binary besar ketika Anda mengganti `MemoryStream` dengan `FileStream`. + +--- + +## Langkah 2: Muat dokumen HTML + +Anda dapat memuat HTML dari string, file, atau `Stream` apa pun. Contoh di bawah menggunakan string inline untuk kesederhanaan, tetapi kode yang sama berfungsi dengan `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tip** – Jika HTML Anda merujuk ke file lokal, pastikan properti `BaseUrl` dari `HTMLDocument` menunjuk ke folder yang berisi aset tersebut. Ini membantu handler menyelesaikan URI relatif dengan benar. + +--- + +## Langkah 3: Konfigurasikan opsi penyimpanan untuk menggunakan custom handler + +`HTMLSaveOptions` memungkinkan Anda menentukan format output dan mekanisme penyimpanan. Menetapkan `OutputStorage` ke instance `MyHandler` memberi tahu Aspose.HTML untuk memanggil handler Anda untuk setiap sumber daya eksternal. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Why set `FileName`?** – Saat menyimpan sebagai ZIP, Aspose.HTML membuat kontainer yang mencakup file HTML utama (dengan nama `index.html` secara default) plus semua sumber daya. Menamai entri secara eksplisit membuat struktur ZIP dapat diprediksi, yang berguna untuk pemrosesan selanjutnya. + +--- + +## Langkah 4: Simpan dokumen ke dalam arsip ZIP + +Sekarang Anda cukup memanggil `doc.Save`, dengan memberikan jalur target dan opsi yang telah dikonfigurasi. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Hasil yang diharapkan + +Setelah program selesai, `demo.zip` berisi: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +Anda dapat membuka ZIP dengan penampil arsip apa pun untuk memverifikasi bahwa file HTML merujuk ke gambar menggunakan jalur relatif `assets/logo.png`. Membuka `index.html` di browser akan menampilkan halaman persis seperti sebelum dikemas. + +--- + +## Menangani sumber daya besar dan pertimbangan memori + +Contoh ini menggunakan `MemoryStream` untuk setiap sumber daya, yang bekerja baik untuk gambar kecil atau file CSS. Untuk aset yang lebih besar (mis., foto resolusi tinggi atau file video) Anda sebaiknya beralih ke `FileStream` untuk menghindari penggunaan memori yang berlebihan: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +Setelah `doc.Save` selesai, Anda dapat menghapus file sementara dengan mengiterasi `resource.CustomData["TempPath"]`. Pola ini memastikan **save html as zip** berfungsi andal bahkan dengan aset berukuran megabyte. + +--- + +## Menambahkan file tambahan ke ZIP (mis., README) + +Terkadang Anda ingin menggabungkan dokumentasi tambahan bersama HTML. Anda dapat melakukannya dengan menggunakan `ZipArchive` secara langsung setelah Aspose.HTML membuat arsip awal. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Sekarang arsip juga berisi `README.txt`, yang menunjukkan cara **create zip from html** sambil memperkaya dengan konten khusus. + +--- + +## Kesalahan umum dan cara menghindarinya + +| Masalah | Gejala | Solusi | +|-------|----------|-----| +| Sumber daya tidak muncul di ZIP | Hanya `index.html` yang ada; gambar tidak ada. | Pastikan `OutputStorage` diatur ke instance `MyHandler`. Verifikasi bahwa `HandleResource` mengembalikan stream yang dapat ditulis. | +| Tautan gambar rusak | Browser menampilkan “missing image” setelah mengekstrak ZIP. | `CustomData["ZipEntryName"]` harus cocok dengan jalur yang digunakan di HTML. Gunakan folder dasar yang konsisten (`assets/`) di handler. | +| Exception out‑of‑memory untuk file besar | Aplikasi crash saat memproses video 20 MB. | Beralih dari `MemoryStream` ke `FileStream` di `HandleResource`. Bersihkan file sementara setelah menyimpan. | +| File ZIP terkunci setelah dibuat | Eksekusi berikutnya gagal dengan “file in use”. | Dispose `HTMLDocument` (`doc.Dispose()`) dan objek `FileStream` apa pun sebelum membuka kembali ZIP. | + +--- + +## Contoh lengkap yang dapat dijalankan + +Berikut adalah program konsol satu file yang dapat Anda salin, tempel, dan jalankan. Program ini mencakup semua bagian yang dibahas di atas. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyHandler : ResourceHandler +{ + private readonly string _basePath; + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + entryName = Guid.NewGuid().ToString() + ".bin"; + + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + resource.CustomData["ZipEntryName"] = zipPath; + return new MemoryStream(); // replace with FileStream for large assets + } +} + +class Program +{ + static void Main() + { + // 1️⃣ HTML content (could also be loaded from a file) + string html = @" + + + + Demo + + + +

Hello, world!

+ Logo + + "; + + // 2️⃣ Load the document + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Configure the custom handler and save options + var handler = new MyHandler("assets"); + HTMLSaveOptions + + +## 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 Menyimpan HTML di C# – Panduan Lengkap Menggunakan Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Cara Meng-zip HTML di C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Simpan HTML sebagai ZIP – Tutorial C# Lengkap](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 fcf4daa304..555f5cd806 100644 --- a/html/italian/net/html-extensions-and-conversions/_index.md +++ b/html/italian/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Crea un PDF da HTML in C# con Aspose.HTML per .NET. Segui la nostra guida passo Salva HTML come archivio ZIP con Aspose.HTML per .NET. Guida passo passo per creare file ZIP contenenti HTML in C#. ### [Salva HTML in ZIP in C# – Esempio completo in memoria](./save-html-to-zip-in-c-complete-in-memory-example/) Scopri come salvare un documento HTML in un archivio ZIP interamente in memoria usando Aspose.HTML per .NET. +### [Salva HTML in ZIP con Aspose.HTML – guida completa](./save-html-to-zip-with-aspose-html-complete-guide/) +Scopri come comprimere un documento HTML in un archivio ZIP usando Aspose.HTML per .NET, con esempi passo‑passo. ## Conclusione diff --git a/html/italian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/italian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..047019767c --- /dev/null +++ b/html/italian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Salva HTML in ZIP usando Aspose.HTML e un gestore di risorse personalizzato. + Scopri come convertire HTML in ZIP, salvare HTML come ZIP e creare ZIP da HTML in + pochi passaggi. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: it +lastmod: 2026-08-09 +og_description: Salva HTML in ZIP con Aspose.HTML e un gestore di risorse personalizzato. + Questo tutorial ti mostra come convertire HTML in ZIP, salvare HTML come ZIP e creare + ZIP da HTML in modo efficiente. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Salva HTML in ZIP con Aspose.HTML – guida passo‑passo +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Salva HTML in ZIP con Aspose.HTML – guida completa +url: /it/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Salva HTML in ZIP con Aspose.HTML – guida completa + +Se hai bisogno di **salvare HTML in ZIP** rapidamente, questo tutorial ti mostra esattamente come farlo con Aspose.HTML per .NET. Entro la fine delle prime due frasi comprenderai come un **custom resource handler** ti consenta di controllare dove finisce ogni risorsa, permettendoti di **convertire HTML in ZIP**, **salvare HTML come ZIP** o **creare ZIP da HTML** con poche righe di codice. + +Percorreremo uno scenario reale: hai uno snippet HTML (o una pagina completa) e devi impacchettarlo insieme alle sue immagini, CSS e JavaScript in un unico file ZIP che può essere inviato su una rete o archiviato per un uso futuro. Nessuno strumento esterno, nessuna copia manuale di file—solo puro C# e Aspose.HTML. + +Imparerai: + +* Come implementare un `ResourceHandler` che scriva ogni risorsa in un `MemoryStream` (o in qualsiasi stream tu scelga). +* Come caricare un documento HTML da una stringa o da un file. +* Come configurare `HTMLSaveOptions` per utilizzare il tuo handler. +* Come verificare che l'archivio ZIP risultante contenga i file attesi. + +Prerequisiti + +* .NET 6.0 o successivo (il codice funziona anche con .NET Framework 4.6+). +* Una licenza valida di Aspose.HTML per .NET (la versione di prova gratuita è sufficiente per lo sviluppo). +* Familiarità di base con gli stream C# e con I/O di file. + +--- + +## Step 1: Create a custom resource handler + +Il cuore della soluzione è una classe che eredita da `Aspose.Html.ResourceHandler`. +Aspose.HTML chiama `HandleResource` per ogni risorsa esterna che incontra (immagini, CSS, font, ecc.). Restituendo uno `Stream` decidi esattamente come la risorsa viene memorizzata. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Why this matters** – Senza un handler personalizzato, Aspose.HTML scrive le risorse sul file system in una cartella temporanea, che poi devi spostare manualmente in un ZIP. L'handler ti dà il controllo totale, elimina i file intermedi e funziona altrettanto bene per binari di grandi dimensioni quando sostituisci `MemoryStream` con un `FileStream`. + +--- + +## Step 2: Load the HTML document + +Puoi caricare l'HTML da una stringa, da un file o da qualsiasi `Stream`. L'esempio qui sotto utilizza una stringa inline per semplicità, ma lo stesso codice funziona con `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tip** – Se il tuo HTML fa riferimento a file locali, assicurati che la proprietà `BaseUrl` di `HTMLDocument` punti alla cartella contenente tali risorse. Questo aiuta l'handler a risolvere correttamente gli URI relativi. + +--- + +## Step 3: Configure save options to use the custom handler + +`HTMLSaveOptions` ti consente di specificare il formato di output e il meccanismo di archiviazione. Impostando `OutputStorage` su un'istanza di `MyHandler` dici ad Aspose.HTML di invocare il tuo handler per ogni risorsa esterna. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Why set `FileName`?** – Quando si salva come ZIP, Aspose.HTML crea un contenitore che include il file HTML principale (chiamato `index.html` per impostazione predefinita) più tutte le risorse. Dare un nome esplicito all'entry rende la struttura del ZIP prevedibile, il che è utile per l'elaborazione successiva. + +--- + +## Step 4: Save the document into a ZIP archive + +Ora basta chiamare `doc.Save`, passando il percorso di destinazione e le opzioni configurate. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Expected result + +Al termine dell'esecuzione, `demo.zip` contiene: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +Puoi aprire il ZIP con qualsiasi visualizzatore di archivi per verificare che il file HTML faccia riferimento all'immagine usando il percorso relativo `assets/logo.png`. Aprendo `index.html` in un browser la pagina verrà visualizzata esattamente come prima del packaging. + +--- + +## Handling large resources and memory considerations + +L'esempio utilizza `MemoryStream` per ogni risorsa, il che funziona bene per piccole immagini o file CSS. Per risorse più grandi (ad esempio foto ad alta risoluzione o file video) dovresti passare a un `FileStream` per evitare un consumo eccessivo di memoria: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +Dopo che `doc.Save` è completato, puoi eliminare i file temporanei iterando su `resource.CustomData["TempPath"]`. Questo schema garantisce che **save html as zip** funzioni in modo affidabile anche con risorse di dimensioni megabyte. + +--- + +## Adding additional files to the ZIP (e.g., a README) + +A volte vuoi includere documentazione aggiuntiva insieme all'HTML. Puoi ottenere questo risultato usando direttamente `ZipArchive` dopo che Aspose.HTML ha creato l'archivio iniziale. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Ora l'archivio contiene anche `README.txt`, dimostrando come **create zip from html** possa essere arricchito con contenuti personalizzati. + +--- + +## Common pitfalls and how to avoid them + +| Problema | Sintomi | Soluzione | +|----------|----------|-----------| +| Le risorse non compaiono nel ZIP | È presente solo `index.html`; le immagini mancano. | Assicurati che `OutputStorage` sia impostato su un'istanza di `MyHandler`. Verifica che `HandleResource` restituisca uno stream scrivibile. | +| Link alle immagini interrotti | Il browser mostra “immagine mancante” dopo l'estrazione del ZIP. | `CustomData["ZipEntryName"]` deve corrispondere al percorso usato nell'HTML. Usa una cartella base coerente (`assets/`) nell'handler. | +| Eccezione Out‑of‑memory per file grandi | L'applicazione si arresta durante l'elaborazione di un video da 50 MB. | Passa da `MemoryStream` a `FileStream` in `HandleResource`. Pulisci i file temporanei dopo il salvataggio. | +| File ZIP bloccato dopo la creazione | Le esecuzioni successive falliscono con “file in use”. | Dispone (`Dispose`) `HTMLDocument` (`doc.Dispose()`) e tutti gli oggetti `FileStream` prima di riaprire il ZIP. | + +--- + +## Full, runnable example + +Di seguito trovi un programma console a file unico che puoi copiare, incollare ed eseguire. Include tutti i componenti discussi sopra. + + + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Save HTML as ZIP – Complete C# Tutorial](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 4110fd8e86..655c63a3c0 100644 --- a/html/japanese/net/html-extensions-and-conversions/_index.md +++ b/html/japanese/net/html-extensions-and-conversions/_index.md @@ -75,9 +75,13 @@ Aspose.HTML for .NET を使用して、HTML コンテンツを ZIP アーカイ ### [C# で HTML を Zip に圧縮する方法 – HTML を Zip に保存](./how-to-zip-html-in-c-save-html-to-zip/) C# と Aspose.HTML を使用して、HTML コンテンツを Zip アーカイブに保存する手順をステップバイステップで解説します。 + ### [C# で HTML を ZIP に保存 – 完全インメモリ例](./save-html-to-zip-in-c-complete-in-memory-example/) Aspose.HTML for .NET を使用して、HTML をメモリ内で ZIP アーカイブに保存する手順をステップバイステップで解説します。 +### [Aspose.HTML を使用して HTML を ZIP に保存する – 完全ガイド](./save-html-to-zip-with-aspose-html-complete-guide/) +Aspose.HTML for .NET を使用して、HTML を ZIP アーカイブとして保存する完全ガイドです。 + ## 結論 結論として、HTML の拡張と変換は、現代の Web 開発に不可欠な要素です。Aspose.HTML for .NET はプロセスを簡素化し、あらゆるレベルの開発者が利用できるようにします。当社のチュートリアルに従うことで、幅広いスキルを備えた熟練した Web 開発者になるための道を順調に進むことができます。 diff --git a/html/japanese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/japanese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..979de195cc --- /dev/null +++ b/html/japanese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-08-09 +description: Aspose.HTML とカスタムリソースハンドラを使用して HTML を ZIP に保存します。HTML を ZIP に変換する方法、HTML + を ZIP として保存する方法、HTML から ZIP を作成する方法を数ステップで学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: ja +lastmod: 2026-08-09 +og_description: Aspose.HTML とカスタムリソースハンドラを使用して HTML を ZIP に保存します。このチュートリアルでは、HTML + を ZIP に変換する方法、HTML を ZIP として保存する方法、そして HTML から効率的に ZIP を作成する方法を示します。 +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Aspose.HTMLでHTMLをZIPに保存する – ステップバイステップガイド +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Aspose.HTMLでHTMLをZIPに保存する完全ガイド +url: /ja/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< 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 to ZIP** quickly, this tutorial shows you exactly how to do it with Aspose.HTML for .NET. By the end of the first two sentences you’ll understand how a **custom resource handler** lets you control where each resource ends up, letting you **convert HTML to ZIP**, **save HTML as ZIP**, or **create ZIP from HTML** with just a few lines of code. + +HTMLを**ZIPに保存**したい場合、このチュートリアルではAspose.HTML for .NETを使用してその方法を正確に示します。最初の2文が終わる頃には、**カスタムリソースハンドラ**が各リソースの保存先を制御でき、数行のコードで**HTMLをZIPに変換**、**HTMLをZIPとして保存**、または**HTMLからZIPを作成**できることが理解できるでしょう。 + +We’ll walk through a real‑world scenario: you have an HTML snippet (or a full page) and you must package it together with its images, CSS, and JavaScript into a single ZIP file that can be sent over a network or stored for later use. No external tools, no manual file copying—just pure C# and Aspose.HTML. + +実際のシナリオとして、HTMLスニペット(またはフルページ)を画像、CSS、JavaScriptと共に単一のZIPファイルにパッケージ化し、ネットワーク経由で送信したり後で保存したりできるようにします。外部ツールや手動でのファイルコピーは不要で、純粋なC#とAspose.HTMLだけで実現できます。 + +You’ll learn: + +* `ResourceHandler` を実装し、各リソースを `MemoryStream`(または任意のストリーム)に書き込む方法。 +* 文字列またはファイルから HTML ドキュメントをロードする方法。 +* `HTMLSaveOptions` を設定してハンドラを使用する方法。 +* 生成された ZIP アーカイブに期待通りのファイルが含まれているか検証する方法。 + +Prerequisites + +* .NET 6.0 以降(コードは .NET Framework 4.6+ でも動作します)。 +* 有効な Aspose.HTML for .NET ライセンス(開発用には無料トライアルが利用可能)。 +* C# のストリームとファイル I/O に関する基本的な知識。 + +--- + +## Step 1: Create a custom resource handler + +The heart of the solution is a class that inherits from `Aspose.Html.ResourceHandler`. +Aspose.HTML calls `HandleResource` for every external asset it encounters (images, CSS, fonts, etc.). By returning a `Stream` you decide exactly how the asset is stored. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Why this matters** – Without a custom handler, Aspose.HTML writes resources to the file system in a temporary folder, which you then have to move into a ZIP manually. The handler gives you full control, eliminates intermediate files, and works equally well for large binaries when you replace `MemoryStream` with a `FileStream`. + +**Why this matters** – カスタムハンドラがない場合、Aspose.HTML はリソースを一時フォルダに書き込み、手動で ZIP に移動する必要があります。ハンドラを使用すれば完全に制御でき、中間ファイルを排除でき、`MemoryStream` を `FileStream` に置き換えるだけで大容量バイナリにも同様に対応できます。 + +--- + +## Step 2: Load the HTML document + +You can load HTML from a string, a file, or any `Stream`. The example below uses an inline string for simplicity, but the same code works with `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tip** – If your HTML references local files, make sure the `BaseUrl` property of `HTMLDocument` points to the folder containing those assets. This helps the handler resolve relative URIs correctly. + +**Tip** – HTML がローカルファイルを参照している場合、`HTMLDocument` の `BaseUrl` プロパティがそのアセットが格納されたフォルダを指すようにしてください。これによりハンドラが相対 URI を正しく解決できます。 + +--- + +## Step 3: Configure save options to use the custom handler + +`HTMLSaveOptions` lets you specify the output format and the storage mechanism. Setting `OutputStorage` to an instance of `MyHandler` tells Aspose.HTML to invoke your handler for every external resource. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Why set `FileName`?** – When saving as ZIP, Aspose.HTML creates a container that includes the primary HTML file (named `index.html` by default) plus all resources. Explicitly naming the entry makes the ZIP structure predictable, which is useful for downstream processing. + +**Why set `FileName`?** – ZIP として保存する際、Aspose.HTML はメインの HTML ファイル(デフォルトで `index.html`)とすべてのリソースを含むコンテナを作成します。エントリに明示的に名前を付けることで ZIP 構造が予測可能になり、後続の処理に便利です。 + +--- + +## Step 4: Save the document into a ZIP archive + +Now you simply call `doc.Save`, passing the target path and the configured options. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Expected result + +After the program finishes, `demo.zip` contains: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +You can open the ZIP with any archive viewer to verify that the HTML file references the image using the relative path `assets/logo.png`. Opening `index.html` in a browser will display the page exactly as it appeared before packaging. + +プログラム実行後、`demo.zip` には以下が含まれます。任意のアーカイブビューアで ZIP を開き、HTML ファイルが相対パス `assets/logo.png` で画像を参照していることを確認できます。ブラウザで `index.html` を開くと、パッケージ化前と同じページが表示されます。 + +--- + +## Handling large resources and memory considerations + +The example uses `MemoryStream` for every resource, which works well for small images or CSS files. For larger assets (e.g., high‑resolution photos or video files) you should switch to a `FileStream` to avoid excessive memory usage: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +After `doc.Save` completes, you can delete the temporary files by iterating over `resource.CustomData["TempPath"]`. This pattern ensures **save html as zip** works reliably even with megabyte‑size assets. + +`doc.Save` が完了したら、`resource.CustomData["TempPath"]` を走査して一時ファイルを削除できます。このパターンにより、メガバイトサイズのアセットでも **save html as zip** が確実に動作します。 + +--- + +## Adding additional files to the ZIP (e.g., a README) + +Sometimes you want to bundle extra documentation alongside the HTML. You can achieve this by using `ZipArchive` directly after Aspose.HTML creates the initial archive. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Now the archive also contains `README.txt`, demonstrating how to **create zip from html** while enriching it with custom content. + +これでアーカイブに `README.txt` も含まれ、**create zip from html** の方法を示しつつ、カスタムコンテンツで拡張できます。 + +--- + +## Common pitfalls and how to avoid them + +| Issue | Symptoms | Fix | +|-------|----------|-----| +| Resources not appearing in the ZIP | Only `index.html` is present; images are missing. | Ensure `OutputStorage` is set to an instance of `MyHandler`. Verify that `HandleResource` returns a writable stream. | +| ZIPにリソースが表示されない | `index.html` のみが存在し、画像が欠落している。 | `OutputStorage` が `MyHandler` のインスタンスに設定されていることを確認してください。`HandleResource` が書き込み可能なストリームを返すことを確認します。 | +| Broken image links | Browser shows “missing image” after extracting the ZIP. | The `CustomData["ZipEntryName"]` must match the path used in the HTML. Use a consistent base folder (`assets/`) in the handler. | +| 画像リンクが壊れる | ZIP を展開した後、ブラウザで「画像が見つかりません」と表示される。 | `CustomData["ZipEntryName"]` は HTML で使用されているパスと一致する必要があります。ハンドラで一貫したベースフォルダ(`assets/`)を使用してください。 | +| Out‑of‑memory exception for large files | Application crashes when processing a 50 MB video. | Switch from `MemoryStream` to `FileStream` in `HandleResource`. Clean up temporary files after saving. | +| 大きなファイルでメモリ不足例外 | 50 MB の動画を処理中にアプリケーションがクラッシュする。 | `HandleResource` で `MemoryStream` から `FileStream` に切り替えてください。保存後に一時ファイルをクリーンアップします。 | +| ZIP file locked after creation | Subsequent runs fail with “file in use”. | Dispose `HTMLDocument` (`doc.Dispose()`) and any `FileStream` objects before re‑opening the ZIP. | +| 作成後にZIPファイルがロックされる | その後の実行で「ファイルが使用中です」というエラーが出る。 | ZIP を再度開く前に `HTMLDocument`(`doc.Dispose()`)とすべての `FileStream` オブジェクトを破棄してください。 | + +--- + +## Full, runnable example + +Below is a single‑file console program that you can copy, paste, and run. It includes all the pieces discussed above. + + + +## 次に学ぶべきことは? + +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. + +以下のチュートリアルは、本ガイドで示した手法を基にした、密接に関連するトピックをカバーしています。各リソースには完全な動作コード例とステップバイステップの解説が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを検討するのに役立ちます。 + +- [C#でHTMLを保存する方法 – カスタムリソースハンドラを使用した完全ガイド](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [C#でHTMLをZIPにする方法 – HTMLをZIPに保存](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [HTMLをZIPとして保存 – 完全C#チュートリアル](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 38fc3bd7e6..a0397864d6 100644 --- a/html/korean/net/html-extensions-and-conversions/_index.md +++ b/html/korean/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Aspose.HTML for .NET을 사용하여 스타일이 적용된 텍스트가 포함 Aspose.HTML for .NET을 사용해 HTML을 ZIP 파일로 저장하는 전체 C# 단계별 튜토리얼. ### [C#에서 HTML을 ZIP으로 저장 – 완전 인메모리 예제](./save-html-to-zip-in-c-complete-in-memory-example/) Aspose.HTML for .NET을 사용하여 메모리 내에서 HTML을 ZIP 파일로 저장하는 방법을 단계별로 안내합니다. +### [Aspose.HTML을 사용하여 HTML을 ZIP으로 저장 – 완전 가이드](./save-html-to-zip-with-aspose-html-complete-guide/) +Aspose.HTML을 사용해 HTML을 ZIP 파일로 저장하는 전체 가이드를 확인하세요. ## 결론 diff --git a/html/korean/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/korean/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..233cd4cc9b --- /dev/null +++ b/html/korean/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,250 @@ +--- +category: general +date: 2026-08-09 +description: Aspose.HTML와 사용자 정의 리소스 핸들러를 사용하여 HTML을 ZIP으로 저장합니다. HTML을 ZIP으로 변환하고, + HTML을 ZIP으로 저장하며, HTML에서 ZIP을 만드는 방법을 몇 단계만에 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: ko +lastmod: 2026-08-09 +og_description: Aspose.HTML와 사용자 지정 리소스 핸들러를 사용하여 HTML을 ZIP으로 저장합니다. 이 튜토리얼에서는 HTML을 + ZIP으로 변환하고, HTML을 ZIP으로 저장하며, HTML에서 ZIP을 효율적으로 만드는 방법을 보여줍니다. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Aspose.HTML를 사용하여 HTML을 ZIP으로 저장하기 – 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Aspose.HTML를 사용하여 HTML을 ZIP으로 저장하기 – 완전 가이드 +url: /ko/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.HTML으로 HTML을 ZIP에 저장 – 완전 가이드 + +HTML을 **save HTML to ZIP** 해야 한다면, 이 튜토리얼에서는 Aspose.HTML for .NET을 사용하여 정확히 어떻게 하는지 보여줍니다. 처음 두 문장을 읽고 나면 **custom resource handler**가 각 리소스가 어디에 저장되는지를 제어하게 해 주어, 몇 줄의 코드만으로 **convert HTML to ZIP**, **save HTML as ZIP**, 혹은 **create ZIP from HTML**을 할 수 있다는 것을 이해하게 됩니다. + +실제 시나리오를 따라가 보겠습니다: HTML 스니펫(또는 전체 페이지)이 있고, 이를 이미지, CSS, JavaScript와 함께 하나의 ZIP 파일로 패키징해야 합니다. 이 ZIP 파일은 네트워크를 통해 전송하거나 나중에 저장할 수 있습니다. 외부 도구 없이, 수동 파일 복사 없이—순수 C#와 Aspose.HTML만 사용합니다. + +배우게 될 내용: + +* 각 리소스를 `MemoryStream`(또는 선택한 스트림)으로 쓰는 `ResourceHandler` 구현 방법 +* 문자열이나 파일에서 HTML 문서를 로드하는 방법 +* `HTMLSaveOptions`를 구성하여 핸들러를 사용하는 방법 +* 결과 ZIP 아카이브에 예상 파일이 포함되었는지 확인하는 방법 + +필수 조건 + +* .NET 6.0 이상 (코드는 .NET Framework 4.6+에서도 작동합니다). +* 유효한 Aspose.HTML for .NET 라이선스 (무료 체험판은 개발에 사용 가능). +* C# 스트림 및 파일 I/O에 대한 기본 지식 + +--- + +## Step 1: custom resource handler 만들기 + +솔루션의 핵심은 `Aspose.Html.ResourceHandler`를 상속하는 클래스입니다. Aspose.HTML은 발견한 모든 외부 자산(이미지, CSS, 폰트 등)에 대해 `HandleResource`를 호출합니다. `Stream`을 반환함으로써 자산이 정확히 어떻게 저장될지 결정할 수 있습니다. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Why this matters** – 사용자 정의 핸들러가 없으면 Aspose.HTML은 리소스를 임시 폴더에 파일 시스템으로 기록하고, 이를 수동으로 ZIP에 옮겨야 합니다. 핸들러를 사용하면 전체 제어가 가능해지고 중간 파일이 사라지며, `MemoryStream`을 `FileStream`으로 교체하면 대용량 바이너리에도 동일하게 작동합니다. + +## Step 2: HTML 문서 로드하기 + +HTML은 문자열, 파일 또는 任意의 `Stream`에서 로드할 수 있습니다. 아래 예시는 간단히 인라인 문자열을 사용하지만, 동일한 코드를 `new HTMLDocument("path/to/file.html")`와 함께 사용할 수 있습니다. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tip** – HTML이 로컬 파일을 참조하는 경우, `HTMLDocument`의 `BaseUrl` 속성이 해당 자산이 있는 폴더를 가리키도록 설정하세요. 이렇게 하면 핸들러가 상대 URI를 올바르게 해석합니다. + +## Step 3: 저장 옵션을 구성하여 custom handler 사용하기 + +`HTMLSaveOptions`를 사용하면 출력 형식과 저장 메커니즘을 지정할 수 있습니다. `OutputStorage`를 `MyHandler` 인스턴스로 설정하면 Aspose.HTML이 모든 외부 리소스에 대해 당신의 핸들러를 호출합니다. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Why set `FileName`?** – ZIP으로 저장할 때, Aspose.HTML은 기본적으로 `index.html`이라는 기본 HTML 파일과 모든 리소스를 포함하는 컨테이너를 생성합니다. 엔트리 이름을 명시적으로 지정하면 ZIP 구조가 예측 가능해져 후속 처리에 유용합니다. + +## Step 4: 문서를 ZIP 아카이브에 저장하기 + +이제 대상 경로와 구성된 옵션을 전달하여 `doc.Save`를 호출하면 됩니다. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### 예상 결과 + +프로그램이 완료되면 `demo.zip`에는 다음이 포함됩니다: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +ZIP을 任意의 압축 뷰어로 열어 HTML 파일이 이미지 `assets/logo.png`를 상대 경로로 참조하는지 확인할 수 있습니다. 브라우저에서 `index.html`을 열면 패키징 전과 동일하게 페이지가 표시됩니다. + +## 대용량 리소스 및 메모리 고려 사항 + +예제에서는 모든 리소스에 `MemoryStream`을 사용합니다. 이는 작은 이미지나 CSS 파일에 적합합니다. 대용량 자산(예: 고해상도 사진이나 비디오 파일)의 경우 과도한 메모리 사용을 피하기 위해 `FileStream`으로 전환해야 합니다: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +`doc.Save`가 완료된 후, `resource.CustomData["TempPath"]`을 순회하여 임시 파일을 삭제할 수 있습니다. 이 패턴은 **save html as zip**이 메가바이트 규모의 자산에서도 안정적으로 동작하도록 보장합니다. + +## ZIP에 추가 파일 추가하기 (예: README) + +때때로 HTML과 함께 추가 문서를 번들링하고 싶을 때가 있습니다. Aspose.HTML이 초기 아카이브를 만든 후 `ZipArchive`를 직접 사용하면 이를 구현할 수 있습니다. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +이제 아카이브에 `README.txt`도 포함되어, **create zip from html**을 수행하면서 사용자 정의 콘텐츠로 풍부하게 만드는 방법을 보여줍니다. + +## 흔히 발생하는 문제와 회피 방법 + +| 문제 | 증상 | 해결 방법 | +|------|------|-----------| +| ZIP에 리소스가 표시되지 않음 | `index.html`만 존재하고 이미지가 누락됨 | `OutputStorage`가 `MyHandler` 인스턴스로 설정되어 있는지 확인하고, `HandleResource`가 쓰기 가능한 스트림을 반환하는지 확인하세요. | +| 이미지 링크 깨짐 | ZIP을 추출한 후 브라우저에서 “이미지 없음”이 표시됨 | `CustomData["ZipEntryName"]`이 HTML에서 사용된 경로와 일치해야 합니다. 핸들러에서 일관된 기본 폴더(`assets/`)를 사용하세요. | +| 대용량 파일 처리 시 메모리 부족 예외 | 50 MB 비디오를 처리할 때 애플리케이션이 충돌함 | `HandleResource`에서 `MemoryStream`을 `FileStream`으로 교체하세요. 저장 후 임시 파일을 정리합니다. | +| 생성 후 ZIP 파일이 잠김 | 다음 실행 시 “파일 사용 중” 오류 발생 | ZIP을 다시 열기 전에 `HTMLDocument`(`doc.Dispose()`)와 모든 `FileStream` 객체를 해제하세요. | + +## 전체 실행 가능한 예제 + +아래는 복사·붙여넣기만으로 실행할 수 있는 단일 파일 콘솔 프로그램입니다. 위에서 논의한 모든 요소가 포함되어 있습니다. + + + +## 다음에 배워야 할 내용은? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 주제를 다룹니다. 각 자료에는 단계별 설명과 함께 완전한 코드 예제가 포함되어 있어 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색하는 데 도움이 됩니다. + +- [C#에서 HTML 저장하기 – 사용자 정의 Resource Handler를 이용한 완전 가이드](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [C#에서 HTML을 ZIP으로 압축하기 – HTML을 ZIP에 저장](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [HTML을 ZIP으로 저장 – 완전 C# 튜토리얼](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 5b553b0026..e7a4bbfdac 100644 --- a/html/polish/net/html-extensions-and-conversions/_index.md +++ b/html/polish/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Dowiedz się, jak stworzyć dokument HTML z formatowanym tekstem i wyeksportowa Zapisz dokument HTML jako archiwum ZIP w C# przy użyciu Aspose.HTML – kompletny przewodnik krok po kroku. ### [Zapisz HTML do ZIP w C# – Kompletny przykład w pamięci](./save-html-to-zip-in-c-complete-in-memory-example/) Zapisz dokument HTML do archiwum ZIP w pamięci przy użyciu Aspose.HTML w C#. +### [Zapisz HTML do ZIP przy użyciu Aspose.HTML – kompletny przewodnik](./save-html-to-zip-with-aspose-html-complete-guide/) +Kompletny przewodnik, jak zapisać dokument HTML jako archiwum ZIP przy użyciu Aspose.HTML w C#. ## Wniosek diff --git a/html/polish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/polish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..977212248c --- /dev/null +++ b/html/polish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Zapisz HTML do ZIP przy użyciu Aspose.HTML i własnego obsługiwacza zasobów. + Dowiedz się, jak konwertować HTML na ZIP, zapisywać HTML jako ZIP oraz tworzyć ZIP + z HTML w kilku krokach. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: pl +lastmod: 2026-08-09 +og_description: Zapisz HTML do ZIP przy użyciu Aspose.HTML i niestandardowego obsługiwacza + zasobów. Ten samouczek pokazuje, jak konwertować HTML na ZIP, zapisywać HTML jako + ZIP oraz efektywnie tworzyć ZIP z HTML. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Zapisz HTML do ZIP przy użyciu Aspose.HTML – przewodnik krok po kroku +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Zapisz HTML do ZIP przy użyciu Aspose.HTML – kompletny przewodnik +url: /pl/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Zapisz HTML do ZIP przy użyciu Aspose.HTML – kompletny przewodnik + +Jeśli potrzebujesz szybko **zapisz HTML do ZIP**, ten tutorial pokazuje dokładnie, jak to zrobić przy użyciu Aspose.HTML dla .NET. Po przeczytaniu pierwszych dwóch zdań zrozumiesz, jak **custom resource handler** pozwala kontrolować, gdzie trafia każdy zasób, umożliwiając **konwersję HTML do ZIP**, **zapis HTML jako ZIP** lub **tworzenie ZIP z HTML** przy użyciu kilku linijek kodu. + +Przejdziemy przez realistyczny scenariusz: masz fragment HTML (lub całą stronę) i musisz spakować go razem z obrazami, CSS i JavaScript w pojedynczy plik ZIP, który można przesłać przez sieć lub przechować na później. Bez zewnętrznych narzędzi, bez ręcznego kopiowania plików — tylko czysty C# i Aspose.HTML. + +Nauczysz się: + +* Jak zaimplementować `ResourceHandler`, który zapisuje każdy zasób do `MemoryStream` (lub dowolnego wybranego strumienia). +* Jak załadować dokument HTML ze stringa lub pliku. +* Jak skonfigurować `HTMLSaveOptions`, aby używał Twojego obsługiwacza. +* Jak zweryfikować, że powstałe archiwum ZIP zawiera oczekiwane pliki. + +**Wymagania wstępne** + +* .NET 6.0 lub nowszy (kod działa również z .NET Framework 4.6+). +* Ważna licencja Aspose.HTML for .NET (bezpłatna wersja próbna wystarcza do rozwoju). +* Podstawowa znajomość strumieni C# oraz operacji I/O na plikach. + +--- + +## Krok 1: Utwórz własny obsługiwacz zasobów + +Serce rozwiązania to klasa dziedzicząca po `Aspose.Html.ResourceHandler`. +Aspose.HTML wywołuje `HandleResource` dla każdego napotkanego zasobu zewnętrznego (obrazy, CSS, czcionki itp.). Zwracając `Stream`, decydujesz dokładnie, jak zasób zostanie zapisany. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Dlaczego to ważne** – Bez własnego obsługiwacza Aspose.HTML zapisuje zasoby w systemie plików w folderze tymczasowym, który trzeba potem ręcznie przenieść do ZIP. Obsługiwacz daje pełną kontrolę, eliminuje pliki pośrednie i działa równie dobrze przy dużych binariach, gdy zamienisz `MemoryStream` na `FileStream`. + +--- + +## Krok 2: Załaduj dokument HTML + +Możesz wczytać HTML ze stringa, pliku lub dowolnego `Stream`. Poniższy przykład używa wbudowanego stringa dla prostoty, ale ten sam kod działa z `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Wskazówka** – Jeśli Twój HTML odwołuje się do lokalnych plików, upewnij się, że właściwość `BaseUrl` obiektu `HTMLDocument` wskazuje na folder zawierający te zasoby. Dzięki temu obsługiwacz prawidłowo rozwiązuje względne URI. + +--- + +## Krok 3: Skonfiguruj opcje zapisu, aby używać własnego obsługiwacza + +`HTMLSaveOptions` pozwala określić format wyjściowy oraz mechanizm przechowywania. Ustawienie `OutputStorage` na instancję `MyHandler` informuje Aspose.HTML, aby wywoływał Twój obsługiwacz dla każdego zasobu zewnętrznego. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Dlaczego ustawia się `FileName`?** – Przy zapisie jako ZIP Aspose.HTML tworzy kontener, który zawiera główny plik HTML (domyślnie `index.html`) oraz wszystkie zasoby. Jawne nadanie nazwy wpisowi sprawia, że struktura ZIP jest przewidywalna, co ułatwia dalsze przetwarzanie. + +--- + +## Krok 4: Zapisz dokument do archiwum ZIP + +Teraz po prostu wywołujesz `doc.Save`, podając ścieżkę docelową i skonfigurowane opcje. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Oczekiwany wynik + +Po zakończeniu programu `demo.zip` zawiera: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +Możesz otworzyć ZIP dowolnym przeglądarką archiwów, aby zweryfikować, że plik HTML odwołuje się do obrazu przy użyciu względnej ścieżki `assets/logo.png`. Otworzenie `index.html` w przeglądarce wyświetli stronę dokładnie tak, jak wyglądała przed spakowaniem. + +--- + +## Obsługa dużych zasobów i kwestie pamięci + +Przykład używa `MemoryStream` dla każdego zasobu, co sprawdza się przy małych obrazach lub plikach CSS. Dla większych zasobów (np. zdjęcia wysokiej rozdzielczości lub pliki wideo) powinieneś przejść na `FileStream`, aby uniknąć nadmiernego zużycia pamięci: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +Po zakończeniu `doc.Save` możesz usunąć pliki tymczasowe, iterując po `resource.CustomData["TempPath"]`. Ten wzorzec zapewnia, że **save html as zip** działa niezawodnie nawet przy zasobach o rozmiarze kilku megabajtów. + +--- + +## Dodawanie dodatkowych plików do ZIP (np. README) + +Czasami chcesz dołączyć dodatkową dokumentację obok HTML. Możesz to zrobić, używając `ZipArchive` bezpośrednio po tym, jak Aspose.HTML utworzy początkowe archiwum. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Teraz archiwum zawiera także `README.txt`, demonstrując, jak **create zip from html** można wzbogacić własną treścią. + +--- + +## Częste pułapki i jak ich unikać + +| Problem | Objawy | Rozwiązanie | +|---------|--------|-------------| +| Zasoby nie pojawiają się w ZIP | Obecny jest tylko `index.html`; obrazy brakują. | Upewnij się, że `OutputStorage` jest ustawiony na instancję `MyHandler`. Zweryfikuj, że `HandleResource` zwraca strumień zapisywalny. | +| Uszkodzone linki do obrazów | Przeglądarka wyświetla „brak obrazu” po rozpakowaniu ZIP. | `CustomData["ZipEntryName"]` musi odpowiadać ścieżce użytej w HTML. Użyj spójnego folderu bazowego (`assets/`) w obsługiwaczu. | +| Wyjątek Out‑of‑memory przy dużych plikach | Aplikacja się zawiesza przy przetwarzaniu 50 MB wideo. | Zamień `MemoryStream` na `FileStream` w `HandleResource`. Usuń pliki tymczasowe po zapisaniu. | +| Plik ZIP zablokowany po utworzeniu | Kolejne uruchomienia kończą się błędem „plik w użyciu”. | Zwolnij `HTMLDocument` (`doc.Dispose()`) oraz wszystkie obiekty `FileStream` przed ponownym otwarciem ZIP. | + +--- + +## Pełny, uruchamialny przykład + +Poniżej znajduje się jednoplikowy program konsolowy, który możesz skopiować, wkleić i uruchomić. Zawiera wszystkie elementy omówione powyżej. + + + +## Co warto nauczyć się dalej? + +Poniższe tutoriale obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne, działające przykłady kodu oraz wyjaśnienia krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia w własnych projektach. + +- [Jak zapisać HTML w C# – Kompletny przewodnik z użyciem własnego obsługiwacza zasobów](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Jak spakować HTML w C# – Zapisz HTML do ZIP](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Zapisz HTML jako ZIP – Kompletny tutorial C#](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 8971d46a58..24dd3f3e38 100644 --- a/html/portuguese/net/html-extensions-and-conversions/_index.md +++ b/html/portuguese/net/html-extensions-and-conversions/_index.md @@ -72,7 +72,8 @@ Aprenda como converter HTML para TIFF com Aspose.HTML para .NET. Siga nosso guia Descubra o poder do Aspose.HTML para .NET: Converta HTML para XPS sem esforço. Pré-requisitos, guia passo a passo e FAQs inclusos. ### [Salvar HTML como ZIP – Tutorial Completo em C#](./save-html-as-zip-complete-c-tutorial/) Aprenda a salvar documentos HTML em arquivos ZIP usando Aspose.HTML para .NET com um tutorial passo a passo em C#. - +### [Salvar HTML em ZIP com Aspose.HTML – guia completo](./save-html-to-zip-with-aspose-html-complete-guide/) +Aprenda a salvar documentos HTML em arquivos ZIP usando Aspose.HTML para .NET com um guia passo a passo completo. ### [Como compactar HTML em C# – Salvar HTML em ZIP](./how-to-zip-html-in-c-save-html-to-zip/) Aprenda a criar um arquivo ZIP contendo arquivos HTML usando Aspose.HTML para .NET em C#. ### [Salvar HTML em ZIP em C# – Exemplo Completo em Memória](./save-html-to-zip-in-c-complete-in-memory-example/) diff --git a/html/portuguese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/portuguese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..22722d2fe9 --- /dev/null +++ b/html/portuguese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Salvar HTML em ZIP usando Aspose.HTML e um manipulador de recursos personalizado. + Aprenda como converter HTML em ZIP, salvar HTML como ZIP e criar ZIP a partir de + HTML em poucos passos. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: pt +lastmod: 2026-08-09 +og_description: Salve HTML em ZIP com Aspose.HTML e um manipulador de recursos personalizado. + Este tutorial mostra como converter HTML para ZIP, salvar HTML como ZIP e criar + ZIP a partir de HTML de forma eficiente. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Salvar HTML em ZIP com Aspose.HTML – guia passo a passo +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Salvar HTML em ZIP com Aspose.HTML – guia completo +url: /pt/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Salvar HTML em ZIP com Aspose.HTML – guia completo + +Se você precisa **salvar HTML em ZIP** rapidamente, este tutorial mostra exatamente como fazer isso com Aspose.HTML para .NET. Ao final das duas primeiras frases, você entenderá como um **custom resource handler** permite controlar onde cada recurso termina, permitindo **converter HTML em ZIP**, **salvar HTML como ZIP**, ou **criar ZIP a partir de HTML** com apenas algumas linhas de código. + +Vamos percorrer um cenário do mundo real: você tem um trecho de HTML (ou uma página completa) e precisa empacotá‑lo junto com suas imagens, CSS e JavaScript em um único arquivo ZIP que pode ser enviado pela rede ou armazenado para uso futuro. Sem ferramentas externas, sem cópia manual de arquivos — apenas C# puro e Aspose.HTML. + +Você aprenderá: + +* Como implementar um `ResourceHandler` que grava cada recurso em um `MemoryStream` (ou qualquer stream que você escolher). +* Como carregar um documento HTML a partir de uma string ou de um arquivo. +* Como configurar `HTMLSaveOptions` para usar seu handler. +* Como verificar se o arquivo ZIP resultante contém os arquivos esperados. + +## Pré‑requisitos + +* .NET 6.0 ou superior (o código também funciona com .NET Framework 4.6+). +* Uma licença válida do Aspose.HTML for .NET (a versão de avaliação gratuita funciona para desenvolvimento). +* Familiaridade básica com streams C# e I/O de arquivos. + +--- + +## Step 1: Create a custom resource handler + +O coração da solução é uma classe que herda de `Aspose.Html.ResourceHandler`. +Aspose.HTML chama `HandleResource` para cada recurso externo que encontra (imagens, CSS, fontes, etc.). Ao retornar um `Stream` você decide exatamente como o recurso será armazenado. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Why this matters** – Sem um handler personalizado, Aspose.HTML grava recursos no sistema de arquivos em uma pasta temporária, que então você precisa mover manualmente para um ZIP. O handler lhe dá controle total, elimina arquivos intermediários e funciona igualmente bem para binários grandes quando você substitui `MemoryStream` por um `FileStream`. + +--- + +## Step 2: Load the HTML document + +Você pode carregar HTML a partir de uma string, de um arquivo ou de qualquer `Stream`. O exemplo abaixo usa uma string embutida por simplicidade, mas o mesmo código funciona com `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tip** – Se seu HTML referencia arquivos locais, certifique‑se de que a propriedade `BaseUrl` de `HTMLDocument` aponta para a pasta que contém esses recursos. Isso ajuda o handler a resolver URIs relativos corretamente. + +--- + +## Step 3: Configure save options to use the custom handler + +`HTMLSaveOptions` permite especificar o formato de saída e o mecanismo de armazenamento. Definir `OutputStorage` como uma instância de `MyHandler` indica ao Aspose.HTML que ele deve invocar seu handler para cada recurso externo. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Why set `FileName`?** – Ao salvar como ZIP, Aspose.HTML cria um contêiner que inclui o arquivo HTML principal (nomeado `index.html` por padrão) mais todos os recursos. Nomear explicitamente a entrada torna a estrutura do ZIP previsível, o que é útil para processamento posterior. + +--- + +## Step 4: Save the document into a ZIP archive + +Agora você simplesmente chama `doc.Save`, passando o caminho de destino e as opções configuradas. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Expected result + +Após a conclusão do programa, `demo.zip` contém: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +Você pode abrir o ZIP com qualquer visualizador de arquivos para verificar que o arquivo HTML referencia a imagem usando o caminho relativo `assets/logo.png`. Abrir `index.html` em um navegador exibirá a página exatamente como aparecia antes da embalagem. + +--- + +## Handling large resources and memory considerations + +O exemplo usa `MemoryStream` para cada recurso, o que funciona bem para imagens pequenas ou arquivos CSS. Para ativos maiores (por exemplo, fotos de alta resolução ou arquivos de vídeo) você deve mudar para um `FileStream` a fim de evitar uso excessivo de memória: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +Depois que `doc.Save` for concluído, você pode excluir os arquivos temporários iterando sobre `resource.CustomData["TempPath"]`. Esse padrão garante que **save html as zip** funcione de forma confiável mesmo com ativos de tamanho em megabytes. + +--- + +## Adding additional files to the ZIP (e.g., a README) + +Às vezes você quer agrupar documentação extra junto ao HTML. Isso pode ser feito usando `ZipArchive` diretamente após o Aspose.HTML criar o arquivo inicial. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Agora o arquivo também contém `README.txt`, demonstrando como **create zip from html** enquanto o enriquece com conteúdo personalizado. + +--- + +## Common pitfalls and how to avoid them + +| Issue | Symptoms | Fix | +|-------|----------|-----| +| Resources not appearing in the ZIP | Only `index.html` is present; images are missing. | Ensure `OutputStorage` is set to an instance of `MyHandler`. Verify that `HandleResource` returns a writable stream. | +| Broken image links | Browser shows “missing image” after extracting the ZIP. | The `CustomData["ZipEntryName"]` must match the path used in the HTML. Use a consistent base folder (`assets/`) in the handler. | +| Out‑of‑memory exception for large files | Application crashes when processing a 50 MB video. | Switch from `MemoryStream` to `FileStream` in `HandleResource`. Clean up temporary files after saving. | +| ZIP file locked after creation | Subsequent runs fail with “file in use”. | Dispose `HTMLDocument` (`doc.Dispose()`) and any `FileStream` objects before re‑opening the ZIP. | + +--- + +## Full, runnable example + +Abaixo está um programa de console de arquivo único que você pode copiar, colar e executar. Ele inclui todas as partes discutidas acima. + + + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que expandem as 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 alternativas de implementação em seus próprios projetos. + +- [Como salvar HTML em C# – Guia completo usando um Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Como compactar HTML em C# – Salvar HTML em Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Salvar HTML como ZIP – Tutorial completo em C#](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 00354e6733..ac3337c946 100644 --- a/html/russian/net/html-extensions-and-conversions/_index.md +++ b/html/russian/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Aspose.HTML для .NET — это не просто библиотека; эт Узнайте, как сохранить HTML‑страницу в архив ZIP с помощью Aspose.HTML для .NET, используя C# в полном пошаговом руководстве. ### [Сохраните HTML в ZIP в C# – Полный пример в памяти](./save-html-to-zip-in-c-complete-in-memory-example/) Сохраните HTML в архив ZIP полностью в памяти с помощью Aspose.HTML для .NET, используя C#. +### [Сохранить HTML в ZIP с Aspose.HTML – полное руководство](./save-html-to-zip-with-aspose-html-complete-guide/) +Полное руководство по сохранению HTML в ZIP‑архив с использованием Aspose.HTML для .NET. ## Заключение diff --git a/html/russian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/russian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..e27be71424 --- /dev/null +++ b/html/russian/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Сохранить HTML в ZIP с помощью Aspose.HTML и пользовательского обработчика + ресурсов. Узнайте, как преобразовать HTML в ZIP, сохранить HTML как ZIP и создать + ZIP из HTML за несколько шагов. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: ru +lastmod: 2026-08-09 +og_description: Сохраните HTML в ZIP с помощью Aspose.HTML и пользовательского обработчика + ресурсов. Этот учебник покажет, как конвертировать HTML в ZIP, сохранять HTML в + виде ZIP и эффективно создавать ZIP из HTML. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Сохранение HTML в ZIP с помощью Aspose.HTML – пошаговое руководство +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Сохранение HTML в ZIP с помощью Aspose.HTML – полное руководство +url: /ru/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< 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 в ZIP**, **сохранять HTML как ZIP** или **создавать ZIP из HTML** всего несколькими строками кода. + +Мы пройдём реальный сценарий: у вас есть фрагмент HTML (или полная страница), и вам нужно упаковать его вместе с изображениями, CSS и JavaScript в один ZIP‑файл, который можно отправить по сети или сохранить для последующего использования. Никаких внешних инструментов, без ручного копирования файлов — только чистый C# и Aspose.HTML. + +Вы узнаете: + +* Как реализовать `ResourceHandler`, который записывает каждый ресурс в `MemoryStream` (или любой другой поток, который вы выберете). +* Как загрузить HTML‑документ из строки или файла. +* Как настроить `HTMLSaveOptions` для использования вашего обработчика. +* Как проверить, что полученный ZIP‑архив содержит ожидаемые файлы. + +## Предварительные требования + +* .NET 6.0 или новее (код также работает с .NET Framework 4.6+). +* Действительная лицензия Aspose.HTML for .NET (бесплатная пробная версия подходит для разработки). +* Базовые знания о потоках C# и работе с файлами. + +--- + +## Шаг 1: Создать пользовательский обработчик ресурсов + +Сердцем решения является класс, наследующий `Aspose.Html.ResourceHandler`. +Aspose.HTML вызывает `HandleResource` для каждого внешнего ресурса, который он встречает (изображения, CSS, шрифты и т.д.). Возвращая `Stream`, вы точно определяете, как ресурс будет сохранён. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Почему это важно** – Без пользовательского обработчика Aspose.HTML записывает ресурсы в файловую систему во временную папку, после чего их нужно вручную перемещать в ZIP. Обработчик даёт полный контроль, устраняет промежуточные файлы и одинаково хорошо работает с большими бинарными данными, если заменить `MemoryStream` на `FileStream`. + +--- + +## Шаг 2: Загрузить HTML‑документ + +HTML можно загрузить из строки, файла или любого `Stream`. В примере ниже используется встроенная строка для простоты, но тот же код работает с `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Подсказка** – Если ваш HTML ссылается на локальные файлы, убедитесь, что свойство `BaseUrl` у `HTMLDocument` указывает на папку, содержащую эти ресурсы. Это помогает обработчику правильно разрешать относительные URI. + +--- + +## Шаг 3: Настроить параметры сохранения для использования пользовательского обработчика + +`HTMLSaveOptions` позволяет задать формат вывода и механизм хранения. Установка `OutputStorage` в экземпляр `MyHandler` заставляет Aspose.HTML вызывать ваш обработчик для каждого внешнего ресурса. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Зачем задавать `FileName`?** – При сохранении в ZIP Aspose.HTML создаёт контейнер, включающий основной HTML‑файл (по умолчанию `index.html`) и все ресурсы. Явное указание имени записи делает структуру ZIP предсказуемой, что полезно для последующей обработки. + +--- + +## Шаг 4: Сохранить документ в ZIP‑архив + +Теперь просто вызовите `doc.Save`, передав путь назначения и настроенные параметры. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Ожидаемый результат + +После завершения программы `demo.zip` содержит: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +Вы можете открыть ZIP любой программой‑архиватором, чтобы убедиться, что HTML‑файл ссылается на изображение по относительному пути `assets/logo.png`. Открытие `index.html` в браузере отобразит страницу точно так же, как до упаковки. + +--- + +## Обработка больших ресурсов и соображения по памяти + +В примере для каждого ресурса используется `MemoryStream`, что подходит для небольших изображений или CSS‑файлов. Для более крупных ресурсов (например, фото высокого разрешения или видеофайлов) следует переключиться на `FileStream`, чтобы избежать чрезмерного потребления памяти: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +После завершения `doc.Save` вы можете удалить временные файлы, пройдясь по `resource.CustomData["TempPath"]`. Такой подход гарантирует надёжную работу **save html as zip** даже с ресурсами размером в мегабайты. + +--- + +## Добавление дополнительных файлов в ZIP (например, README) + +Иногда требуется добавить дополнительную документацию рядом с HTML. Это можно сделать, используя `ZipArchive` напрямую после того, как Aspose.HTML создаст начальный архив. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Теперь архив также содержит `README.txt`, демонстрируя, как **create zip from html** и одновременно обогащать его пользовательским содержимым. + +--- + +## Распространённые подводные камни и как их избежать + +| Проблема | Симптомы | Решение | +|----------|----------|----------| +| Ресурсы не попадают в ZIP | В архиве только `index.html`; изображения отсутствуют. | Убедитесь, что `OutputStorage` установлен в экземпляр `MyHandler`. Проверьте, что `HandleResource` возвращает поток с правом записи. | +| Сломанные ссылки на изображения | Браузер показывает «изображение отсутствует» после извлечения ZIP. | `CustomData["ZipEntryName"]` должно совпадать с путём, используемым в HTML. Используйте единый базовый каталог (`assets/`) в обработчике. | +| Исключение Out‑of‑memory для больших файлов | Приложение падает при обработке 50 МБ видео. | Перейдите с `MemoryStream` на `FileStream` в `HandleResource`. Очистите временные файлы после сохранения. | +| ZIP‑файл заблокирован после создания | Последующие запуски завершаются ошибкой «файл используется». | Вызовите `Dispose` у `HTMLDocument` (`doc.Dispose()`) и у всех объектов `FileStream` перед повторным открытием ZIP. | + +--- + +## Полный, готовый к запуску пример + +Ниже приведена одностраничная консольная программа, которую можно скопировать, вставить и запустить. В ней собраны все обсуждаемые части. + + + +## Что изучать дальше? + +Следующие учебники охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [Как сохранить HTML в C# – полное руководство с пользовательским обработчиком ресурсов](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Как упаковать HTML в ZIP в C# – сохранить HTML в ZIP](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Сохранить HTML как ZIP – полное руководство на C#](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 58e38eec45..4609fbc160 100644 --- a/html/spanish/net/html-extensions-and-conversions/_index.md +++ b/html/spanish/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Descubra el poder de Aspose.HTML para .NET: convierta HTML a XPS sin esfuerzo. R Aprenda a empaquetar archivos HTML en un archivo ZIP usando C# y Aspose.HTML. Guía paso a paso con ejemplos de código. ### [Guardar HTML en ZIP en C# – Ejemplo completo en memoria](./save-html-to-zip-in-c-complete-in-memory-example/) Aprenda a guardar HTML en un archivo ZIP usando C# con un ejemplo completo en memoria. +### [Guardar HTML en ZIP con Aspose.HTML – guía completa](./save-html-to-zip-with-aspose-html-complete-guide/) +Aprenda a guardar HTML en un archivo ZIP usando Aspose.HTML para .NET con una guía paso a paso. ## Conclusión diff --git a/html/spanish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/spanish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..9c640a597c --- /dev/null +++ b/html/spanish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Guardar HTML en ZIP usando Aspose.HTML y un controlador de recursos personalizado. + Aprende cómo convertir HTML a ZIP, guardar HTML como ZIP y crear ZIP a partir de + HTML en unos pocos pasos. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: es +lastmod: 2026-08-09 +og_description: Guarda HTML en ZIP con Aspose.HTML y un controlador de recursos personalizado. + Este tutorial muestra cómo convertir HTML a ZIP, guardar HTML como ZIP y crear ZIP + a partir de HTML de manera eficiente. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Guardar HTML en ZIP con Aspose.HTML – guía paso a paso +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Guardar HTML en ZIP con Aspose.HTML – guía completa +url: /es/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Guardar HTML en ZIP con Aspose.HTML – guía completa + +Si necesitas **guardar HTML en ZIP** rápidamente, este tutorial te muestra exactamente cómo hacerlo con Aspose.HTML para .NET. Al final de las dos primeras frases entenderás cómo un **custom resource handler** te permite controlar dónde termina cada recurso, permitiéndote **convertir HTML a ZIP**, **guardar HTML como ZIP**, o **crear ZIP a partir de HTML** con solo unas pocas líneas de código. + +Recorreremos un escenario del mundo real: tienes un fragmento de HTML (o una página completa) y debes empaquetarlo junto con sus imágenes, CSS y JavaScript en un único archivo ZIP que pueda enviarse a través de una red o almacenarse para uso posterior. Sin herramientas externas, sin copiar archivos manualmente—solo C# puro y Aspose.HTML. + +Aprenderás: + +* Cómo implementar un `ResourceHandler` que escriba cada recurso en un `MemoryStream` (o cualquier stream que elijas). +* Cómo cargar un documento HTML desde una cadena o un archivo. +* Cómo configurar `HTMLSaveOptions` para usar tu handler. +* Cómo verificar que el archivo ZIP resultante contiene los archivos esperados. + +Requisitos previos + +* .NET 6.0 o posterior (el código también funciona con .NET Framework 4.6+). +* Una licencia válida de Aspose.HTML para .NET (la prueba gratuita funciona para desarrollo). +* Familiaridad básica con streams de C# y operaciones de archivo I/O. + +--- + +## Paso 1: Crear un manejador de recursos personalizado + +El núcleo de la solución es una clase que hereda de `Aspose.Html.ResourceHandler`. +Aspose.HTML llama a `HandleResource` para cada recurso externo que encuentra (imágenes, CSS, fuentes, etc.). Al devolver un `Stream` decides exactamente cómo se almacena el recurso. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Por qué es importante** – Sin un handler personalizado, Aspose.HTML escribe los recursos en el sistema de archivos en una carpeta temporal, que luego debes mover manualmente a un ZIP. El handler te brinda control total, elimina archivos intermedios y funciona igual de bien con binarios grandes cuando reemplazas `MemoryStream` por un `FileStream`. + +--- + +## Paso 2: Cargar el documento HTML + +Puedes cargar HTML desde una cadena, un archivo o cualquier `Stream`. El ejemplo a continuación usa una cadena en línea por simplicidad, pero el mismo código funciona con `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Consejo** – Si tu HTML hace referencia a archivos locales, asegúrate de que la propiedad `BaseUrl` de `HTMLDocument` apunte a la carpeta que contiene esos recursos. Esto ayuda al handler a resolver correctamente los URI relativos. + +--- + +## Paso 3: Configurar las opciones de guardado para usar el handler personalizado + +`HTMLSaveOptions` te permite especificar el formato de salida y el mecanismo de almacenamiento. Configurar `OutputStorage` con una instancia de `MyHandler` indica a Aspose.HTML que invoque tu handler para cada recurso externo. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**¿Por qué establecer `FileName`?** – Al guardar como ZIP, Aspose.HTML crea un contenedor que incluye el archivo HTML principal (llamado `index.html` por defecto) más todos los recursos. Nombrar explícitamente la entrada hace que la estructura del ZIP sea predecible, lo cual es útil para el procesamiento posterior. + +--- + +## Paso 4: Guardar el documento en un archivo ZIP + +Ahora simplemente llamas a `doc.Save`, pasando la ruta de destino y las opciones configuradas. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Resultado esperado + +Después de que el programa termine, `demo.zip` contiene: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +Puedes abrir el ZIP con cualquier visor de archivos para verificar que el archivo HTML hace referencia a la imagen usando la ruta relativa `assets/logo.png`. Abrir `index.html` en un navegador mostrará la página exactamente como aparecía antes del empaquetado. + +--- + +## Manejo de recursos grandes y consideraciones de memoria + +El ejemplo usa `MemoryStream` para cada recurso, lo que funciona bien para imágenes pequeñas o archivos CSS. Para recursos más grandes (p. ej., fotos de alta resolución o archivos de video) deberías cambiar a un `FileStream` para evitar un uso excesivo de memoria: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +Después de que `doc.Save` finalice, puedes eliminar los archivos temporales iterando sobre `resource.CustomData["TempPath"]`. Este patrón asegura que **save html as zip** funcione de manera fiable incluso con recursos de varios megabytes. + +--- + +## Añadiendo archivos adicionales al ZIP (p. ej., un README) + +A veces deseas empaquetar documentación adicional junto con el HTML. Puedes lograrlo usando `ZipArchive` directamente después de que Aspose.HTML cree el archivo inicial. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Ahora el archivo también contiene `README.txt`, demostrando cómo **create zip from html** mientras lo enriquece con contenido personalizado. + +--- + +## Problemas comunes y cómo evitarlos + +| Problema | Síntomas | Solución | +|----------|----------|----------| +| Los recursos no aparecen en el ZIP | Solo `index.html` está presente; faltan imágenes. | Asegúrate de que `OutputStorage` esté configurado con una instancia de `MyHandler`. Verifica que `HandleResource` devuelva un stream escribible. | +| Enlaces de imagen rotos | El navegador muestra “imagen faltante” después de extraer el ZIP. | El `CustomData["ZipEntryName"]` debe coincidir con la ruta usada en el HTML. Usa una carpeta base consistente (`assets/`) en el handler. | +| Excepción de falta de memoria para archivos grandes | La aplicación se bloquea al procesar un video de 50 MB. | Cambia de `MemoryStream` a `FileStream` en `HandleResource`. Elimina los archivos temporales después de guardar. | +| Archivo ZIP bloqueado después de la creación | Ejecuciones posteriores fallan con “archivo en uso”. | Descarta `HTMLDocument` (`doc.Dispose()`) y cualquier objeto `FileStream` antes de volver a abrir el ZIP. | + +--- + +## Ejemplo completo y ejecutable + +A continuación se muestra un programa de consola de un solo archivo que puedes copiar, pegar y ejecutar. Incluye todas las piezas discutidas arriba. + + + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Cómo guardar HTML en C# – Guía completa usando un Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [Cómo comprimir HTML en C# – Guardar HTML en Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Guardar HTML como ZIP – Tutorial completo en C#](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 6d01c9b961..bff93b43d9 100644 --- a/html/swedish/net/html-extensions-and-conversions/_index.md +++ b/html/swedish/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Skapa PDF från HTML med C# och Aspose.HTML för .NET. Följ vår steg‑för‑ Lär dig hur du sparar HTML som en ZIP-fil med en komplett C#-kodexempel och steg-för-steg-instruktioner. ### [Spara HTML till ZIP i C# – Komplett minnesexempel](./save-html-to-zip-in-c-complete-in-memory-example/) Lär dig hur du sparar HTML-filer i ett ZIP‑arkiv i minnet med C# och Aspose.HTML. +### [Spara HTML till ZIP med Aspose.HTML – komplett guide](./save-html-to-zip-with-aspose-html-complete-guide/) +Lär dig steg för steg hur du sparar HTML-filer i ett ZIP‑arkiv med Aspose.HTML för .NET i en komplett guide. ## Slutsats diff --git a/html/swedish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/swedish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..e4b973d303 --- /dev/null +++ b/html/swedish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,318 @@ +--- +category: general +date: 2026-08-09 +description: Spara HTML till ZIP med Aspose.HTML och en anpassad resurs‑hanterare. + Lär dig hur du konverterar HTML till ZIP, sparar HTML som ZIP och skapar ZIP från + HTML på några få steg. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: sv +lastmod: 2026-08-09 +og_description: Spara HTML till ZIP med Aspose.HTML och en anpassad resurshanterare. + Denna handledning visar hur du konverterar HTML till ZIP, sparar HTML som ZIP och + skapar ZIP från HTML på ett effektivt sätt. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Spara HTML till ZIP med Aspose.HTML – steg‑för‑steg‑guide +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Spara HTML till ZIP med Aspose.HTML – komplett guide +url: /sv/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Spara HTML till ZIP med Aspose.HTML – komplett guide + +Om du snabbt behöver **spara HTML till ZIP**, visar den här handledningen exakt hur du gör det med Aspose.HTML för .NET. Efter de två första meningarna kommer du att förstå hur en **custom resource handler** låter dig styra var varje resurs hamnar, så att du kan **convert HTML to ZIP**, **save HTML as ZIP**, eller **create ZIP from HTML** med bara några rader kod. + +Vi går igenom ett verkligt scenario: du har ett HTML‑snutt (eller en hel sida) och du måste paketera den tillsammans med dess bilder, CSS och JavaScript i en enda ZIP‑fil som kan skickas över ett nätverk eller lagras för senare bruk. Inga externa verktyg, ingen manuell filkopiering – bara ren C# och Aspose.HTML. + +Du kommer att lära dig: + +* Hur du implementerar en `ResourceHandler` som skriver varje resurs till en `MemoryStream` (eller någon annan ström du väljer). +* Hur du laddar ett HTML‑dokument från en sträng eller en fil. +* Hur du konfigurerar `HTMLSaveOptions` för att använda din handler. +* Hur du verifierar att den resulterande ZIP‑arkivet innehåller de förväntade filerna. + +## Förutsättningar + +* .NET 6.0 eller senare (koden fungerar också med .NET Framework 4.6+). +* En giltig Aspose.HTML för .NET‑licens (gratis provversion fungerar för utveckling). +* Grundläggande kunskap om C#‑strömmar och fil‑I/O. + +--- + +## Steg 1: Skapa en anpassad resource handler + +Kärnan i lösningen är en klass som ärver från `Aspose.Html.ResourceHandler`. +Aspose.HTML anropar `HandleResource` för varje extern resurs den stöter på (bilder, CSS, teckensnitt osv.). Genom att returnera en `Stream` bestämmer du exakt hur resursen lagras. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Varför detta är viktigt** – Utan en anpassad handler skriver Aspose.HTML resurser till filsystemet i en temporär mapp, som du sedan måste flytta in i en ZIP manuellt. Handlern ger dig full kontroll, eliminerar mellanfiler och fungerar lika bra för stora binärfiler när du ersätter `MemoryStream` med en `FileStream`. + +--- + +## Steg 2: Ladda HTML‑dokumentet + +Du kan ladda HTML från en sträng, en fil eller någon `Stream`. Exemplet nedan använder en inbäddad sträng för enkelhetens skull, men samma kod fungerar med `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tips** – Om ditt HTML refererar till lokala filer, se till att `BaseUrl`‑egenskapen på `HTMLDocument` pekar på mappen som innehåller dessa resurser. Detta hjälper handlern att lösa relativa URI:er korrekt. + +--- + +## Steg 3: Konfigurera spara‑alternativ för att använda den anpassade handlern + +`HTMLSaveOptions` låter dig ange utdataformatet och lagringsmekanismen. Genom att sätta `OutputStorage` till en instans av `MyHandler` instruerar du Aspose.HTML att anropa din handler för varje extern resurs. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Varför sätta `FileName`?** – Vid sparande som ZIP skapar Aspose.HTML en behållare som inkluderar huvud‑HTML‑filen (namngiven `index.html` som standard) plus alla resurser. Att explicit namnge posten gör ZIP‑strukturen förutsägbar, vilket är användbart för efterföljande bearbetning. + +--- + +## Steg 4: Spara dokumentet i ett ZIP‑arkiv + +Nu anropar du helt enkelt `doc.Save`, och skickar in mål‑sökvägen samt de konfigurerade alternativen. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Förväntat resultat + +När programmet är klart innehåller `demo.zip`: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +Du kan öppna ZIP‑filen med vilken arkivvisare som helst för att verifiera att HTML‑filen refererar till bilden med den relativa sökvägen `assets/logo.png`. Att öppna `index.html` i en webbläsare visar sidan exakt som den såg ut innan paketeringen. + +--- + +## Hantera stora resurser och minnesaspekter + +Exemplet använder `MemoryStream` för varje resurs, vilket fungerar bra för små bilder eller CSS‑filer. För större tillgångar (t.ex. högupplösta foton eller videofiler) bör du byta till en `FileStream` för att undvika överdrivet minnesbruk: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +Efter att `doc.Save` har slutförts kan du radera de temporära filerna genom att iterera över `resource.CustomData["TempPath"]`. Detta mönster säkerställer att **save html as zip** fungerar pålitligt även med megabyte‑stora resurser. + +--- + +## Lägg till extra filer i ZIP‑en (t.ex. en README) + +Ibland vill du paketera extra dokumentation tillsammans med HTML‑filen. Detta kan du göra genom att använda `ZipArchive` direkt efter att Aspose.HTML har skapat det initiala arkivet. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Nu innehåller arkivet också `README.txt`, vilket demonstrerar hur man **create zip from html** samtidigt som man berikar det med anpassat innehåll. + +--- + +## Vanliga fallgropar och hur du undviker dem + +| Problem | Symptom | Lösning | +|---------|---------|---------| +| Resurser saknas i ZIP‑en | Endast `index.html` finns; bilder saknas. | Se till att `OutputStorage` är satt till en instans av `MyHandler`. Verifiera att `HandleResource` returnerar en skrivbar ström. | +| Trasiga bildlänkar | Webbläsaren visar “missing image” efter att ZIP‑en har extraherats. | `CustomData["ZipEntryName"]` måste matcha sökvägen som används i HTML. Använd en konsekvent basmapp (`assets/`) i handlern. | +| Out‑of‑memory‑undantag för stora filer | Applikationen kraschar när den bearbetar en 50 MB video. | Byt från `MemoryStream` till `FileStream` i `HandleResource`. Rensa temporära filer efter sparandet. | +| ZIP‑fil låst efter skapande | Efterföljande körningar misslyckas med “file in use”. | Dispose `HTMLDocument` (`doc.Dispose()`) och alla `FileStream`‑objekt innan ZIP‑en öppnas igen. | + +--- + +## Fullt, körbart exempel + +Nedan är ett enkel‑filskonsolprogram som du kan kopiera, klistra in och köra. Det innehåller alla delar som diskuterats ovan. + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyHandler : ResourceHandler +{ + private readonly string _basePath; + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + entryName = Guid.NewGuid().ToString() + ".bin"; + + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + resource.CustomData["ZipEntryName"] = zipPath; + return new MemoryStream(); // replace with FileStream for large assets + } +} + +class Program +{ + static void Main() + { + // 1️⃣ HTML content (could also be loaded from a file) + string html = @" + + + + Demo + + + +

Hello, world!

+ Logo + + "; + + // 2️⃣ Load the document + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Configure the custom handler and save options + var handler = new MyHandler("assets"); + HTMLSaveOptions + + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närliggande ämnen som bygger på teknikerna som demonstrerats i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Save HTML as ZIP – Complete C# Tutorial](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 2474ca32c0..415a9a0b2d 100644 --- a/html/thai/net/html-extensions-and-conversions/_index.md +++ b/html/thai/net/html-extensions-and-conversions/_index.md @@ -73,6 +73,8 @@ Aspose.HTML สำหรับ .NET ไม่ใช่แค่ไลบรา บันทึกไฟล์ HTML เป็น ZIP อย่างครบถ้วนด้วย C# ตามขั้นตอนของเรา ### [บันทึก HTML เป็น ZIP ใน C# – ตัวอย่างทำงานในหน่วยความจำเต็มรูปแบบ](./save-html-to-zip-in-c-complete-in-memory-example/) บันทึกไฟล์ HTML เป็นไฟล์ ZIP โดยใช้ C# ด้วยตัวอย่างทำงานในหน่วยความจำเต็มรูปแบบ +### [บันทึก HTML เป็น ZIP ด้วย Aspose.HTML – คู่มือเต็ม](./save-html-to-zip-with-aspose-html-complete-guide/) +เรียนรู้วิธีบันทึกไฟล์ HTML เป็นไฟล์ ZIP อย่างครบถ้วนด้วย Aspose.HTML สำหรับ .NET พร้อมตัวอย่างโค้ดและขั้นตอนละเอียด ## บทสรุป diff --git a/html/thai/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/thai/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..780702b422 --- /dev/null +++ b/html/thai/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-08-09 +description: บันทึก HTML เป็น ZIP ด้วย Aspose.HTML และตัวจัดการทรัพยากรแบบกำหนดเอง + เรียนรู้วิธีแปลง HTML เป็น ZIP, บันทึก HTML เป็น ZIP, และสร้าง ZIP จาก HTMLในไม่กี่ขั้นตอน. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: th +lastmod: 2026-08-09 +og_description: บันทึก HTML เป็น ZIP ด้วย Aspose.HTML และตัวจัดการทรัพยากรแบบกำหนดเอง + บทเรียนนี้จะแสดงวิธีแปลง HTML เป็น ZIP, บันทึก HTML เป็น ZIP, และสร้าง ZIP จาก HTML + อย่างมีประสิทธิภาพ +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: บันทึก HTML เป็น ZIP ด้วย Aspose.HTML – คู่มือทีละขั้นตอน +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: บันทึก HTML เป็น ZIP ด้วย Aspose.HTML – คู่มือฉบับสมบูรณ์ +url: /th/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< 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. ภายในสองประโยคแรกคุณจะเข้าใจว่า **custom resource handler** ทำให้คุณควบคุมว่าทรัพยากรแต่ละรายการจะถูกเก็บไว้ที่ไหน ทำให้คุณสามารถ **convert HTML to ZIP**, **save HTML as ZIP**, หรือ **create ZIP from HTML** ได้ด้วยเพียงไม่กี่บรรทัดของโค้ด. + +เราจะเดินผ่านสถานการณ์จริง: คุณมีส่วนของ HTML (หรือหน้าเต็ม) และคุณต้องบรรจุมันพร้อมกับรูปภาพ, CSS, และ JavaScript ไว้ในไฟล์ ZIP เดียวที่สามารถส่งผ่านเครือข่ายหรือเก็บไว้ใช้ในภายหลังได้ ไม่ต้องใช้เครื่องมือภายนอก ไม่ต้องคัดลอกไฟล์ด้วยมือ—เพียงแค่ C# แท้ ๆ และ Aspose.HTML. + +คุณจะได้เรียนรู้: + +* วิธีการสร้าง `ResourceHandler` ที่เขียนแต่ละทรัพยากรลงใน `MemoryStream` (หรือสตรีมใด ๆ ที่คุณเลือก). +* วิธีการโหลดเอกสาร HTML จากสตริงหรือไฟล์. +* วิธีการกำหนดค่า `HTMLSaveOptions` ให้ใช้ handler ของคุณ. +* วิธีการตรวจสอบว่าไฟล์ ZIP ที่ได้มีไฟล์ที่คาดหวังอยู่. + +## ข้อกำหนดเบื้องต้น + +* .NET 6.0 หรือใหม่กว่า (โค้ดนี้ยังทำงานกับ .NET Framework 4.6+). +* ใบอนุญาต Aspose.HTML for .NET ที่ถูกต้อง (รุ่นทดลองฟรีใช้ได้สำหรับการพัฒนา). +* ความคุ้นเคยพื้นฐานกับสตรีม C# และการทำ I/O ของไฟล์. + +--- + +## ขั้นตอนที่ 1: สร้าง custom resource handler + +หัวใจของวิธีแก้คือคลาสที่สืบทอดจาก `Aspose.Html.ResourceHandler`. +Aspose.HTML จะเรียก `HandleResource` สำหรับทุกแอสเซ็ตภายนอกที่พบ (รูปภาพ, CSS, ฟอนต์ ฯลฯ). โดยการคืนค่า `Stream` คุณจะกำหนดได้อย่างแม่นยำว่าแอสเซ็ตจะถูกจัดเก็บอย่างไร. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Why this matters** – หากไม่มี custom handler, Aspose.HTML จะเขียนทรัพยากรลงในระบบไฟล์ในโฟลเดอร์ชั่วคราว ซึ่งคุณต้องย้ายเข้า ZIP ด้วยตนเอง. handler ให้การควบคุมเต็มที่, กำจัดไฟล์กลาง, และทำงานได้ดีเช่นกันสำหรับไบนารีขนาดใหญ่เมื่อคุณเปลี่ยน `MemoryStream` เป็น `FileStream`. + +--- + +## ขั้นตอนที่ 2: โหลดเอกสาร HTML + +คุณสามารถโหลด HTML จากสตริง, ไฟล์, หรือ `Stream` ใดก็ได้ ตัวอย่างด้านล่างใช้สตริงในบรรทัดเดียวเพื่อความง่าย, แต่โค้ดเดียวกันทำงานกับ `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Tip** – หาก HTML ของคุณอ้างอิงไฟล์ในเครื่อง, ตรวจสอบให้แน่ใจว่า property `BaseUrl` ของ `HTMLDocument` ชี้ไปยังโฟลเดอร์ที่มีทรัพยากรเหล่านั้น. สิ่งนี้ช่วยให้ handler แก้ไข URI แบบ relative ได้อย่างถูกต้อง. + +--- + +## ขั้นตอนที่ 3: กำหนดค่า save options ให้ใช้ custom handler + +`HTMLSaveOptions` ให้คุณระบุรูปแบบเอาต์พุตและกลไกการจัดเก็บ. การตั้งค่า `OutputStorage` ให้เป็นอินสแตนซ์ของ `MyHandler` จะบอก Aspose.HTML ให้เรียก handler ของคุณสำหรับทุกทรัพยากรภายนอก. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Why set `FileName`?** – เมื่อบันทึกเป็น ZIP, Aspose.HTML จะสร้างคอนเทนเนอร์ที่รวมไฟล์ HTML หลัก (ชื่อ `index.html` เป็นค่าเริ่มต้น) พร้อมกับทรัพยากรทั้งหมด. การตั้งชื่อ entry อย่างชัดเจนทำให้โครงสร้าง ZIP คาดเดาได้, ซึ่งมีประโยชน์ต่อการประมวลผลต่อไป. + +--- + +## ขั้นตอนที่ 4: บันทึกเอกสารเป็นไฟล์ ZIP + +ตอนนี้คุณเพียงแค่เรียก `doc.Save`, ส่งพาธเป้าหมายและตัวเลือกที่กำหนดไว้. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### ผลลัพธ์ที่คาดหวัง + +หลังจากโปรแกรมทำงานเสร็จ, `demo.zip` จะมี: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +คุณสามารถเปิด ZIP ด้วยโปรแกรมดูไฟล์ใดก็ได้เพื่อยืนยันว่าไฟล์ HTML อ้างอิงรูปภาพด้วยพาธ relative `assets/logo.png`. การเปิด `index.html` ในเบราว์เซอร์จะแสดงหน้าเว็บเหมือนเดิมก่อนบรรจุ. + +--- + +## การจัดการทรัพยากรขนาดใหญ่และข้อพิจารณาเรื่องหน่วยความจำ + +ตัวอย่างใช้ `MemoryStream` สำหรับทุกทรัพยากร, ซึ่งทำงานได้ดีสำหรับรูปภาพหรือไฟล์ CSS ขนาดเล็ก. สำหรับแอสเซ็ตขนาดใหญ่ (เช่น ภาพความละเอียดสูงหรือไฟล์วิดีโอ) คุณควรเปลี่ยนเป็น `FileStream` เพื่อหลีกเลี่ยงการใช้หน่วยความจำมากเกินไป: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +หลังจาก `doc.Save` เสร็จสิ้น, คุณสามารถลบไฟล์ชั่วคราวโดยวนลูป `resource.CustomData["TempPath"]`. รูปแบบนี้ทำให้ **save html as zip** ทำงานอย่างเชื่อถือได้แม้กับแอสเซ็ตขนาดเมกะไบต์. + +--- + +## การเพิ่มไฟล์เพิ่มเติมลงใน ZIP (เช่น README) + +บางครั้งคุณอาจต้องการบรรจุเอกสารเพิ่มเติมพร้อมกับ HTML. คุณทำได้โดยใช้ `ZipArchive` โดยตรงหลังจาก Aspose.HTML สร้าง archive แรก. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +ตอนนี้ archive ยังมี `README.txt`, แสดงวิธี **create zip from html** พร้อมกับเพิ่มเนื้อหาที่กำหนดเอง. + +--- + +## ปัญหาที่พบบ่อยและวิธีหลีกเลี่ยง + +| ปัญหา | อาการ | วิธีแก้ | +|-------|----------|-----| +| ทรัพยากรไม่ปรากฏใน ZIP | มีเพียง `index.html` เท่านั้น; รูปภาพหายไป. | ตรวจสอบให้แน่ใจว่า `OutputStorage` ถูกตั้งเป็นอินสแตนซ์ของ `MyHandler`. ตรวจสอบว่า `HandleResource` คืนค่า stream ที่สามารถเขียนได้. | +| ลิงก์รูปภาพเสีย | เบราว์เซอร์แสดง “missing image” หลังจากแตกไฟล์ ZIP. | `CustomData["ZipEntryName"]` ต้องตรงกับพาธที่ใช้ใน HTML. ใช้โฟลเดอร์ฐานที่สม่ำเสมอ (`assets/`) ใน handler. | +| ข้อยกเว้น Out‑of‑memory สำหรับไฟล์ขนาดใหญ่ | แอปพลิเคชันพังเมื่อประมวลผลวิดีโอขนาด 50 MB. | เปลี่ยนจาก `MemoryStream` เป็น `FileStream` ใน `HandleResource`. ทำความสะอาดไฟล์ชั่วคราวหลังการบันทึก. | +| ไฟล์ ZIP ถูกล็อกหลังการสร้าง | การรันครั้งต่อไปล้มเหลวด้วยข้อความ “file in use”. | Dispose `HTMLDocument` (`doc.Dispose()`) และอ็อบเจ็กต์ `FileStream` ใด ๆ ก่อนเปิด ZIP ใหม่. | + +--- + +## ตัวอย่างเต็มที่สามารถรันได้ + +ด้านล่างเป็นโปรแกรมคอนโซลไฟล์เดียวที่คุณสามารถคัดลอก, วาง, และรันได้. มันรวมส่วนทั้งหมดที่อธิบายไว้ข้างต้น. + + + +## สิ่งที่คุณควรเรียนต่อไป + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดซึ่งต่อยอดจากเทคนิคที่แสดงในคู่มือนี้. แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานครบถ้วนพร้อมคำอธิบายทีละขั้นตอนเพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานทางเลือกในโครงการของคุณ. + +- [วิธีบันทึก HTML ใน C# – คู่มือเต็มโดยใช้ Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [วิธีบีบอัด HTML ใน C# – บันทึก HTML เป็น Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [บันทึก HTML เป็น ZIP – คอร์ส C# เต็มรูปแบบ](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 8dd996b055..9d6fc3c825 100644 --- a/html/turkish/net/html-extensions-and-conversions/_index.md +++ b/html/turkish/net/html-extensions-and-conversions/_index.md @@ -69,6 +69,8 @@ Aspose.HTML for .NET kullanarak HTML'den PDF'ye nasıl dönüştüreceğinizi ad ### [Stil Verilmiş Metinle HTML Belgesi Oluşturma ve PDF'ye Dışa Aktarma – Tam Kılavuz](./create-html-document-with-styled-text-and-export-to-pdf-full/) ### [HTML'yi ZIP Olarak Kaydet – Tam C# Öğreticisi](./save-html-as-zip-complete-c-tutorial/) Aspose.HTML for .NET kullanarak HTML dosyalarını ZIP arşivine kaydetmeyi adım adım öğrenin. +### [Aspose.HTML ile HTML'yi ZIP'e Kaydet – Tam Kılavuz](./save-html-to-zip-with-aspose-html-complete-guide/) +Aspose.HTML for .NET kullanarak HTML dosyalarını ZIP arşivine kaydetmeyi adım adım öğrenin. ### [C# ile HTML'yi ZIP'e Kaydet – Tam Bellek İçi Örnek](./save-html-to-zip-in-c-complete-in-memory-example/) Aspose.HTML for .NET kullanarak HTML dosyasını bellek içinde ZIP arşivine dönüştürmeyi adım adım öğrenin. diff --git a/html/turkish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/turkish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..e240ef3c0e --- /dev/null +++ b/html/turkish/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Aspose.HTML ve özel bir kaynak işleyicisi kullanarak HTML'yi ZIP olarak + kaydedin. HTML'yi ZIP'e dönüştürmeyi, HTML'yi ZIP olarak kaydetmeyi ve HTML'den + ZIP oluşturmayı birkaç adımda öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: tr +lastmod: 2026-08-09 +og_description: Aspose.HTML ve özel bir kaynak işleyicisi ile HTML'yi ZIP olarak kaydedin. + Bu öğreticide HTML'yi ZIP'e nasıl dönüştüreceğinizi, HTML'yi ZIP olarak nasıl kaydedeceğinizi + ve HTML'den verimli bir şekilde ZIP oluşturmayı gösteriyor. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Aspose.HTML ile HTML'yi ZIP'e Kaydet – Adım Adım Rehber +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Aspose.HTML ile HTML'yi ZIP'e Kaydet – Tam Rehber +url: /tr/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML'yi ZIP olarak Kaydetme – Aspose.HTML ile Tam Kılavuz + +Eğer **save HTML to ZIP** işlemini hızlı bir şekilde yapmanız gerekiyorsa, bu eğitim Aspose.HTML for .NET ile bunu tam olarak nasıl yapacağınızı gösterir. İlk iki cümlenin sonunda, bir **custom resource handler**'ın her kaynağın nereye yerleştirileceğini nasıl kontrol ettiğini, **convert HTML to ZIP**, **save HTML as ZIP** ya da **create ZIP from HTML** işlemlerini sadece birkaç satır kodla nasıl gerçekleştirebileceğinizi anlayacaksınız. + +Gerçek bir senaryoyu adım adım inceleyeceğiz: bir HTML parçacığınız (veya tam bir sayfanız) var ve bunu görüntüler, CSS ve JavaScript dosyalarıyla birlikte tek bir ZIP dosyasında paketlemeniz gerekiyor; bu ZIP dosyası ağ üzerinden gönderilebilir ya da daha sonra kullanılmak üzere saklanabilir. Harici araçlar yok, manuel dosya kopyalama yok—sadece saf C# ve Aspose.HTML. + +Öğrenecekleriniz: + +* Her kaynağı bir `MemoryStream` (veya seçtiğiniz herhangi bir akış) içine yazan bir `ResourceHandler` nasıl uygulanır. +* HTML belgesini bir dizeden ya da dosyadan nasıl yüklersiniz. +* `HTMLSaveOptions`'ı kendi işleyicinizi kullanacak şekilde nasıl yapılandırırsınız. +* Oluşan ZIP arşivinin beklenen dosyaları içerdiğini nasıl doğrularsınız. + +Önkoşullar + +* .NET 6.0 veya üzeri (kod .NET Framework 4.6+ ile de çalışır). +* Geçerli bir Aspose.HTML for .NET lisansı (ücretsiz deneme sürümü geliştirme için yeterlidir). +* C# akışları ve dosya I/O konularına temel aşinalık. + +--- + +## Adım 1: Özel bir resource handler oluşturun + +Çözümün kalbi, `Aspose.Html.ResourceHandler` sınıfından türetilen bir sınıftır. +Aspose.HTML, karşılaştığı her dış varlık (görseller, CSS, fontlar vb.) için `HandleResource` metodunu çağırır. Bir `Stream` döndürerek varlığın tam olarak nasıl saklanacağını belirlersiniz. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Neden önemli?** – Özel bir işleyici olmadan, Aspose.HTML kaynakları geçici bir klasöre yazar; bu dosyaları daha sonra manuel olarak bir ZIP içine taşımanız gerekir. İşleyici size tam kontrol sağlar, ara dosyaları ortadan kaldırır ve `MemoryStream` yerine `FileStream` kullandığınızda büyük ikili dosyalarla da sorunsuz çalışır. + +--- + +## Adım 2: HTML belgesini yükleyin + +HTML'i bir dizeden, bir dosyadan ya da herhangi bir `Stream`'den yükleyebilirsiniz. Aşağıdaki örnek basitlik açısından satır içi bir dize kullanıyor, ancak aynı kod `new HTMLDocument("path/to/file.html")` ile de çalışır. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**İpucu** – HTML'iniz yerel dosyalara referans veriyorsa, `HTMLDocument`'in `BaseUrl` özelliğinin bu varlıkların bulunduğu klasöre işaret ettiğinden emin olun. Bu, işleyicinin göreli URI'ları doğru çözmesine yardımcı olur. + +--- + +## Adım 3: Özel işleyiciyi kullanacak şekilde kaydetme seçeneklerini yapılandırın + +`HTMLSaveOptions`, çıktı formatını ve depolama mekanizmasını belirlemenizi sağlar. `OutputStorage`'ı `MyHandler` örneğiyle ayarlamak, Aspose.HTML'in her dış kaynağı sizin işleyicinize yönlendirmesini sağlar. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**`FileName` neden ayarlanmalı?** – ZIP olarak kaydederken, Aspose.HTML varsayılan olarak birincil HTML dosyasını (`index.html`) ve tüm kaynakları içeren bir kapsayıcı oluşturur. Giriş dosyasını açıkça adlandırmak, ZIP yapısını öngörülebilir kılar; bu da sonraki işlemler için faydalıdır. + +--- + +## Adım 4: Belgeyi bir ZIP arşivine kaydedin + +Şimdi sadece `doc.Save` metodunu, hedef yolu ve yapılandırılmış seçenekleri geçirerek çağırmanız yeterli. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Beklenen sonuç + +Program tamamlandığında, `demo.zip` şunları içerir: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +ZIP'i herhangi bir arşiv görüntüleyiciyle açıp HTML dosyasının `assets/logo.png` göreli yolunu kullandığını doğrulayabilirsiniz. `index.html` dosyasını bir tarayıcıda açtığınızda, sayfa paketlenmeden önceki haliyle tam olarak görüntülenir. + +--- + +## Büyük kaynakları ve bellek kullanımını yönetme + +Örnek, her kaynak için `MemoryStream` kullanıyor; bu küçük görseller veya CSS dosyaları için uygundur. Daha büyük varlıklar (ör. yüksek çözünürlüklü fotoğraflar veya video dosyaları) için aşırı bellek tüketimini önlemek amacıyla `FileStream`'e geçmelisiniz: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +`doc.Save` tamamlandıktan sonra, `resource.CustomData["TempPath"]` üzerinden geçerek geçici dosyaları silebilirsiniz. Bu desen, **save html as zip** işleminin megabayt büyüklüğündeki varlıklarla bile sorunsuz çalışmasını sağlar. + +--- + +## ZIP'e ek dosyalar ekleme (ör. README) + +Bazen HTML'in yanında ekstra dokümantasyon da paketlemek istersiniz. Bunu, Aspose.HTML ilk arşivi oluşturduktan sonra doğrudan `ZipArchive` kullanarak yapabilirsiniz. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Artık arşivde `README.txt` de bulunuyor; bu, **create zip from html** işlemini özelleştirilmiş içerikle zenginleştirerek nasıl yapabileceğinizi gösterir. + +--- + +## Yaygın hatalar ve önleme yöntemleri + +| Sorun | Belirtiler | Çözüm | +|-------|------------|-------| +| Kaynaklar ZIP içinde görünmüyor | Sadece `index.html` var; görseller eksik. | `OutputStorage`'ın `MyHandler` örneği olduğundan emin olun. `HandleResource`'un yazılabilir bir akış döndürdüğünü kontrol edin. | +| Bozuk görsel bağlantıları | ZIP'i çıkardıktan sonra tarayıcı “missing image” hatası veriyor. | `CustomData["ZipEntryName"]` HTML'de kullanılan yol ile aynı olmalı. İşleyicide tutarlı bir temel klasör (`assets/`) kullanın. | +| Büyük dosyalar için bellek taşması | 50 MB bir video işlenirken uygulama çöküyor. | `HandleResource` içinde `MemoryStream` yerine `FileStream` kullanın. Kaydetme sonrası geçici dosyaları temizleyin. | +| ZIP dosyası oluşturulduktan sonra kilitleniyor | Sonraki çalıştırmalarda “file in use” hatası alınıyor. | `HTMLDocument` (`doc.Dispose()`) ve tüm `FileStream` nesnelerini ZIP'i yeniden açmadan önce serbest bırakın. | + +--- + +## Tam, çalıştırılabilir örnek + +Aşağıda tek dosyalı bir konsol programı bulunuyor; kopyalayıp yapıştırarak çalıştırabilirsiniz. Yukarıda tartışılan tüm parçalar bu örnekte bir araya getirilmiştir. + + + +## Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki eğitimler, bu kılavuzda gösterilen tekniklere dayanan ilgili konuları kapsar. Her kaynak, adım adım açıklamalar ve tam çalışan kod örnekleri içerir; böylece ek API özelliklerini ustalaşabilir ve projelerinizde alternatif uygulama yaklaşımlarını keşfedebilirsiniz. + +- [How to Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Save HTML as ZIP – Complete C# Tutorial](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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 169c7624f6..754fb3cb26 100644 --- a/html/vietnamese/net/html-extensions-and-conversions/_index.md +++ b/html/vietnamese/net/html-extensions-and-conversions/_index.md @@ -65,14 +65,12 @@ Tìm hiểu cách chuyển đổi HTML sang TIFF bằng Aspose.HTML cho .NET. L Khám phá sức mạnh của Aspose.HTML cho .NET: Chuyển đổi HTML sang XPS dễ dàng. Bao gồm các điều kiện tiên quyết, hướng dẫn từng bước và Câu hỏi thường gặp. ### [Cách Nén HTML thành Zip trong C# – Lưu HTML vào Zip](./how-to-zip-html-in-c-save-html-to-zip/) Hướng dẫn chi tiết cách nén HTML thành tệp Zip bằng C# và Aspose.HTML, kèm ví dụ mã và các tùy chọn cấu hình. -### [Tạo tài liệu HTML với văn bản có kiểu dáng và xuất ra PDF – Hướng dẫn đầy đủ](./create-html-document-with-styled-text-and-export-to-pdf-full/) -Hướng dẫn chi tiết cách tạo tài liệu HTML có văn bản định dạng và xuất ra PDF bằng Aspose.HTML cho .NET. -### [Tạo PDF từ HTML – Hướng dẫn từng bước C#](./create-pdf-from-html-c-step-by-step-guide/) -Tạo PDF từ HTML trong .NET bằng C#. Hướng dẫn chi tiết từng bước để chuyển đổi HTML sang PDF nhanh chóng. ### [Lưu HTML dưới dạng ZIP – Hướng dẫn C# hoàn chỉnh](./save-html-as-zip-complete-c-tutorial/) Hướng dẫn chi tiết cách lưu tài liệu HTML thành tệp ZIP bằng Aspose.HTML cho .NET với C#. ### [Lưu HTML thành ZIP trong C# – Ví dụ Toàn bộ trong Bộ nhớ](./save-html-to-zip-in-c-complete-in-memory-example/) Hướng dẫn lưu tài liệu HTML vào tệp ZIP trong C# bằng Aspose.HTML, sử dụng bộ nhớ tạm và không tạo file tạm trên đĩa. +### [Lưu HTML thành ZIP với Aspose.HTML – hướng dẫn đầy đủ](./save-html-to-zip-with-aspose-html-complete-guide/) +Hướng dẫn chi tiết cách lưu tài liệu HTML vào tệp ZIP bằng Aspose.HTML trong .NET, bao gồm ví dụ mã và tùy chọn cấu hình. ## Phần kết luận diff --git a/html/vietnamese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md b/html/vietnamese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md new file mode 100644 index 0000000000..e12e7c7a1c --- /dev/null +++ b/html/vietnamese/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Lưu HTML thành ZIP bằng Aspose.HTML và trình xử lý tài nguyên tùy chỉnh. + Tìm hiểu cách chuyển đổi HTML sang ZIP, lưu HTML dưới dạng ZIP và tạo ZIP từ HTML + trong vài bước. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- save html to zip +- custom resource handler +- convert html to zip +- save html as zip +- create zip from html +language: vi +lastmod: 2026-08-09 +og_description: Lưu HTML thành ZIP với Aspose.HTML và trình xử lý tài nguyên tùy chỉnh. + Hướng dẫn này chỉ cho bạn cách chuyển đổi HTML sang ZIP, lưu HTML dưới dạng ZIP + và tạo ZIP từ HTML một cách hiệu quả. +og_image_alt: Diagram illustrating save HTML to ZIP process using Aspose.HTML custom + resource handler +og_title: Lưu HTML thành ZIP với Aspose.HTML – hướng dẫn chi tiết từng bước +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Save HTML to ZIP using Aspose.HTML and a custom resource handler. Learn + how to convert HTML to ZIP, save HTML as ZIP, and create ZIP from HTML in a few + steps. + headline: Save HTML to ZIP with Aspose.HTML – complete guide + type: TechArticle +tags: +- Aspose.HTML +- C# +- ZIP archive +title: Lưu HTML thành ZIP với Aspose.HTML – hướng dẫn đầy đủ +url: /vi/net/html-extensions-and-conversions/save-html-to-zip-with-aspose-html-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Lưu HTML thành ZIP với Aspose.HTML – hướng dẫn đầy đủ + +Nếu bạn cần **lưu HTML thành ZIP** nhanh chóng, hướng dẫn này sẽ chỉ cho bạn cách thực hiện với Aspose.HTML cho .NET. Sau hai câu đầu tiên, bạn sẽ hiểu cách **custom resource handler** cho phép bạn kiểm soát nơi mỗi tài nguyên được lưu, giúp bạn **chuyển đổi HTML sang ZIP**, **lưu HTML dưới dạng ZIP**, hoặc **tạo ZIP từ HTML** chỉ với vài dòng mã. + +Chúng tôi sẽ đi qua một kịch bản thực tế: bạn có một đoạn HTML (hoặc một trang đầy đủ) và cần đóng gói nó cùng với các hình ảnh, CSS và JavaScript vào một tệp ZIP duy nhất có thể gửi qua mạng hoặc lưu trữ để sử dụng sau. Không cần công cụ bên ngoài, không sao chép tệp thủ công—chỉ cần C# thuần và Aspose.HTML. + +Bạn sẽ học: + +* Cách triển khai một `ResourceHandler` ghi mỗi tài nguyên vào một `MemoryStream` (hoặc bất kỳ stream nào bạn chọn). +* Cách tải tài liệu HTML từ một chuỗi hoặc tệp. +* Cách cấu hình `HTMLSaveOptions` để sử dụng handler của bạn. +* Cách xác minh archive ZIP kết quả chứa các tệp mong đợi. + +**Yêu cầu trước** + +* .NET 6.0 hoặc mới hơn (mã cũng hoạt động với .NET Framework 4.6+). +* Giấy phép Aspose.HTML for .NET hợp lệ (bản dùng thử miễn phí hoạt động cho phát triển). +* Kiến thức cơ bản về các stream C# và I/O tệp. + +--- + +## Bước 1: Tạo custom resource handler + +Trọng tâm của giải pháp là một lớp kế thừa từ `Aspose.Html.ResourceHandler`. +Aspose.HTML gọi `HandleResource` cho mỗi tài nguyên bên ngoài mà nó gặp (hình ảnh, CSS, phông chữ, v.v.). Bằng cách trả về một `Stream`, bạn quyết định chính xác cách tài nguyên được lưu trữ. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +/// +/// Writes each HTML resource into a memory stream that will later be added to a ZIP entry. +/// +class MyHandler : ResourceHandler +{ + // The key that will be used as the entry name inside the ZIP archive. + private readonly string _basePath; + + public MyHandler(string basePath = "") + { + _basePath = basePath; + } + + public override Stream HandleResource(Resource resource) + { + // Determine a safe file name for the resource. + string entryName = Path.GetFileName(resource.Uri); + if (string.IsNullOrEmpty(entryName)) + { + // Fallback for data URIs or resources without a file name. + entryName = Guid.NewGuid().ToString() + ".bin"; + } + + // Combine with optional base path inside the ZIP. + string zipPath = Path.Combine(_basePath, entryName).Replace('\\', '/'); + + // Store the ZIP entry name in the resource's custom data so Aspose.HTML can reference it. + resource.CustomData["ZipEntryName"] = zipPath; + + // Return a fresh MemoryStream; Aspose.HTML will write the content into it. + return new MemoryStream(); + } +} +``` + +**Tại sao điều này quan trọng** – Nếu không có custom handler, Aspose.HTML sẽ ghi tài nguyên vào hệ thống tệp trong một thư mục tạm, sau đó bạn phải di chuyển chúng vào ZIP một cách thủ công. Handler cung cấp cho bạn toàn quyền kiểm soát, loại bỏ các tệp trung gian, và hoạt động tốt cho các binary lớn khi bạn thay `MemoryStream` bằng `FileStream`. + +--- + +## Bước 2: Tải tài liệu HTML + +Bạn có thể tải HTML từ một chuỗi, một tệp, hoặc bất kỳ `Stream` nào. Ví dụ dưới đây sử dụng chuỗi nội tuyến để đơn giản, nhưng cùng mã cũng hoạt động với `new HTMLDocument("path/to/file.html")`. + +```csharp +// Simple HTML containing an image tag (the image will be handled by MyHandler). +string htmlContent = @" + + + + Demo + + + +

Hello, world!

+ Logo + +"; + +HTMLDocument doc = new HTMLDocument(htmlContent); +``` + +**Mẹo** – Nếu HTML của bạn tham chiếu tới các tệp cục bộ, hãy chắc chắn thuộc tính `BaseUrl` của `HTMLDocument` trỏ tới thư mục chứa các tài nguyên đó. Điều này giúp handler giải quyết đúng các URI tương đối. + +--- + +## Bước 3: Cấu hình tùy chọn lưu để sử dụng custom handler + +`HTMLSaveOptions` cho phép bạn chỉ định định dạng đầu ra và cơ chế lưu trữ. Đặt `OutputStorage` thành một instance của `MyHandler` sẽ yêu cầu Aspose.HTML gọi handler của bạn cho mỗi tài nguyên bên ngoài. + +```csharp +// Create the handler; optionally specify a folder inside the ZIP. +var handler = new MyHandler("assets"); + +// Configure save options. +HTMLSaveOptions saveOptions = new HTMLSaveOptions +{ + // The main HTML file will be named "index.html" inside the ZIP. + FileName = "index.html", + // Use the custom handler for all linked resources. + OutputStorage = handler, + // Ensure the ZIP container is created. + SaveFormat = SaveFormat.Zip +}; +``` + +**Tại sao đặt `FileName`?** – Khi lưu dưới dạng ZIP, Aspose.HTML tạo một container bao gồm tệp HTML chính (được đặt tên `index.html` theo mặc định) cùng với tất cả các tài nguyên. Đặt tên rõ ràng cho entry giúp cấu trúc ZIP dự đoán được, hữu ích cho các quy trình xử lý tiếp theo. + +--- + +## Bước 4: Lưu tài liệu vào archive ZIP + +Bây giờ bạn chỉ cần gọi `doc.Save`, truyền đường dẫn đích và các tùy chọn đã cấu hình. + +```csharp +string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); +Directory.CreateDirectory(outputDirectory); + +string zipPath = Path.Combine(outputDirectory, "demo.zip"); + +// Save the HTML and all its resources into demo.zip. +doc.Save(zipPath, saveOptions); + +Console.WriteLine($"ZIP archive created at: {zipPath}"); +``` + +### Kết quả mong đợi + +Sau khi chương trình kết thúc, `demo.zip` chứa: + +``` +demo.zip +│─ index.html (the original HTML) +│─ assets/ +│ └─ logo.png (image fetched from the remote URL) +``` + +Bạn có thể mở ZIP bằng bất kỳ trình xem archive nào để xác minh tệp HTML tham chiếu tới hình ảnh bằng đường dẫn tương đối `assets/logo.png`. Mở `index.html` trong trình duyệt sẽ hiển thị trang đúng như trước khi đóng gói. + +--- + +## Xử lý tài nguyên lớn và cân nhắc bộ nhớ + +Ví dụ sử dụng `MemoryStream` cho mọi tài nguyên, phù hợp với các hình ảnh hoặc tệp CSS nhỏ. Đối với tài nguyên lớn hơn (ví dụ: ảnh độ phân giải cao hoặc tệp video) bạn nên chuyển sang `FileStream` để tránh sử dụng bộ nhớ quá mức: + +```csharp +public override Stream HandleResource(Resource resource) +{ + string tempPath = Path.GetTempFileName(); + // Store the temporary file path in custom data for later cleanup if needed. + resource.CustomData["TempPath"] = tempPath; + return new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); +} +``` + +Sau khi `doc.Save` hoàn thành, bạn có thể xóa các tệp tạm bằng cách lặp qua `resource.CustomData["TempPath"]`. Mô hình này đảm bảo **save html as zip** hoạt động ổn định ngay cả với các tài nguyên có kích thước megabyte. + +--- + +## Thêm các tệp bổ sung vào ZIP (ví dụ: README) + +Đôi khi bạn muốn đóng gói tài liệu bổ sung cùng với HTML. Bạn có thể thực hiện điều này bằng cách sử dụng `ZipArchive` trực tiếp sau khi Aspose.HTML tạo archive ban đầu. + +```csharp +using System.IO.Compression; + +// Open the existing ZIP for update. +using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) +using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) +{ + // Add a README.txt entry. + ZipArchiveEntry readme = archive.CreateEntry("README.txt"); + using (StreamWriter writer = new StreamWriter(readme.Open())) + { + writer.WriteLine("This ZIP contains a self‑contained HTML demo."); + writer.WriteLine("Open index.html to view the page."); + } +} +``` + +Bây giờ archive cũng chứa `README.txt`, minh họa cách **create zip from html** đồng thời bổ sung nội dung tùy chỉnh. + +--- + +## Những lỗi thường gặp và cách tránh + +| Vấn đề | Triệu chứng | Cách khắc phục | +|-------|------------|----------------| +| Tài nguyên không xuất hiện trong ZIP | Chỉ có `index.html` hiện ra; hình ảnh bị thiếu. | Đảm bảo `OutputStorage` được đặt thành một instance của `MyHandler`. Kiểm tra `HandleResource` trả về một stream có thể ghi. | +| Liên kết hình ảnh bị hỏng | Trình duyệt hiển thị “missing image” sau khi giải nén ZIP. | `CustomData["ZipEntryName"]` phải khớp với đường dẫn được sử dụng trong HTML. Sử dụng thư mục cơ sở nhất quán (`assets/`) trong handler. | +| Ngoại lệ out‑of‑memory cho tệp lớn | Ứng dụng bị sập khi xử lý video 50 MB. | Chuyển từ `MemoryStream` sang `FileStream` trong `HandleResource`. Dọn dẹp các tệp tạm sau khi lưu. | +| Tệp ZIP bị khóa sau khi tạo | Các lần chạy tiếp theo thất bại với lỗi “file in use”. | Giải phóng `HTMLDocument` (`doc.Dispose()`) và bất kỳ đối tượng `FileStream` nào trước khi mở lại ZIP. | + +--- + +## Ví dụ đầy đủ, có thể chạy + +Dưới đây là một chương trình console đơn file mà bạn có thể sao chép, dán và chạy. Nó bao gồm tất cả các phần đã thảo luận ở trên. + + + +## 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 Save HTML in C# – Complete Guide Using a Custom Resource Handler](/html/english/net/working-with-html-documents/how-to-save-html-in-c-complete-guide-using-a-custom-resource/) +- [How to Zip HTML in C# – Save HTML to Zip](/html/english/net/html-extensions-and-conversions/how-to-zip-html-in-c-save-html-to-zip/) +- [Save HTML as ZIP – Complete C# Tutorial](/html/english/net/html-extensions-and-conversions/save-html-as-zip-complete-c-tutorial/) + +{{< /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