diff --git a/html/arabic/net/generate-jpg-and-png-images/_index.md b/html/arabic/net/generate-jpg-and-png-images/_index.md index 432f80cdc..8e54111a9 100644 --- a/html/arabic/net/generate-jpg-and-png-images/_index.md +++ b/html/arabic/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET هي مكتبة قوية تتيح للمطورين إنشا تعلم كيفية تمكين مضاد التعرج عند تحويل ملفات DOCX إلى صور PNG أو JPG باستخدام Aspose.HTML. ### [تحويل docx إلى png – إنشاء أرشيف zip في C# – دليل تعليمي](./convert-docx-to-png-create-zip-archive-c-tutorial/) تعلم كيفية تحويل ملفات docx إلى صور PNG وإنشاء أرشيف ZIP باستخدام C# و Aspose.HTML. +### [تحويل HTML إلى PNG – دليل كامل بلغة C# مع تصدير ZIP](./convert-html-to-png-full-c-guide-with-zip-export/) +دليل شامل يوضح تحويل ملفات HTML إلى صور PNG باستخدام C# وتصدير النتائج في أرشيف ZIP. ## خاتمة diff --git a/html/arabic/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/arabic/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..590ecdf2c --- /dev/null +++ b/html/arabic/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-03-21 +description: تحويل HTML إلى PNG وعرض HTML كصورة مع حفظ HTML في ملف ZIP. تعلم كيفية + تطبيق نمط الخط في HTML وإضافة الخط العريض لعناصر 

في بضع خطوات فقط. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: ar +og_description: تحويل HTML إلى PNG بسرعة. يوضح هذا الدليل كيفية تحويل HTML إلى صورة، + حفظ HTML في ملف ZIP، تطبيق نمط الخط على HTML وإضافة الخط العريض لعناصر p. +og_title: تحويل HTML إلى PNG – دليل C# الكامل +tags: +- Aspose +- C# +title: تحويل HTML إلى PNG – دليل C# الكامل مع تصدير ZIP +url: /ar/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحويل HTML إلى PNG – دليل C# كامل مع تصدير ZIP + +هل احتجت يومًا إلى **convert HTML to PNG** لكن لم تكن متأكدًا أي مكتبة يمكنها القيام بذلك دون استدعاء متصفح بدون رأس؟ لست وحدك. في العديد من المشاريع—مصغرات البريد الإلكتروني، معاينات الوثائق، أو صور النظرة السريعة—تحويل صفحة ويب إلى صورة ثابتة هو حاجة واقعية. + +الأخبار السارة؟ مع Aspose.HTML يمكنك **render HTML as image**، تعديل العلامات في الوقت الفعلي، وحتى **save HTML to ZIP** للتوزيع لاحقًا. في هذا الدرس سنستعرض مثالًا كاملًا وقابلًا للتنفيذ ي **applies font style HTML**، وبشكل محدد **add bold to p** العناصر، قبل إنشاء ملف PNG. في النهاية ستحصل على فئة C# واحدة تقوم بكل شيء من تحميل الصفحة إلى أرشفة مواردها. + +## ما ستحتاجه + +- .NET 6.0 أو أحدث (API يعمل على .NET Core أيضًا) +- Aspose.HTML لـ .NET 6+ (حزمة NuGet `Aspose.Html`) +- فهم أساسي لصياغة C# (لا تحتاج إلى مفاهيم متقدمة) + +هذا كل شيء. لا متصفحات خارجية، لا phantomjs، مجرد شفرة مُدارة خالصة. + +## الخطوة 1 – تحميل مستند HTML + +أولاً نقوم بإدخال ملف المصدر (أو URL) إلى كائن `HTMLDocument`. هذه الخطوة هي الأساس لكل من **render html as image** و **save html to zip** لاحقًا. + +```csharp +using Aspose.Html; +using System.IO; + +///

+/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*لماذا هذا مهم:* فئة `HTMLDocument` تقوم بتحليل العلامات، بناء DOM، وحل الموارد المرتبطة (CSS، الصور، الخطوط). بدون كائن مستند صحيح لا يمكنك تعديل الأنماط أو إنشاء أي شيء. + +## الخطوة 2 – تطبيق نمط الخط HTML (Add Bold to p) + +الآن سنقوم **apply font style HTML** عن طريق التكرار على كل عنصر `

` وتعيين خاصية `font-weight` إلى bold. هذه هي الطريقة البرمجية لـ **add bold to p** العلامات دون تعديل الملف الأصلي. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*نصيحة محترف:* إذا كنت تحتاج لتغميق جزء فقط، غيّر المحدد إلى شيء أكثر تحديدًا، مثل `"p.intro"`. + +## الخطوة 3 – تحويل HTML إلى صورة (Convert HTML to PNG) + +مع جاهزية DOM، نقوم بتكوين `ImageRenderingOptions` وندعو `RenderToImage`. هنا يحدث سحر **convert html to png**. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*لماذا الخيارات مهمة:* ضبط عرض/ارتفاع ثابت يمنع الناتج من أن يكون كبيرًا جدًا، بينما يمنح التنعيم نتيجة بصرية أكثر سلاسة. يمكنك أيضًا تغيير `options` إلى `ImageFormat.Jpeg` إذا كنت تفضل حجم ملف أصغر. + +## الخطوة 4 – حفظ HTML إلى ZIP (Bundle Resources) + +غالبًا ما تحتاج إلى إرسال HTML الأصلي مع ملفات CSS والصور والخطوط الخاصة به. `ZipArchiveSaveOptions` من Aspose.HTML يقوم بذلك بالضبط. كما نضيف `ResourceHandler` مخصص بحيث تُكتب جميع الأصول الخارجية إلى نفس المجلد كالأرشيف. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*حالة خاصة:* إذا كان HTML الخاص بك يشير إلى صور بعيدة تتطلب مصادقة، سيفشل المعالج الافتراضي. في هذه الحالة يمكنك توسيع `MyResourceHandler` لإضافة رؤوس HTTP. + +## الخطوة 5 – ربط كل شيء في فئة Converter واحدة + +فيما يلي الفئة الكاملة، الجاهزة للتنفيذ، التي تربط جميع الخطوات السابقة معًا. يمكنك نسخها ولصقها في تطبيق console، استدعاء `Convert`، ومراقبة ظهور الملفات. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### النتيجة المتوقعة + +بعد تشغيل المقتطف أعلاه ستجد ملفين في `outputDirectory`: + +| File | Description | +|------|-------------| +| `page.png` | صورة PNG بحجم 1200 × 800 تمثل الـ HTML الأصلي، مع عرض كل فقرة **bold**. | +| `archive.zip` | حزمة ZIP تحتوي على `input.html` الأصلي، وملفاته CSS، الصور، وأي خطوط ويب – مثالية للتوزيع دون اتصال. | + +يمكنك فتح `page.png` في أي عارض صور للتحقق من تطبيق نمط الغامق، واستخراج `archive.zip` لرؤية الـ HTML غير المعدل مع موارده. + +## أسئلة شائعة وملاحظات + +- **ماذا لو كان HTML يحتوي على JavaScript؟** + Aspose.HTML **لا** ينفذ السكريبتات أثناء التحويل، لذا لن يظهر المحتوى الديناميكي. للحصول على صفحات مُعالجة بالكامل ستحتاج إلى متصفح بدون رأس، لكن للقوالب الثابتة هذا النهج أسرع وأخف. + +- **هل يمكنني تغيير تنسيق الإخراج إلى JPEG أو BMP؟** + نعم—غيّر خاصية `ImageFormat` في `ImageRenderingOptions`، مثال: `options.ImageFormat = ImageFormat.Jpeg;`. + +- **هل يجب إلغاء تخصيص `HTMLDocument` يدويًا؟** + الفئة تنفذ `IDisposable`. في خدمة طويلة التشغيل غلفها بكتلة `using` أو استدعِ `document.Dispose()` بعد الانتهاء. + +- **كيف يعمل `MyResourceHandler` المخصص؟** + يستقبل كل مورد خارجي (CSS، صور، خطوط) ويكتبها إلى المجلد الذي تحدده. هذا يضمن أن الـ ZIP يحتوي على نسخة مطابقة لكل ما يشير إليه HTML. + +## الخاتمة + +الآن لديك حلًا مضغوطًا وجاهزًا للإنتاج يقوم بـ **convert html to png**, **render html as image**, **save html to zip**, **apply font style html**, و **add bold to p**—كل ذلك في بضع أسطر C#. الشفرة مستقلة، تعمل مع .NET 6+، ويمكن دمجها في أي خدمة خلفية تحتاج إلى لقطات بصرية سريعة للمحتوى الويب. + +هل أنت مستعد للخطوة التالية؟ جرّب تغيير حجم التحويل، جرب خصائص CSS أخرى (مثل `font-family` أو `color`)، أو دمج هذا المحول في نقطة نهاية ASP.NET Core تُعيد PNG عند الطلب. الاحتمالات لا حصر لها، ومع Aspose.HTML تتجنب الاعتماد على المتصفحات الثقيلة. + +إذا واجهت أي مشاكل أو لديك أفكار لتوسعات، اترك تعليقًا أدناه. برمجة سعيدة! + +![convert html to png example](example.png "convert html to png example") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/arabic/net/html-document-manipulation/_index.md b/html/arabic/net/html-document-manipulation/_index.md index 5dca51c48..ce312e3d6 100644 --- a/html/arabic/net/html-document-manipulation/_index.md +++ b/html/arabic/net/html-document-manipulation/_index.md @@ -51,8 +51,8 @@ url: /ar/net/html-document-manipulation/ ## دروس تعليمية حول التعامل مع مستندات HTML ### [تحميل مستندات HTML بشكل غير متزامن في .NET باستخدام Aspose.HTML](./load-html-doc-asynchronously/) تعرف على كيفية استخدام Aspose.HTML for .NET للعمل مع مستندات HTML. دليل خطوة بخطوة مع أمثلة وأسئلة شائعة للمطورين. -### [تحميل مستندات HTML باستخدام بيانات الاعتماد في .NET باستخدام Aspose.HTML](./load-html-doc-with-credentials/) -تعرف على كيفية تعزيز تحسين محرك البحث الخاص بك باستخدام Aspose.HTML لـ .NET. قم بتعزيز التصنيفات وتحليل محتوى الويب وتحسينه لمحركات البحث. +### [تحميل مستندات HTML باستخدام بيانات الاعتماد في .NET باستخدام Aspose.HTML](./load-html-with-credentials/) +تعرف على كيفية تعزيز تحسين محرك البحث الخاص بك باستخدام Aspose.HTML لـ .NET. قم بتحسين التصنيفات وتحليل محتوى الويب وتحسينه لمحركات البحث. ### [تحميل HTML باستخدام خادم بعيد في .NET مع Aspose.HTML](./load-html-using-remote-server/) اكتشف إمكانات Aspose.HTML لـ .NET من خلال دليلنا الشامل. تعرّف على كيفية استيراد مساحات الأسماء والوصول إلى مستندات HTML عن بُعد والمزيد. ### [تحميل HTML باستخدام URL في .NET مع Aspose.HTML](./load-html-using-url/) @@ -71,6 +71,8 @@ url: /ar/net/html-document-manipulation/ أطلق العنان لإمكانات تطوير الويب باستخدام Aspose.HTML for .NET. أنشئ مستندات HTML وحولها وتعامل معها بسهولة. ### [إنشاء HTML من سلسلة في C# – دليل معالج الموارد المخصص](./create-html-from-string-in-c-custom-resource-handler-guide/) تعرف على كيفية إنشاء مستند HTML من سلسلة نصية في C# باستخدام معالج موارد مخصص. +### [إنشاء مستند HTML باستخدام C# – دليل خطوة بخطوة](./create-html-document-c-step-by-step-guide/) +تعرف على كيفية إنشاء مستند HTML باستخدام C# مع Aspose.HTML عبر دليل خطوة بخطوة. ## خاتمة diff --git a/html/arabic/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/arabic/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..c7f2f4231 --- /dev/null +++ b/html/arabic/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: إنشاء مستند HTML باستخدام C# وتعلم كيفية الحصول على عنصر بواسطة المعرف، + وتحديد العنصر بواسطة المعرف، وتغيير نمط عنصر HTML وإضافة غامق ومائل باستخدام Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: ar +og_description: إنشاء مستند HTML باستخدام C# وتعلم فورًا كيفية الحصول على عنصر بالمعرف، + وتحديد العنصر بالمعرف، وتغيير نمط عنصر HTML وإضافة الخط العريض والمائل مع أمثلة + شفرة واضحة. +og_title: إنشاء مستند HTML C# – دليل البرمجة الكامل +tags: +- Aspose.Html +- C# +- DOM manipulation +title: إنشاء مستند HTML C# – دليل خطوة بخطوة +url: /ar/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء مستند HTML C# – دليل خطوة بخطوة + +هل احتجت يوماً إلى **إنشاء مستند HTML C#** من الصفر ثم تعديل مظهر فقرة واحدة؟ لست وحدك. في العديد من مشاريع أتمتة الويب ستقوم بإنشاء ملف HTML، وتبحث عن عنصر باستخدام الـ ID الخاص به، ثم تطبق بعض الأنماط—غالباً عريض + مائل—دون الحاجة إلى فتح المتصفح. + +في هذا الدرس سنستعرض ذلك بالضبط: سننشئ مستند HTML في C#، **get element by id**، **locate element by id**، **change HTML element style**، وأخيراً **add bold italic** باستخدام مكتبة Aspose.Html. في النهاية ستحصل على مقطع شفرة قابل للتنفيذ يمكنك إدراجه في أي مشروع .NET. + +## ما ستحتاجه + +- .NET 6 أو أحدث (الكود يعمل أيضاً على .NET Framework 4.7+) +- Visual Studio 2022 (أو أي محرر تفضله) +- حزمة **Aspose.Html** NuGet (`Install-Package Aspose.Html`) + +هذا كل شيء—لا ملفات HTML إضافية، لا خادم ويب، فقط بضع أسطر من C#. + +## إنشاء مستند HTML C# – تهيئة المستند + +أولاً وقبل كل شيء: تحتاج إلى كائن `HTMLDocument` حي يمكن لمحرك Aspose.Html العمل معه. فكر في ذلك كفتح دفتر جديد ستكتب فيه العلامات الخاصة بك. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **لماذا هذا مهم:** بتمرير السلسلة الخام إلى `HTMLDocument`، تتجنب التعامل مع إدخال/إخراج الملفات وتبقي كل شيء في الذاكرة—مثالي لاختبارات الوحدة أو الإنشاء السريع أثناء التشغيل. + +## الحصول على عنصر بواسطة ID – العثور على الفقرة + +الآن بعد أن المستند موجود، نحتاج إلى **get element by id**. توفر واجهة برمجة تطبيقات DOM الدالة `GetElementById`، التي تُعيد مرجع `IElement` أو `null` إذا لم يكن الـ ID موجوداً. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **نصيحة احترافية:** رغم أن العلامات لدينا صغيرة، فإن إضافة فحص للـ null يوفر عليك المتاعب عندما يُعاد استخدام المنطق نفسه على صفحات أكبر وأكثر ديناميكية. + +## تحديد العنصر بواسطة ID – نهج بديل + +أحياناً قد يكون لديك بالفعل مرجع إلى جذر المستند وتفضّل البحث بنمط الاستعلام. استخدام محددات CSS (`QuerySelector`) هو طريقة أخرى لـ **locate element by id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **متى تستخدم أي منهما؟** `GetElementById` أسرع قليلاً لأنها بحث تجزئة مباشر. `QuerySelector` يتفوق عندما تحتاج إلى محددات معقدة (مثال: `div > p.highlight`). + +## تغيير نمط عنصر HTML – إضافة عريض ومائل + +مع العنصر في يدك، الخطوة التالية هي **change HTML element style**. تُظهر Aspose.Html كائن `Style` حيث يمكنك تعديل خصائص CSS أو استخدام تعداد `WebFontStyle` لتطبيق عدة سمات خط في آن واحد. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +هذه السطر الواحد يضبط `font-weight` للعنصر إلى `bold` و`font-style` إلى `italic`. في الخلفية تقوم Aspose.Html بترجمة التعداد إلى سلسلة CSS المناسبة. + +### مثال كامل يعمل + +جمع كل القطع معاً ينتج برنامجًا مدمجًا يمكنك تجميعه وتشغيله فورًا: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**الناتج المتوقع** + +``` +Rendered HTML: +

Hello world

+``` + +علامة `

` الآن تحمل سمة `style` مضمنة تجعل النص عريضًا ومائلًا—تمامًا ما أردنا. + +## الحالات الحدية والمشكلات الشائعة + +| الحالة | ما الذي يجب مراقبته | كيفية التعامل | +|-----------|-------------------|---------------| +| **معرف العنصر غير موجود** | `GetElementById` يعيد `null`. | إلقاء استثناء أو الرجوع إلى عنصر افتراضي. | +| **عدة عناصر تشترك في نفس الـ ID** | مواصفات HTML تقول إن الـ IDs يجب أن تكون فريدة، لكن صفحات العالم الحقيقي أحياناً تكسر القاعدة. | `GetElementById` يعيد أول تطابق؛ فكر في استخدام `QuerySelectorAll` إذا كنت بحاجة للتعامل مع التكرارات. | +| **تعارض الأنماط** | قد يتم استبدال الأنماط المضمنة الحالية. | أضف إلى كائن `Style` بدلاً من تعيين سلسلة `style` بالكامل: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **العرض في المتصفح** | بعض المتصفحات تتجاهل `WebFontStyle` إذا كان للعنصر فئة CSS ذات أولوية أعلى. | استخدم `!important` عبر `paragraph.Style.SetProperty("font-weight", "bold", "important");` إذا لزم الأمر. | + +## نصائح احترافية للمشاريع الواقعية + +- **قم بتخزين المستند في الذاكرة** إذا كنت تعالج العديد من العناصر؛ إنشاء `HTMLDocument` جديد لكل قطعة صغيرة قد يضر بالأداء. +- **اجمع تغييرات النمط** في عملية `Style` واحدة لتجنب عدة عمليات إعادة تدفق DOM. +- **استفد من محرك العرض في Aspose.Html** لتصدير المستند النهائي كملف PDF أو صورة—مفيد لأدوات التقارير. + +## تأكيد بصري (اختياري) + +إذا كنت تفضّل رؤية النتيجة في المتصفح، يمكنك حفظ السلسلة المولدة إلى ملف `.html`: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +افتح `output.html` وسترى **Hello world** معروضاً بخط عريض + مائل. + +![مثال إنشاء مستند HTML C# يُظهر فقرة عريضة ومائلة](/images/create-html-document-csharp.png "إنشاء مستند HTML C# – النتيجة المعروضة") + +*نص بديل: إنشاء مستند HTML C# – النتيجة المعروضة بنص عريض ومائل.* + +## الخلاصة + +لقد **أنشأنا مستند HTML C#**، **حصلنا على عنصر بواسطة id**، **حددنا عنصرًا بواسطة id**، **غيّرنا نمط عنصر HTML**، وأخيرًا **أضفنا عريض ومائل**—كل ذلك بضع أسطر باستخدام Aspose.Html. النهج بسيط، يعمل في أي بيئة .NET، ويتوسع إلى عمليات تعديل DOM أكبر. + +هل أنت مستعد للخطوة التالية؟ جرّب استبدال `WebFontStyle` بتعدادات أخرى مثل `Underline` أو اجمع عدة أنماط يدويًا. أو جرّب تحميل ملف HTML خارجي وتطبيق التقنية نفسها على مئات العناصر. السماء هي الحد، والآن لديك أساس قوي للبناء عليه. + +برمجة سعيدة! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/arabic/net/html-extensions-and-conversions/_index.md b/html/arabic/net/html-extensions-and-conversions/_index.md index 980eb7013..bd698d39d 100644 --- a/html/arabic/net/html-extensions-and-conversions/_index.md +++ b/html/arabic/net/html-extensions-and-conversions/_index.md @@ -41,6 +41,8 @@ url: /ar/net/html-extensions-and-conversions/ قم بتحويل HTML إلى PDF بسهولة باستخدام Aspose.HTML for .NET. اتبع دليلنا خطوة بخطوة واكتشف قوة تحويل HTML إلى PDF. ### [إنشاء PDF من HTML – دليل خطوة بخطوة بلغة C#](./create-pdf-from-html-c-step-by-step-guide/) دليل خطوة بخطوة لإنشاء ملف PDF من HTML باستخدام C# ومكتبة Aspose.HTML. +### [إنشاء PDF من HTML باستخدام Aspose – دليل خطوة بخطوة بلغة C#](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +دليل شامل لإنشاء ملفات PDF من مستندات HTML باستخدام Aspose وC# خطوة بخطوة. ### [إنشاء مستند HTML بنص منسق وتصديره إلى PDF – دليل كامل](./create-html-document-with-styled-text-and-export-to-pdf-full/) دليل شامل لإنشاء مستند HTML بنص منسق وتصديره إلى PDF باستخدام Aspose.HTML. ### [تحويل EPUB إلى صورة في .NET باستخدام Aspose.HTML](./convert-epub-to-image/) @@ -63,6 +65,8 @@ url: /ar/net/html-extensions-and-conversions/ تحويل HTML إلى MHTML في .NET باستخدام Aspose.HTML - دليل خطوة بخطوة لأرشفة محتوى الويب بكفاءة. تعرف على كيفية استخدام Aspose.HTML لـ .NET لإنشاء أرشيفات MHTML. ### [تحويل HTML إلى PNG في .NET باستخدام Aspose.HTML](./convert-html-to-png/) اكتشف كيفية استخدام Aspose.HTML for .NET لمعالجة مستندات HTML وتحويلها. دليل خطوة بخطوة لتطوير .NET بشكل فعال. +### [تحويل HTML إلى صورة في C# – دليل كامل](./convert-html-to-image-in-c-complete-guide/) +دليل شامل خطوة بخطوة لتحويل HTML إلى صورة باستخدام Aspose.HTML في C#. تعلم الخيارات المتاحة وأمثلة التعليمات البرمجية. ### [تحويل HTML إلى TIFF في .NET باستخدام Aspose.HTML](./convert-html-to-tiff/) تعرف على كيفية تحويل HTML إلى TIFF باستخدام Aspose.HTML لـ .NET. اتبع دليلنا خطوة بخطوة لتحسين محتوى الويب بكفاءة. ### [تحويل HTML إلى XPS في .NET باستخدام Aspose.HTML](./convert-html-to-xps/) @@ -73,6 +77,9 @@ url: /ar/net/html-extensions-and-conversions/ تعلم كيفية حفظ مستند HTML كملف ZIP باستخدام Aspose.HTML في C# خطوة بخطوة. ### [حفظ HTML إلى ZIP في C# – مثال كامل في الذاكرة](./save-html-to-zip-in-c-complete-in-memory-example/) تعلم كيفية حفظ مستند HTML كملف ZIP في الذاكرة باستخدام C# ومكتبة Aspose.HTML. +### [حفظ HTML كملف ZIP في C# – دليل كامل مع تخزين مخصص](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +اكتشف كيفية حفظ ملفات HTML كملفات ZIP باستخدام C# مع تخزين مخصص خطوة بخطوة باستخدام Aspose.HTML. +### [ضغط HTML باستخدام Aspose.HTML – دليل كامل](./how-to-zip-html-with-aspose-html-complete-guide/) ## خاتمة diff --git a/html/arabic/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/arabic/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..bca156af3 --- /dev/null +++ b/html/arabic/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,187 @@ +--- +category: general +date: 2026-03-21 +description: تحويل HTML إلى صورة باستخدام Aspose.HTML في C#. تعلّم كيفية حفظ HTML + كملف PNG، وتحديد حجم الصورة عند العرض، وكتابة الصورة إلى ملف في بضع خطوات فقط. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: ar +og_description: حوّل HTML إلى صورة بسرعة. يوضح هذا الدليل كيفية حفظ HTML كملف PNG، + وضبط حجم الصورة عند العرض، وكتابة الصورة إلى ملف باستخدام Aspose.HTML. +og_title: تحويل HTML إلى صورة في C# – دليل خطوة بخطوة +tags: +- Aspose.HTML +- C# +- Image Rendering +title: تحويل HTML إلى صورة في C# – دليل كامل +url: /ar/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convert HTML to Image in C# – Complete Guide + +هل احتجت يومًا إلى **convert HTML to image** من أجل صورة مصغرة للوحة التحكم، أو معاينة بريد إلكتروني، أو تقرير PDF؟ إنها حالة تظهر أكثر مما تتوقع، خاصةً عندما تتعامل مع محتوى ويب ديناميكي يجب تضمينه في مكان آخر. + +الأخبار السارة؟ مع Aspose.HTML يمكنك **convert HTML to image** في بضع أسطر فقط، وستتعلم أيضًا كيفية *save HTML as PNG*، التحكم بأبعاد الإخراج، و*write image to file* دون عناء. + +في هذا الدرس سنستعرض كل ما تحتاج معرفته: من تحميل صفحة عن بُعد إلى تعديل حجم العرض، وأخيرًا حفظ النتيجة كملف PNG على القرص. لا أدوات خارجية، ولا حيل سطر أوامر معقدة—فقط كود C# نقي يمكنك إدراجه في أي مشروع .NET. + +## What You’ll Learn + +- كيف تقوم بـ **render webpage to PNG** باستخدام فئة `HTMLDocument` الخاصة بـ Aspose.HTML. +- الخطوات الدقيقة لـ **set image size rendering** حتى يتطابق الإخراج مع متطلبات التخطيط الخاصة بك. +- طرق لـ **write image to file** بأمان، مع معالجة التدفقات ومسارات الملفات. +- نصائح لتصحيح المشكلات الشائعة مثل الخطوط المفقودة أو مهلات الشبكة. + +### Prerequisites + +- .NET 6.0 أو أحدث (تعمل الواجهة البرمجية مع .NET Framework أيضًا، لكن يُنصح بـ .NET 6+). +- إشارة إلى حزمة NuGet الخاصة بـ Aspose.HTML for .NET (`Aspose.Html`). +- إلمام أساسي بـ C# و async/await (اختياري لكن مفيد). + +إذا كان لديك هذه المتطلبات، فأنت جاهز للبدء في تحويل HTML إلى صورة فورًا. + +## Step 1: Load the Web Page – The Foundation of Converting HTML to Image + +قبل أن يتم أي عرض، تحتاج إلى كائن `HTMLDocument` يمثل الصفحة التي تريد التقاطها. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*لماذا هذا مهم:* يقوم `HTMLDocument` بتحليل HTML، وحل CSS، وبناء DOM. إذا تعذر تحميل المستند (مثلاً مشكلة في الشبكة)، فإن العرض اللاحق سينتج صورة فارغة. تأكد دائمًا من إمكانية الوصول إلى URL قبل المتابعة. + +## Step 2: Set Image Size Rendering – Controlling Width, Height, and Quality + +يتيح لك Aspose.HTML ضبط أبعاد الإخراج بدقة باستخدام `ImageRenderingOptions`. هنا تقوم بـ **set image size rendering** لتتناسب مع تخطيطك المستهدف. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*نصيحة احترافية:* إذا تركت `Width` و `Height`، سيستخدم Aspose.HTML الحجم الأصلي للصفحة، والذي قد يكون غير متوقع لتصاميم الاستجابة. تحديد أبعاد صريحة يضمن أن مخرجات **save HTML as PNG** تظهر بالضبط كما تتوقع. + +## Step 3: Write Image to File – Persisting the Rendered PNG + +الآن بعد أن أصبح المستند جاهزًا وتم ضبط خيارات العرض، يمكنك أخيرًا **write image to file**. استخدام `FileStream` يضمن إنشاء الملف بأمان، حتى إذا لم يكن المجلد موجودًا بعد. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +بعد تشغيل هذا الجزء، ستجد `page.png` في الموقع الذي حددته. لقد قمت للتو بـ **rendered webpage to PNG** وكتبتها إلى القرص في عملية واحدة بسيطة. + +### Expected Result + +افتح `C:\Temp\page.png` بأي عارض صور. يجب أن ترى لقطة دقيقة لـ `https://example.com`، معروضة بدقة 1024 × 768 بكسل مع حواف ناعمة بفضل مضاد التعرج. إذا احتوت الصفحة على محتوى ديناميكي (مثل العناصر التي يولدها JavaScript)، فسيتم التقاطها طالما تم تحميل DOM بالكامل قبل العرض. + +## Step 4: Handling Edge Cases – Fonts, Authentication, and Large Pages + +بينما يعمل التدفق الأساسي لمعظم المواقع العامة، غالبًا ما تواجه السيناريوهات الواقعية تحديات غير متوقعة: + +| Situation | What to Do | +|-----------|------------| +| **خطوط مخصصة لا يتم تحميلها** | قم بدمج ملفات الخط محليًا واستخدم `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **صفحات خلف المصادقة** | استخدم نسخة `HTMLDocument` التي تقبل `HttpWebRequest` مع ملفات تعريف الارتباط أو الرموز. | +| **صفحات طويلة جدًا** | قم بزيادة `Height` أو فعّل `PageScaling` في `ImageRenderingOptions` لتجنب القطع. | +| **ارتفاع استهلاك الذاكرة** | اعرض على أجزاء باستخدام نسخة `RenderToImage` التي تقبل منطقة `Rectangle`. | + +معالجة هذه التفاصيل الخاصة بـ *write image to file* يضمن أن خط أنابيب `convert html to image` يبقى قويًا في بيئة الإنتاج. + +## Step 5: Full Working Example – Copy‑Paste Ready + +فيما يلي البرنامج الكامل، جاهز للترجمة. يتضمن جميع الخطوات، ومعالجة الأخطاء، والتعليقات التي تحتاجها. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +شغّل هذا البرنامج، وسترى رسالة التأكيد في وحدة التحكم. سيكون ملف PNG بالضبط ما تتوقعه عندما تقوم بـ **render webpage to PNG** يدويًا في المتصفح وتلتقط صورة شاشة—لكن أسرع وبشكل آلي بالكامل. + +## Frequently Asked Questions + +**س: هل يمكنني تحويل ملف HTML محلي بدلاً من URL؟** +بالطبع. فقط استبدل URL بمسار ملف: `new HTMLDocument(@"C:\myPage.html")`. + +**س: هل أحتاج إلى ترخيص لـ Aspose.HTML؟** +ترخيص التقييم المجاني يعمل للتطوير والاختبار. للإنتاج، اشترِ ترخيصًا لإزالة علامة التقييم. + +**س: ماذا لو استخدمت الصفحة JavaScript لتحميل المحتوى بعد التحميل الأولي؟** +يقوم Aspose.HTML بتنفيذ JavaScript بشكل متزامن أثناء التحليل، لكن السكريبتات الطويلة قد تحتاج إلى تأخير يدوي. يمكنك استخدام `HTMLDocument.WaitForReadyState` قبل العرض. + +## Conclusion + +أصبح لديك الآن حل متكامل لتحويل **convert HTML to image** في C#. باتباع الخطوات أعلاه يمكنك **save HTML as PNG**، وضبط **set image size rendering** بدقة، والقيام بـ **write image to file** بثقة على أي بيئة Windows أو Linux. + +من لقطات الشاشة البسيطة إلى إنشاء تقارير آلية، هذه التقنية تتوسع بسهولة. بعد ذلك، جرّب تجربة صيغ إخراج أخرى مثل JPEG أو BMP، أو دمج الكود في واجهة API لـ ASP.NET Core التي تُعيد PNG مباشرة للمستدعين. الاحتمالات لا حصر لها تقريبًا. + +برمجة سعيدة، ولتكون صورك المُعروضة دائمًا ذات جودة بكسل‑مثالية! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/arabic/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/arabic/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..3b326d70e --- /dev/null +++ b/html/arabic/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-03-21 +description: إنشاء ملف PDF من HTML بسرعة باستخدام Aspose HTML. تعلم كيفية تحويل HTML + إلى PDF، وتحويل HTML إلى PDF، وكيفية استخدام Aspose في دليل مختصر. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: ar +og_description: إنشاء PDF من HTML باستخدام Aspose في C#. يوضح هذا الدليل كيفية عرض + HTML كـ PDF، وتحويل HTML إلى PDF، وكيفية استخدام Aspose بفعالية. +og_title: إنشاء PDF من HTML – دليل Aspose C# الكامل +tags: +- Aspose +- C# +- PDF generation +title: إنشاء ملف PDF من HTML باستخدام Aspose – دليل خطوة بخطوة بلغة C# +url: /ar/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء PDF من HTML باستخدام Aspose – دليل خطوة‑بخطوة C# + +هل احتجت يومًا إلى **إنشاء PDF من HTML** لكنك لم تكن متأكدًا أي مكتبة ستعطيك نتائج دقيقة على مستوى البكسل؟ لست وحدك. يواجه العديد من المطورين صعوبات عندما يحاولون تحويل قطعة ويب إلى مستند قابل للطباعة، لينتهي بهم الأمر بنص غير واضح أو تخطيطات مكسورة. + +الخبر السار هو أن Aspose HTML يجعل العملية بأكملها خالية من المتاعب. في هذا الدرس سنستعرض الشيفرة الدقيقة التي تحتاجها **لتحويل HTML إلى PDF**، نوضح لماذا كل إعداد مهم، ونظهر لك كيفية **تحويل HTML إلى PDF** دون أي حيل مخفية. في النهاية، ستعرف **كيفية استخدام Aspose** لإنشاء ملفات PDF موثوقة في أي مشروع .NET. + +## المتطلبات المسبقة – ما ستحتاجه قبل البدء + +- **.NET 6.0 أو أحدث** (العينة تعمل أيضًا على .NET Framework 4.7+) +- **Visual Studio 2022** أو أي بيئة تطوير تدعم C# +- حزمة **Aspose.HTML for .NET** عبر NuGet (نسخة تجريبية مجانية أو نسخة مرخصة) +- فهم أساسي لصياغة C# (ليس مطلوبًا معرفة عميقة بـ PDF) + +إذا كان لديك كل ذلك، فأنت جاهز للانطلاق. وإلا، احصل على أحدث SDK لـ .NET وقم بتثبيت حزمة NuGet باستخدام: + +```bash +dotnet add package Aspose.HTML +``` + +هذا السطر الواحد يجلب لك كل ما تحتاجه لتحويل **aspose html to pdf**. + +--- + +## الخطوة 1: إعداد المشروع لإنشاء PDF من HTML + +أول ما تقوم به هو إنشاء تطبيق console جديد (أو دمج الشيفرة في خدمة موجودة). إليك هيكلًا بسيطًا لملف `Program.cs`: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **نصيحة احترافية:** إذا رأيت `Aspise.Html.Rendering.Text` في عينات أقدم، استبدله بـ `Aspose.Html.Rendering.Text`. الخطأ المطبعي سيتسبب في حدوث خطأ تجميعي. + +استخدام المساحات الاسمية الصحيحة يضمن أن المترجم يستطيع العثور على الفئة **TextOptions** التي سنحتاجها لاحقًا. + +## الخطوة 2: بناء مستند HTML (Render HTML to PDF) + +الآن نقوم بإنشاء HTML المصدر. يتيح لك Aspose تمرير سلسلة نصية خام، مسار ملف، أو حتى عنوان URL. لهذا العرض سنبقي الأمور بسيطة: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +لماذا نمرر سلسلة نصية؟ لأنها تتجنب عمليات I/O على نظام الملفات، تُسرّع التحويل، وتضمن أن HTML الذي تراه في الشيفرة هو نفسه ما سيتم عرضه. إذا كنت تفضّل التحميل من ملف، ما عليك سوى استبدال معامل المُنشئ بمسار ملف URI. + +## الخطوة 3: تحسين عرض النص (Convert HTML to PDF with Better Quality) + +غالبًا ما يحدد عرض النص ما إذا كان PDF الخاص بك يبدو واضحًا أو غير واضح. توفر Aspose فئة `TextOptions` التي تسمح لك بتمكين **sub‑pixel hinting**—وهو أمر أساسي لإخراج عالي الدقة DPI. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +تمكين `UseHinting` يكون مفيدًا خصوصًا عندما يحتوي HTML المصدر على خطوط مخصصة أو أحجام خطوط صغيرة. بدون ذلك، قد تلاحظ حواف متعرجة في PDF النهائي. + +## الخطوة 4: ربط خيارات النص بإعدادات تحويل PDF (How to Use Aspose) + +بعد ذلك، نربط تلك الخيارات النصية بـ PDF renderer. هنا يتألق **aspose html to pdf** حقًا—فكل شيء من حجم الصفحة إلى الضغط يمكن ضبطه. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +يمكنك حذف `PageSetup` إذا كنت راضيًا عن حجم A4 الافتراضي. الفكرة الأساسية هي أن كائن `TextOptions` يعيش داخل `PdfRenderingOptions`، وهكذا تخبر Aspose *كيف* يعرض النص. + +## الخطوة 5: تحويل HTML وحفظ PDF (Convert HTML to PDF) + +أخيرًا، نقوم ببث الناتج إلى ملف. استخدام كتلة `using` يضمن إغلاق مقبض الملف بشكل صحيح، حتى لو حدث استثناء. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +عند تشغيل البرنامج، ستجد `output.pdf` بجوار الملف التنفيذي. افتحه، وسترى عنوانًا وفقرة نظيفة—تمامًا كما تم تعريفهما في سلسلة HTML. + +### النتيجة المتوقعة + +![إنشاء PDF من مثال HTML](https://example.com/images/pdf-output.png "إنشاء PDF من مثال HTML") + +*تُظهر لقطة الشاشة ملف PDF المُولد مع العنوان “Hello, Aspose!” معروضًا بوضوح بفضل تلميحات النص.* + +--- + +## أسئلة شائعة وحالات خاصة + +### 1. ماذا لو كان HTML الخاص بي يشير إلى موارد خارجية (صور، CSS)؟ + +يقوم Aspose بحل عناوين URL النسبية بناءً على URI الأساسي للمستند. إذا كنت تمرر سلسلة نصية خام، عيّن الـ URI الأساسي يدويًا: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +الآن أي `` سيُبحث عنه بالنسبة إلى `C:/MyProject/`. + +### 2. كيف يمكنني تضمين خطوط غير مثبتة على الخادم؟ + +أضف كتلة ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### الخطوة 4: تكوين خيارات الحفظ لاستخدام التخزين المخصص + +`HtmlSaveOptions` يتيح لنا إخبار Aspose بتجميع كل شيء في ملف ZIP. خاصية `OutputStorage` (القديمة) تستقبل مثيل `MyStorage` الخاص بنا. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **ملاحظة:** في Aspose HTML 23.9+ تُسمى الخاصية `OutputStorage` لكنها مُعلّمة كمهجورة. البديل الحديث هو `ZipOutputStorage`. الكود أدناه يعمل مع كلاهما لأن الواجهة هي نفسها. + +### الخطوة 5: حفظ المستند كأرشيف ZIP + +اختر مجلدًا هدفًا (أو stream) ودع Aspose يتولى العملية. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +عند انتهاء البرنامج ستجد `output.zip` يحتوي على: + +* `index.html` – المستند الرئيسي. +* أي صور مدمجة، ملفات CSS، أو سكريبتات (إذا كان HTML الخاص بك يشير إليها). + +يمكنك فتح ملف ZIP بأي مدير أرشيف للتحقق من البنية. + +--- + +## التحقق من النتيجة (اختياري) + +إذا أردت فحص الأرشيف برمجياً دون استخراجها إلى القرص: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +المخرجات المتوقعة: + +``` +- index.html (452 bytes) +``` + +إذا كان لديك صور أو CSS، فستظهر كمدخلات إضافية. هذا الفحص السريع يؤكد أن **create html zip archive** عمل كما هو متوقع. + +## الأسئلة الشائعة وحالات الحافة + +| السؤال | الإجابة | +|----------|--------| +| **ماذا لو احتجت إلى كتابة ملف ZIP مباشرة إلى تدفق الاستجابة؟** | أرجع الـ `MemoryStream` الذي تحصل عليه من `MyStorage` بعد `document.Save`. حوّله إلى `byte[]` واكتبها إلى `HttpResponse.Body`. | +| **هل سيقوم HTML الخاص بي بتحميل عناوين URL الخارجية؟** | لا. Aspose يضم فقط الموارد التي تكون *مضمنة* (مثل `` أو الملفات المحلية). بالنسبة للأصول البعيدة يجب عليك تحميلها أولاً وتعديل العلامات. | +| **هل يجب تجاهل خاصية `OutputStorage` التي تم تعليمها كمهجورة؟** | لا تزال تعمل، لكن `ZipOutputStorage` الأحدث يقدم نفس الـ API باسم مختلف. استبدل `OutputStorage` بـ `ZipOutputStorage` إذا أردت بناء خالٍ من التحذيرات. | +| **هل يمكنني تشفير ملف ZIP؟** | نعم. بعد الحفظ، افتح الملف باستخدام `System.IO.Compression.ZipArchive` واضبط كلمة مرور باستخدام مكتبات طرف ثالث مثل `SharpZipLib`. Aspose نفسها لا توفر تشفيراً. | + +## مثال كامل يعمل (نسخ‑لصق) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +شغّل البرنامج، افتح `output.zip`، وسترى ملف `index.html` واحد يعرض عنوان “Hello from ZIP!” عند فتحه في المتصفح. + +## الخلاصة + +أنت الآن تعرف **كيفية حفظ HTML كملف ZIP** في C# باستخدام فئة **تخزين مخصص**، وكيفية **تصدير HTML إلى ZIP**، وكيفية **إنشاء أرشيف HTML مضغوط** جاهز للتوزيع. النمط مرن—استبدل `MemoryStream` بـ stream سحابي، أضف تشفيرًا، أو دمجه في واجهة ويب API تُعيد ملف ZIP عند الطلب. + +هل أنت مستعد للخطوة التالية؟ جرّب إمداد صفحة ويب كاملة مع الصور والأنماط، أو ربط التخزين بـ Azure Blob Storage لتجاوز نظام الملفات المحلي تمامًا. السماء هي الحد عندما تجمع بين قدرات ZIP في Aspose.HTML ومنطق التخزين الخاص بك. + +برمجة سعيدة، ولتكن أرشيفاتك دائمًا مرتبة! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/chinese/net/generate-jpg-and-png-images/_index.md b/html/chinese/net/generate-jpg-and-png-images/_index.md index 3a7bc53dc..af2117f8f 100644 --- a/html/chinese/net/generate-jpg-and-png-images/_index.md +++ b/html/chinese/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET 提供了一种将 HTML 转换为图像的简单方法。 了解如何在使用 Aspose.HTML for .NET 将 DOCX 文档转换为 PNG 或 JPG 图像时启用抗锯齿,以提升图像质量。 ### [使用 C# 将 docx 转换为 png 并创建 zip 存档教程](./convert-docx-to-png-create-zip-archive-c-tutorial/) 学习如何使用 C# 将 DOCX 文档转换为 PNG 图像并打包为 ZIP 文件的完整步骤。 +### [使用 C# 将 HTML 转换为 PNG 并导出 ZIP – 完整指南](./convert-html-to-png-full-c-guide-with-zip-export/) +本教程详细演示如何使用 C# 将 HTML 渲染为 PNG 图像并将结果打包为 ZIP 文件,步骤完整。 ## 结论 diff --git a/html/chinese/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/chinese/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..a5695a842 --- /dev/null +++ b/html/chinese/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-03-21 +description: 将 HTML 转换为 PNG 并将其渲染为图像,同时将 HTML 保存为 ZIP。学习如何在 HTML 中应用字体样式,并在几步内为 p + 元素添加粗体。 +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: zh +og_description: 快速将HTML转换为PNG。本指南展示如何将HTML渲染为图像、将HTML保存为ZIP、应用字体样式以及为

元素添加粗体。 +og_title: 将HTML转换为PNG – 完整C#教程 +tags: +- Aspose +- C# +title: 将HTML转换为PNG – 完整C#指南与ZIP导出 +url: /zh/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 将 HTML 转换为 PNG – 完整 C# 指南(含 ZIP 导出) + +是否曾经需要**将 HTML 转换为 PNG**,却不确定哪个库能够在不引入无头浏览器的情况下完成?你并不孤单。在许多项目中——邮件缩略图、文档预览或快速查看图片——将网页转换为静态图片是一个真实的需求。 + +好消息是?使用 Aspose.HTML,你可以**将 HTML 渲染为图像**,在运行时微调标记,甚至**将 HTML 保存为 ZIP**以便后续分发。在本教程中,我们将逐步演示一个完整、可运行的示例,**对 HTML 应用字体样式**,具体来说是**为 p 元素加粗**,然后生成 PNG 文件。完成后,你将拥有一个单一的 C# 类,能够从加载页面到归档资源全部搞定。 + +## 你需要准备的环境 + +- .NET 6.0 或更高(该 API 也支持 .NET Core) +- Aspose.HTML for .NET 6+(NuGet 包 `Aspose.Html`) +- 对 C# 语法的基本了解(不需要高级概念) + +就这些。无需外部浏览器、phantomjs,只需纯托管代码。 + +## 第一步 – 加载 HTML 文档 + +首先我们将源文件(或 URL)加载到 `HTMLDocument` 对象中。这一步是后续**将 HTML 渲染为图像**和**将 HTML 保存为 zip**的基础。 + +```csharp +using Aspose.Html; +using System.IO; + +///

+/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*为什么重要:* `HTMLDocument` 类会解析标记,构建 DOM,并解析链接的资源(CSS、图片、字体)。没有正确的文档对象,你就无法操作样式或进行渲染。 + +## 第二步 – 应用字体样式 HTML(为 p 加粗) + +接下来我们通过遍历每个 `

` 元素并将其 `font-weight` 设置为 bold,**对 HTML 应用字体样式**。这是一种在不修改原始文件的情况下**为 p 标签加粗**的编程方式。 + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*小技巧:* 如果只需要对一部分加粗,可以将选择器改为更具体的,例如 `"p.intro"`。 + +## 第三步 – 将 HTML 渲染为图像(将 HTML 转换为 PNG) + +DOM 准备好后,我们配置 `ImageRenderingOptions` 并调用 `RenderToImage`。这就是**将 html 转换为 png**的魔法所在。 + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*为什么选项重要:* 设置固定的宽度/高度可以防止输出文件过大,而抗锯齿则能得到更平滑的视觉效果。如果你更倾向于更小的文件大小,也可以将 `options` 的 `ImageFormat` 切换为 `ImageFormat.Jpeg`。 + +## 第四步 – 将 HTML 保存为 ZIP(打包资源) + +通常你需要将原始 HTML 与其 CSS、图片和字体一起发布。Aspose.HTML 的 `ZipArchiveSaveOptions` 正好可以完成此操作。我们还接入了自定义的 `ResourceHandler`,使所有外部资源都写入与归档同一文件夹。 + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*边缘情况:* 如果你的 HTML 引用了需要身份验证的远程图片,默认处理器会失败。在这种情况下,你可以扩展 `MyResourceHandler` 来注入 HTTP 头部。 + +## 第五步 – 在单个转换器类中串联所有步骤 + +下面是完整、可直接运行的类,它把前面的所有步骤整合在一起。你可以把它复制粘贴到控制台应用中,调用 `Convert`,即可看到生成的文件。 + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### 预期输出 + +运行上述代码片段后,你将在 `outputDirectory` 中看到两个文件: + +| 文件 | 描述 | +|------|------| +| `page.png` | 1200 × 800 PNG 渲染的源 HTML,所有段落均已 **加粗**。 | +| `archive.zip` | 包含原始 `input.html`、其 CSS、图片以及所有网络字体的 ZIP 包——非常适合离线分发。 | + +你可以在任意图像查看器中打开 `page.png`,验证加粗样式是否生效;解压 `archive.zip` 则可以看到未修改的 HTML 及其资源。 + +## 常见问题与注意事项 + +- **如果 HTML 包含 JavaScript 会怎样?** + Aspose.HTML 在渲染时**不执行**脚本,因此动态内容不会出现。若需要完整渲染的页面,需要使用无头浏览器,但对于静态模板而言,此方法更快更轻量。 + +- **可以将输出格式改为 JPEG 或 BMP 吗?** + 可以——只需更改 `ImageRenderingOptions` 的 `ImageFormat` 属性,例如 `options.ImageFormat = ImageFormat.Jpeg;`。 + +- **需要手动释放 `HTMLDocument` 吗?** + 该类实现了 `IDisposable`。在长期运行的服务中,建议使用 `using` 块或在完成后调用 `document.Dispose()`。 + +- **自定义的 `MyResourceHandler` 是如何工作的?** + 它会接收每个外部资源(CSS、图片、字体),并将其写入你指定的文件夹。这样可以确保 ZIP 包中完整复制 HTML 所引用的所有内容。 + +## 结论 + +现在,你已经拥有一个紧凑、可投入生产的解决方案,能够**将 html 转换为 png**、**将 html 渲染为图像**、**将 html 保存为 zip**、**对 html 应用字体样式**以及**为 p 加粗**——全部只需几行 C# 代码。代码自包含,兼容 .NET 6+,可直接嵌入任何需要快速获取网页视觉快照的后端服务。 + +准备好下一步了吗?尝试更改渲染尺寸,实验其他 CSS 属性(如 `font-family` 或 `color`),或将此转换器集成到 ASP.NET Core 端点中,以按需返回 PNG。可能性无限,而使用 Aspose.HTML 你可以摆脱笨重的浏览器依赖。 + +如果你遇到问题或有扩展想法,欢迎在下方留言。祝编码愉快! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/chinese/net/html-document-manipulation/_index.md index d79966fc2..af6bad6e1 100644 --- a/html/chinese/net/html-document-manipulation/_index.md +++ b/html/chinese/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aspose.HTML for .NET 以其简单性和强大性脱颖而出。它使您能够 使用 Aspose.HTML for .NET 释放 Web 开发的潜力。轻松创建、转换和操作 HTML 文档。 ### [在 C# 中从字符串创建 HTML – 自定义资源处理程序指南](./create-html-from-string-in-c-custom-resource-handler-guide/) 了解如何使用自定义资源处理程序将字符串转换为 HTML 文档。 +### [在 C# 中创建 HTML 文档 – 步骤指南](./create-html-document-c-step-by-step-guide/) +了解如何使用 Aspose.HTML for .NET 在 C# 中创建 HTML 文档的完整步骤和示例。 ## 结论 diff --git a/html/chinese/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/chinese/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..a1da613c3 --- /dev/null +++ b/html/chinese/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,186 @@ +--- +category: general +date: 2026-03-21 +description: 使用 C# 创建 HTML 文档,并学习如何通过 id 获取元素、定位元素、修改 HTML 元素样式以及使用 Aspose.Html 添加粗体和斜体。 +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: zh +og_description: 使用 C# 创建 HTML 文档,快速学习通过 ID 获取元素、定位元素、修改 HTML 元素样式,并添加粗体斜体,配有清晰的代码示例。 +og_title: 使用 C# 创建 HTML 文档 – 完整编程指南 +tags: +- Aspose.Html +- C# +- DOM manipulation +title: 使用 C# 创建 HTML 文档 – 步骤指南 +url: /zh/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 创建 HTML 文档 C# – 步骤指南 + +是否曾经需要**从头创建 HTML 文档 C#**,然后仅仅调整一个段落的外观?你并不孤单。在许多网页自动化项目中,你会生成一个 HTML 文件,按 ID 找到标签,然后应用一些样式——通常是粗体 + 斜体——而根本不打开浏览器。 + +在本教程中,我们将完整演示这一过程:创建 C# 中的 HTML 文档,**通过 id 获取元素**,**通过 id 定位元素**,**更改 HTML 元素样式**,最后使用 Aspose.Html 库**添加粗体斜体**。完成后,你将拥有一个可以直接放入任何 .NET 项目的完整可运行代码片段。 + +## 你需要的环境 + +- .NET 6 或更高版本(代码同样适用于 .NET Framework 4.7+) +- Visual Studio 2022(或任意你喜欢的编辑器) +- **Aspose.Html** NuGet 包(`Install-Package Aspose.Html`) + +仅此而已——不需要额外的 HTML 文件,不需要 Web 服务器,只需几行 C#。 + +## 创建 HTML 文档 C# – 初始化文档 + +首先,你需要一个活跃的 `HTMLDocument` 对象,让 Aspose.Html 引擎可以操作它。把它想象成打开一本全新的笔记本,准备写入你的标记。 + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **为什么重要:** 将原始字符串传递给 `HTMLDocument`,可以避免文件 I/O,所有内容都保存在内存中——非常适合单元测试或即时生成。 + +## 通过 ID 获取元素 – 查找段落 + +文档已经存在后,我们需要**通过 id 获取元素**。DOM API 提供 `GetElementById`,如果 ID 不存在则返回 `IElement` 引用或 `null`。 + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **小技巧:** 即使我们的标记很小,加入空值检查也能在同样的逻辑被复用于更大、动态页面时避免头疼。 + +## 通过 ID 定位元素 – 替代方法 + +有时你已经拥有文档根节点的引用,并倾向于使用查询式搜索。使用 CSS 选择器(`QuerySelector`)是另一种**通过 id 定位元素**的方式: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **何时使用哪种?** `GetElementById` 稍快一些,因为它是直接的哈希查找。`QuerySelector` 在需要复杂选择器(例如 `div > p.highlight`)时更有优势。 + +## 更改 HTML 元素样式 – 添加粗体斜体 + +拿到元素后,下一步是**更改 HTML 元素样式**。Aspose.Html 暴露了一个 `Style` 对象,你可以在其中调整 CSS 属性,或使用便捷的 `WebFontStyle` 枚举一次性应用多个字体特性。 + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +这行代码将元素的 `font-weight` 设置为 `bold`,`font-style` 设置为 `italic`。在内部,Aspose.Html 会把枚举转换为相应的 CSS 字符串。 + +### 完整可运行示例 + +将所有片段组合在一起,就得到一个紧凑、独立的程序,你可以立即编译运行: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**预期输出** + +``` +Rendered HTML: +

Hello world

+``` + +现在 `

` 标签带有内联 `style` 属性,使文本同时呈现粗体和斜体——正是我们想要的效果。 + +## 边缘情况与常见陷阱 + +| 情况 | 需要注意的点 | 处理方式 | +|-----------|-------------------|---------------| +| **ID 不存在** | `GetElementById` 返回 `null`。 | 抛出异常或回退到默认元素。 | +| **多个元素共享同一 ID** | HTML 规范要求 ID 唯一,但实际页面有时会违规。 | `GetElementById` 返回第一个匹配;如果需要处理重复,可使用 `QuerySelectorAll`。 | +| **样式冲突** | 现有的内联样式可能被覆盖。 | 向 `Style` 对象追加而不是直接设置整个 `style` 字符串:`paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **在浏览器中的渲染** | 如果元素已有更高特异性的 CSS 类,某些浏览器会忽略 `WebFontStyle`。 | 如有必要,通过 `paragraph.Style.SetProperty("font-weight", "bold", "important");` 使用 `!important`。 | + +## 实战小贴士 + +- **缓存文档**:如果要处理大量元素,避免为每个小片段都创建新的 `HTMLDocument`,这会影响性能。 +- **合并样式修改**:在一次 `Style` 事务中完成所有更改,以避免多次 DOM 重排。 +- **利用 Aspose.Html 的渲染引擎**:将最终文档导出为 PDF 或图片——对报表工具非常有用。 + +## 可视化确认(可选) + +如果想在浏览器中查看结果,可以将渲染后的字符串保存为 `.html` 文件: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +打开 `output.html`,你会看到 **Hello world** 以粗体 + 斜体显示。 + +![Create HTML Document C# 示例,显示粗体斜体段落](/images/create-html-document-csharp.png "Create HTML Document C# – 渲染输出") + +*Alt text: Create HTML Document C# 示例,显示粗体斜体文本。* + +## 结论 + +我们已经**创建了 HTML 文档 C#**,**通过 id 获取元素**,**通过 id 定位元素**,**更改了 HTML 元素样式**,并最终**添加了粗体斜体**——全部使用 Aspose.Html 的几行代码完成。该方法简洁、适用于任何 .NET 环境,并能扩展到更大规模的 DOM 操作。 + +准备好下一步了吗?尝试将 `WebFontStyle` 换成其他枚举如 `Underline`,或手动组合多个样式。亦或加载外部 HTML 文件,对数百个元素执行相同技术。可能性无限,而你已经拥有坚实的基础可以继续构建。 + +祝编码愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/chinese/net/html-extensions-and-conversions/_index.md b/html/chinese/net/html-extensions-and-conversions/_index.md index a6c24babf..6d4d13622 100644 --- a/html/chinese/net/html-extensions-and-conversions/_index.md +++ b/html/chinese/net/html-extensions-and-conversions/_index.md @@ -59,6 +59,8 @@ Aspose.HTML for .NET 不仅仅是一个库;它是 Web 开发领域的变革者 使用 Aspose.HTML 在 .NET 中将 HTML 转换为 MHTML - 高效 Web 内容存档的分步指南。了解如何使用 Aspose.HTML for .NET 创建 MHTML 存档。 ### [使用 Aspose.HTML 在 .NET 中将 HTML 转换为 PNG](./convert-html-to-png/) 了解如何使用 Aspose.HTML for .NET 来操作和转换 HTML 文档。高效 .NET 开发的分步指南。 +### [在 C# 中将 HTML 转换为图像 – 完整指南](./convert-html-to-image-in-c-complete-guide/) +使用 Aspose.HTML for .NET 在 C# 中将 HTML 转换为图像的完整分步指南,涵盖代码示例和关键技巧。 ### [使用 Aspose.HTML 在 .NET 中将 HTML 转换为 TIFF](./convert-html-to-tiff/) 了解如何使用 Aspose.HTML for .NET 将 HTML 转换为 TIFF。按照我们的分步指南进行有效的 Web 内容优化。 ### [使用 Aspose.HTML 在 .NET 中将 HTML 转换为 XPS](./convert-html-to-xps/) @@ -69,11 +71,16 @@ Aspose.HTML for .NET 不仅仅是一个库;它是 Web 开发领域的变革者 本完整指南展示如何使用 Aspose.HTML for .NET 创建带样式的 HTML 文档并将其导出为 PDF,包含详细步骤和代码示例。 ### [使用 Aspose.HTML 在 C# 中将 HTML 创建为 PDF – 完整指南](./create-pdf-from-html-c-step-by-step-guide/) 使用 Aspose.HTML for .NET 在 C# 中将 HTML 转换为 PDF 的完整分步指南,涵盖代码示例和最佳实践。 +### [使用 Aspose.HTML 在 C# 中将 HTML 创建为 PDF – 步骤详解 C# 指南](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +通过 Aspose.HTML for .NET 的分步示例,在 C# 中将 HTML 转换为 PDF,涵盖关键代码和最佳实践。 ### [使用 Aspose.HTML 在 .NET 中将 HTML 保存为 ZIP – 完整的 C# 教程](./save-html-as-zip-complete-c-tutorial/) 使用 Aspose.HTML for .NET 将 HTML 内容打包为 ZIP 文件的完整 C# 示例,包含代码演示和关键步骤。 - +### [在 C# 中将 HTML 保存为 ZIP – 完整指南(自定义存储)](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +使用 Aspose.HTML for .NET 在 C# 中将 HTML 打包为 ZIP,并展示自定义存储的完整实现步骤。 ### [在 C# 中将 HTML 保存为 ZIP – 完整内存示例](./save-html-to-zip-in-c-complete-in-memory-example/) 演示如何使用 Aspose.HTML for .NET 在 C# 中将 HTML 内容压缩为 ZIP 文件,完整的内存操作示例。 +### [使用 Aspose.HTML 将 HTML 打包为 ZIP – 完整指南](./how-to-zip-html-with-aspose-html-complete-guide/) +使用 Aspose.HTML for .NET 在 C# 中将 HTML 打包为 ZIP 的完整指南,涵盖代码示例和关键步骤。 ## 结论 diff --git a/html/chinese/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/chinese/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..278552b59 --- /dev/null +++ b/html/chinese/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,185 @@ +--- +category: general +date: 2026-03-21 +description: 使用 Aspose.HTML 在 C# 中将 HTML 转换为图像。了解如何将 HTML 保存为 PNG、设置图像尺寸渲染,以及仅需几步即可将图像写入文件。 +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: zh +og_description: 快速将HTML转换为图像。本指南展示如何将HTML保存为PNG、设置图像尺寸渲染,以及使用 Aspose.HTML 将图像写入文件。 +og_title: 在 C# 中将 HTML 转换为图像 – 步骤指南 +tags: +- Aspose.HTML +- C# +- Image Rendering +title: 在 C# 中将 HTML 转换为图像 – 完整指南 +url: /zh/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 将 HTML 转换为图像(C#) – 完整指南 + +是否曾需要 **convert HTML to image** 来生成仪表盘缩略图、邮件预览或 PDF 报告?这种场景出现的频率往往超出你的预期,尤其是在处理必须嵌入其他位置的动态网页内容时。 + +好消息是?使用 Aspose.HTML,你只需几行代码就能 **convert HTML to image**,并且还能学习如何 *save HTML as PNG*、控制输出尺寸,以及 *write image to file*,轻松搞定。 + +在本教程中,我们将逐步讲解你需要掌握的全部内容:从加载远程页面、微调渲染尺寸,到最终将结果持久化为磁盘上的 PNG 文件。无需外部工具,也不需要繁琐的命令行技巧——只需纯 C# 代码,直接放入任意 .NET 项目即可使用。 + +## 你将学到 + +- 如何使用 Aspose.HTML 的 `HTMLDocument` 类 **render webpage to PNG**。 +- 设置 **set image size rendering** 的完整步骤,以确保输出符合布局需求。 +- 安全 **write image to file** 的方法,处理流和文件路径。 +- 常见问题的排查技巧,例如缺失字体或网络超时。 + +### 前置条件 + +- .NET 6.0 或更高版本(API 也支持 .NET Framework,但推荐使用 .NET 6+)。 +- 已引用 Aspose.HTML for .NET NuGet 包(`Aspose.Html`)。 +- 对 C# 和 async/await 有基本了解(可选,但有帮助)。 + +如果你已经具备上述条件,即可立即开始 **convert HTML to image**。 + +## 第一步:加载网页 – 转换 HTML 为图像的基础 + +在进行任何渲染之前,你需要一个代表要捕获页面的 `HTMLDocument` 实例。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Why this matters:* `HTMLDocument` 负责解析 HTML、解析 CSS 并构建 DOM。如果文档无法加载(例如网络问题),后续渲染将得到空白图像。务必在继续之前确认 URL 可访问。 + +## 第二步:设置图像尺寸渲染 – 控制宽度、高度和质量 + +Aspose.HTML 通过 `ImageRenderingOptions` 让你精细调节输出尺寸。这正是 **set image size rendering** 与目标布局匹配的地方。 + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Pro tip:* 如果省略 `Width` 和 `Height`,Aspose.HTML 将使用页面的固有尺寸,这在响应式设计下可能难以预测。显式指定尺寸可确保你的 **save HTML as PNG** 输出恰如预期。 + +## 第三步:写入图像文件 – 持久化渲染后的 PNG + +当文档准备就绪且渲染选项已设置后,你就可以 **write image to file**。使用 `FileStream` 能在文件夹尚未存在时安全创建文件。 + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +运行此代码块后,你将在指定位置看到 `page.png`。你已经 **render webpage to PNG** 并将其写入磁盘,整个过程简洁明了。 + +### 预期结果 + +使用任意图像查看器打开 `C:\Temp\page.png`。你应当看到 `https://example.com` 的忠实快照,分辨率为 1024 × 768 像素,且因抗锯齿处理而边缘平滑。如果页面包含动态内容(例如 JavaScript 生成的元素),只要在渲染前 DOM 完全加载,它们也会被捕获。 + +## 第四步:处理边缘情况 – 字体、身份验证和大页面 + +基本流程适用于大多数公开站点,但实际场景常会出现各种挑战: + +| 情况 | 处理方式 | +|-----------|------------| +| **Custom fonts not loading** | 将字体文件本地化并使用 `htmlDoc.Fonts.Add("path/to/font.ttf")` 添加。 | +| **Pages behind authentication** | 使用接受 `HttpWebRequest`(包含 Cookie 或 Token)的 `HTMLDocument` 重载。 | +| **Very tall pages** | 增大 `Height` 或在 `ImageRenderingOptions` 中启用 `PageScaling`,避免截断。 | +| **Memory usage spikes** | 使用接受 `Rectangle` 区域的 `RenderToImage` 重载分块渲染。 | + +妥善处理这些 *write image to file* 细节,可确保你的 **convert html to image** 流程在生产环境中保持稳健。 + +## 第五步:完整工作示例 – 可直接复制粘贴 + +下面是完整的程序代码,已准备好编译运行。它包含所有步骤、错误处理以及必要的注释。 + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +运行该程序后,你将在控制台看到确认信息。生成的 PNG 文件将与你在浏览器中手动 **render webpage to PNG** 并截图的效果完全一致——只不过更快且全自动。 + +## 常见问题 + +**Q: 能否将本地 HTML 文件而不是 URL 转换?** +当然可以。只需将 URL 替换为文件路径,例如 `new HTMLDocument(@"C:\myPage.html")`。 + +**Q: 使用 Aspose.HTML 是否需要许可证?** +免费评估许可证可用于开发和测试。生产环境请购买正式许可证,以去除评估水印。 + +**Q: 如果页面在初始加载后通过 JavaScript 动态加载内容怎么办?** +Aspose.HTML 在解析期间同步执行 JavaScript,但长时间运行的脚本可能需要手动延迟。可在渲染前调用 `HTMLDocument.WaitForReadyState`。 + +## 结论 + +现在,你已经掌握了在 C# 中 **convert HTML to image** 的完整端到端方案。通过上述步骤,你可以 **save HTML as PNG**、精准 **set image size rendering**,并自信地 **write image to file** 于任意 Windows 或 Linux 环境。 + +从简单的截图到自动化报告生成,这一技术具备良好的可扩展性。接下来,可尝试输出 JPEG、BMP 等其他格式,或将代码集成到 ASP.NET Core API 中,直接返回 PNG 给调用方。可能性几乎无限。 + +祝编码愉快,愿你的渲染图像始终像素完美! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/chinese/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/chinese/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..69583fe16 --- /dev/null +++ b/html/chinese/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-03-21 +description: 使用 Aspose HTML 快速将 HTML 创建为 PDF。学习将 HTML 渲染为 PDF、转换为 PDF,以及在简明教程中如何使用 + Aspose。 +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: zh +og_description: 使用 Aspose 在 C# 中将 HTML 创建为 PDF。本指南展示了如何将 HTML 渲染为 PDF、将 HTML 转换为 PDF,以及如何有效使用 + Aspose。 +og_title: 从HTML创建PDF – 完整的Aspose C#教程 +tags: +- Aspose +- C# +- PDF generation +title: 使用 Aspose 将 HTML 转换为 PDF – 步骤详解 C# 指南 +url: /zh/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose 将 HTML 创建为 PDF – 步骤指南 C# + +是否曾经需要**从 HTML 创建 PDF**,但不确定哪个库能提供像素完美的效果?你并不孤单。许多开发者在尝试将网页片段转换为可打印文档时会遇到困难,最终得到模糊的文字或布局错乱。 + +好消息是 Aspose HTML 让整个过程变得轻松无痛。在本教程中,我们将逐步演示**渲染 HTML 为 PDF**所需的完整代码,探讨每个设置为何重要,并展示如何**将 HTML 转换为 PDF**而无需任何隐藏技巧。完成后,你将了解**如何使用 Aspose**在任何 .NET 项目中可靠地生成 PDF。 + +## 前置条件 – 开始之前需要准备的内容 + +- **.NET 6.0 或更高**(示例同样适用于 .NET Framework 4.7+) +- **Visual Studio 2022** 或任何支持 C# 的 IDE +- **Aspose.HTML for .NET** NuGet 包(免费试用版或正式授权版) +- 对 C# 语法有基本了解(不需要深入的 PDF 知识) + +如果你已经具备这些条件,就可以开始了。否则,请先获取最新的 .NET SDK 并使用以下命令安装 NuGet 包: + +```bash +dotnet add package Aspose.HTML +``` + +这行代码会一次性引入进行**aspose html to pdf**转换所需的所有依赖。 + +--- + +## 步骤 1:设置项目以从 HTML 创建 PDF + +首先创建一个新的控制台应用(或将代码集成到现有服务中)。下面是一个最小的 `Program.cs` 框架: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** 如果在旧示例中看到 `Aspise.Html.Rendering.Text`,请替换为 `Aspose.Html.Rendering.Text`。拼写错误会导致编译错误。 + +使用正确的命名空间可以确保编译器能够定位我们稍后需要的 **TextOptions** 类。 + +## 步骤 2:构建 HTML 文档(将 HTML 渲染为 PDF) + +现在我们创建源 HTML。Aspose 允许你传入原始字符串、文件路径,甚至是 URL。演示中我们保持最简单的方式: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +为什么要传入字符串?它可以避免文件系统 I/O,加快转换速度,并保证代码中看到的 HTML 与实际渲染的内容完全一致。如果你更倾向于从文件加载,只需将构造函数参数换成文件 URI 即可。 + +## 步骤 3:微调文本渲染(将 HTML 转换为 PDF 并提升质量) + +文本渲染往往决定 PDF 是清晰还是模糊。Aspose 提供了 `TextOptions` 类,可让你启用子像素 hinting——这对高 DPI 输出至关重要。 + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +在源 HTML 包含自定义字体或小字号时,启用 `UseHinting` 尤为有用。否则,最终的 PDF 可能会出现锯齿状边缘。 + +## 步骤 4:将文本选项附加到 PDF 渲染配置(如何使用 Aspose) + +接下来,我们将这些文本选项绑定到 PDF 渲染器。这正是 **aspose html to pdf** 发光发热的地方——从页面尺寸到压缩方式都可以微调。 + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +如果你对默认的 A4 大小满意,可以省略 `PageSetup`。关键点在于 `TextOptions` 对象位于 `PdfRenderingOptions` 中,这就是告诉 Aspose *如何* 渲染文本的方式。 + +## 步骤 5:渲染 HTML 并保存为 PDF(将 HTML 转换为 PDF) + +最后,我们将输出流写入文件。使用 `using` 块可以确保即使出现异常,文件句柄也会被正确关闭。 + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +运行程序后,你会在可执行文件所在目录看到 `output.pdf`。打开它,你应当看到一个干净的标题和段落——完全与 HTML 字符串中定义的内容一致。 + +### 预期输出 + +![create pdf from html example output](https://example.com/images/pdf-output.png "create pdf from html example output") + +*该截图展示了生成的 PDF,其中标题 “Hello, Aspose!” 因文本 hinting 而渲染得非常锐利。* + +--- + +## 常见问题与边缘情况 + +### 1. 如果我的 HTML 引用了外部资源(图片、CSS)怎么办? + +Aspose 会根据文档的基础 URI 解析相对 URL。如果你提供的是原始字符串,需要手动设置基础 URI: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +此时任何 `` 都会相对于 `C:/MyProject/` 进行查找。 + +### 2. 如何嵌入服务器上未安装的字体? + +添加一个使用 `@font-face` 指向本地或远程字体文件的 ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### 步骤 4:配置保存选项以使用自定义存储 + +`HtmlSaveOptions` 让我们告诉 Aspose 将所有内容打包成 ZIP 文件。`OutputStorage` 属性(旧版)接受我们的 `MyStorage` 实例。 + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **注意:** 在 Aspose HTML 23.9+ 中该属性仍名为 `OutputStorage`,但已标记为过时。现代替代方案是 `ZipOutputStorage`。下面的代码同时兼容两者,因为接口相同。 + +### 步骤 5:将文档保存为 ZIP 归档 + +指定目标文件夹(或流),让 Aspose 完成剩余工作。 + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +程序结束后,你将在 `output.zip` 中看到: + +* `index.html` – 主文档。 +* 任何嵌入的图片、CSS 文件或脚本(如果你的 HTML 引用了它们)。 + +使用任意压缩管理器打开 ZIP,即可验证结构是否正确。 + +--- + +## 验证结果(可选) + +如果想在不解压到磁盘的情况下以编程方式检查归档: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +典型输出: + +``` +- index.html (452 bytes) +``` + +若包含图片或 CSS,它们会作为额外条目出现。此快速检查可确认 **create html zip archive** 已如预期工作。 + +--- + +## 常见问题与边缘情况 + +| 问题 | 答案 | +|----------|--------| +| **如果需要直接将 ZIP 写入响应流,该怎么办?** | 在 `document.Save` 之后,从 `MyStorage` 获取的 `MemoryStream` 转为 `byte[]`,写入 `HttpResponse.Body` 即可。 | +| **我的 HTML 引用了外部 URL——会自动下载吗?** | 不会。Aspose 只会打包 *嵌入的* 资源(例如 `` 或本地文件)。对于远程资产,需要先下载并在标记中进行相应修改。 | +| **`OutputStorage` 属性已标记为过时,是否可以忽略?** | 它仍然可用,但新版的 `ZipOutputStorage` 提供相同的 API,只是名称不同。若想消除警告,请将 `OutputStorage` 替换为 `ZipOutputStorage`。 | +| **可以对 ZIP 加密吗?** | 可以。保存后,使用 `System.IO.Compression.ZipArchive` 并结合第三方库(如 `SharpZipLib`)设置密码。Aspose 本身不提供加密功能。 | + +--- + +## 完整可运行示例(复制粘贴) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +运行程序,打开 `output.zip`,你会看到一个 `index.html` 文件,浏览器打开后会显示 “Hello from ZIP!” 标题。 + +--- + +## 结论 + +现在,你已经掌握了在 C# 中使用 **自定义存储** 类 **将 HTML 保存为 ZIP** 的完整方法,了解了如何 **导出 HTML 为 ZIP**,以及如何 **创建可供分发的 HTML zip archive**。该模式灵活可变——可以将 `MemoryStream` 替换为云流、添加加密,或集成到返回 ZIP 的 Web API 中。 + +准备好下一步了吗?尝试使用包含图片和样式的完整网页,或将存储接入 Azure Blob Storage,彻底摆脱本地文件系统的限制。当你将 Aspose.HTML 的 ZIP 功能与自定义存储逻辑结合时,可能性无限。 + +祝编码愉快,愿你的归档始终整洁有序! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/czech/net/generate-jpg-and-png-images/_index.md b/html/czech/net/generate-jpg-and-png-images/_index.md index 11b9c8465..d72d2ffef 100644 --- a/html/czech/net/generate-jpg-and-png-images/_index.md +++ b/html/czech/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Naučte se používat Aspose.HTML pro .NET k manipulaci s dokumenty HTML, převo Naučte se, jak při převodu dokumentů DOCX na PNG nebo JPG povolit antialiasing pro hladší výstup. ### [Převod docx na png – vytvoření zip archivu C# tutoriál](./convert-docx-to-png-create-zip-archive-c-tutorial/) Naučte se převést soubory DOCX na PNG a zabalit je do ZIP archivu pomocí C# a Aspose.HTML. +### [Převod HTML na PNG – Kompletní průvodce C# s exportem ZIP](./convert-html-to-png-full-c-guide-with-zip-export/) +Naučte se převést HTML na PNG v C# a výsledek zabalit do ZIP archivu pomocí Aspose.HTML. ## Závěr diff --git a/html/czech/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/czech/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..2ef317637 --- /dev/null +++ b/html/czech/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Převést HTML na PNG a vykreslit HTML jako obrázek při ukládání HTML do + ZIP. Naučte se použít styl písma v HTML a přidat tučný text do elementů p během + několika kroků. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: cs +og_description: Rychle převést HTML na PNG. Tento návod ukazuje, jak vykreslit HTML + jako obrázek, uložit HTML do ZIP, aplikovat styl písma v HTML a přidat tučný text + k elementům p. +og_title: Převod HTML na PNG – Kompletní C# tutoriál +tags: +- Aspose +- C# +title: Převod HTML na PNG – Kompletní průvodce C# s exportem ZIP +url: /cs/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Převod HTML na PNG – Kompletní průvodce v C# s exportem do ZIP + +Už jste někdy potřebovali **převést HTML na PNG**, ale nebyli jste si jisti, která knihovna to zvládne bez použití headless prohlížeče? Nejste v tom sami. V mnoha projektech – náhledy e‑mailů, ukázky dokumentace nebo rychlé náhledy obrázků – je převod webové stránky na statický obrázek reálnou potřebou. + +Dobrá zpráva? S Aspose.HTML můžete **renderovat HTML jako obrázek**, během běhu upravit značky a dokonce **uložit HTML do ZIP** pro pozdější distribuci. V tomto tutoriálu projdeme kompletním, spustitelným příkladem, který **aplikuje font‑style HTML**, konkrétně **přidá tučný text do elementů p**, a poté vytvoří soubor PNG. Na konci budete mít jedinou třídu v C#, která zvládne vše od načtení stránky až po archivaci jejích zdrojů. + +## Co budete potřebovat + +- .NET 6.0 nebo novější (API funguje i na .NET Core) +- Aspose.HTML pro .NET 6+ (NuGet balíček `Aspose.Html`) +- Základní znalost syntaxe C# (žádné pokročilé koncepty nejsou vyžadovány) + +To je vše. Žádné externí prohlížeče, žádný phantomjs, jen čistý spravovaný kód. + +## Krok 1 – Načtení HTML dokumentu + +Nejprve načteme zdrojový soubor (nebo URL) do objektu `HTMLDocument`. Tento krok je základem jak pro **render html as image**, tak pro **save html to zip** později. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Proč je to důležité:* Třída `HTMLDocument` parsuje značky, vytvoří DOM a vyřeší propojené zdroje (CSS, obrázky, fonty). Bez správného objektu dokumentu nemůžete manipulovat se styly ani nic renderovat. + +## Krok 2 – Aplikace font‑style HTML (Přidání tučného p) + +Nyní **aplikujeme font‑style HTML** tak, že projdeme všechny elementy `

` a nastavíme jejich `font-weight` na tučné. Jedná se o programatický způsob, jak **add bold to p** tagy, aniž byste zasahovali do původního souboru. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Tip:* Pokud potřebujete tučný text jen u části odstavců, změňte selektor na konkrétnější, např. `"p.intro"`. + +## Krok 3 – Renderování HTML jako obrázek (Convert HTML to PNG) + +S připraveným DOMem nakonfigurujeme `ImageRenderingOptions` a zavoláme `RenderToImage`. Zde se odehrává magie **convert html to png**. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Proč jsou volby důležité:* Nastavení pevné šířky/výšky zabrání příliš velkému výstupu, antialiasing poskytne hladší vizuální výsledek. Můžete také přepnout `options` na `ImageFormat.Jpeg`, pokud preferujete menší soubor. + +## Krok 4 – Uložení HTML do ZIP (Balíček zdrojů) + +Často potřebujete distribuovat původní HTML spolu s jeho CSS, obrázky a fonty. `ZipArchiveSaveOptions` od Aspose.HTML to udělá přesně. Navíc připojíme vlastní `ResourceHandler`, aby všechny externí assety byly zapsány do stejné složky jako archiv. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Okrajový případ:* Pokud váš HTML odkazuje na vzdálené obrázky vyžadující autentizaci, výchozí handler selže. V takovém scénáři můžete rozšířit `MyResourceHandler` a vložit HTTP hlavičky. + +## Krok 5 – Propojení všeho do jedné třídy Converter + +Níže je kompletní, připravená třída, která spojuje všechny předchozí kroky. Stačí ji zkopírovat do konzolové aplikace, zavolat `Convert` a sledovat, jak se soubory vytvoří. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Očekávaný výstup + +Po spuštění výše uvedeného úryvku najdete ve složce `outputDirectory` dva soubory: + +| Soubor | Popis | +|--------|-------| +| `page.png` | PNG renderování o rozměrech 1200 × 800 zdrojového HTML, přičemž každý odstavec je zobrazen **tučně**. | +| `archive.zip` | ZIP balíček obsahující původní `input.html`, jeho CSS, obrázky a všechny web‑fonty – ideální pro offline distribuci. | + +Soubor `page.png` můžete otevřít v libovolném prohlížeči obrázků a ověřit, že tučný styl byl aplikován, a rozbalit `archive.zip`, abyste viděli nedotčené HTML spolu s jeho assety. + +## Časté otázky a úskalí + +- **Co když HTML obsahuje JavaScript?** + Aspose.HTML **nevykonává** skripty během renderování, takže dynamický obsah se nezobrazí. Pro plně vykreslené stránky byste potřebovali headless prohlížeč, ale pro statické šablony je tento přístup rychlejší a lehčí. + +- **Mohu změnit výstupní formát na JPEG nebo BMP?** + Ano – změňte vlastnost `ImageFormat` v `ImageRenderingOptions`, např. `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Musím ručně uvolnit `HTMLDocument`?** + Třída implementuje `IDisposable`. V dlouho běžící službě ji obalte do `using` bloku nebo po dokončení zavolejte `document.Dispose()`. + +- **Jak funguje vlastní `MyResourceHandler`?** + Přijímá každý externí zdroj (CSS, obrázky, fonty) a zapisuje jej do určené složky. Tím zajistí, že ZIP obsahuje věrnou kopii všeho, na co HTML odkazuje. + +## Závěr + +Nyní máte kompaktní, připravené řešení pro **convert html to png**, **render html as image**, **save html to zip**, **apply font style html** a **add bold to p** – vše v několika řádcích C#. Kód je samostatný, funguje s .NET 6+ a lze jej vložit do libovolné backendové služby, která potřebuje rychlé vizuální snímky webového obsahu. + +Jste připraveni na další krok? Zkuste změnit velikost renderování, experimentujte s dalšími CSS vlastnostmi (např. `font-family` nebo `color`) nebo integrujte tento konvertor do ASP.NET Core endpointu, který na požádání vrátí PNG. Možnosti jsou neomezené a s Aspose.HTML se vyhnete těžkopádným závislostem na prohlížečích. + +Pokud narazíte na problémy nebo máte nápady na rozšíření, zanechte komentář níže. Šťastné programování! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/czech/net/html-document-manipulation/_index.md index 6f2c68f80..f839c93be 100644 --- a/html/czech/net/html-document-manipulation/_index.md +++ b/html/czech/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Naučte se používat Aspose.HTML pro .NET. Importujte jmenný prostor, slučujt Odemkněte potenciál vývoje webu s Aspose.HTML pro .NET. Snadno vytvářejte, převádějte a manipulujte s dokumenty HTML. ### [Vytvoření HTML ze řetězce v C# – Průvodce vlastním Resource Handlerem](./create-html-from-string-in-c-custom-resource-handler-guide/) Naučte se, jak vytvořit HTML dokument z řetězce v C# pomocí vlastního Resource Handleru. +### [Vytvoření HTML dokumentu v C# – Průvodce krok za krokem](./create-html-document-c-step-by-step-guide/) +Naučte se, jak vytvořit HTML dokument v C# pomocí Aspose.HTML krok po kroku. ## Závěr diff --git a/html/czech/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/czech/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..b571bbf13 --- /dev/null +++ b/html/czech/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Vytvořte HTML dokument v C# a naučte se, jak získat prvek podle ID, najít + prvek podle ID, změnit styl HTML prvku a přidat tučný a kurzívní styl pomocí Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: cs +og_description: Vytvořte HTML dokument v C# a okamžitě se naučte získat prvek podle + ID, najít prvek podle ID, změnit styl HTML prvku a přidat tučný a kurzívu s jasnými + ukázkami kódu. +og_title: Vytvořte HTML dokument v C# – Kompletní průvodce programováním +tags: +- Aspose.Html +- C# +- DOM manipulation +title: Vytvoření HTML dokumentu v C# – krok za krokem +url: /cs/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření HTML dokumentu v C# – krok za krokem + +Už jste někdy potřebovali **create HTML document C#** od nuly a pak upravit vzhled jediného odstavce? Nejste v tom sami. V mnoha projektech web‑automatizace vytvoříte HTML soubor, vyhledáte tag podle jeho ID a pak použijete nějaké stylování – často tučné + kurzíva – aniž byste se dotkli prohlížeče. + +V tomto tutoriálu projdeme přesně tímto: vytvoříme HTML dokument v C#, **get element by id**, **locate element by id**, **change HTML element style**, a nakonec **add bold italic** pomocí knihovny Aspose.Html. Na konci budete mít plně spustitelný úryvek, který můžete vložit do libovolného .NET projektu. + +## Co budete potřebovat + +- .NET 6 nebo novější (kód funguje také na .NET Framework 4.7+) +- Visual Studio 2022 (nebo jakýkoli editor, který chcete) +- Balíček **Aspose.Html** NuGet (`Install-Package Aspose.Html`) + +A to je vše—žádné extra HTML soubory, žádný webový server, jen několik řádků C#. + +## Vytvoření HTML dokumentu v C# – inicializace dokumentu + +Nejprve: potřebujete živý objekt `HTMLDocument`, se kterým může pracovat engine Aspose.Html. Představte si to jako otevření čistého sešitu, do kterého budete psát svůj markup. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Proč je to důležité:** Předáním surového řetězce do `HTMLDocument` se vyhnete práci se souborovým I/O a vše zůstane v paměti—ideální pro unit testy nebo generování za běhu. + +## Získání elementu podle ID – hledání odstavce + +Nyní, když dokument existuje, potřebujeme **get element by id**. DOM API nám poskytuje `GetElementById`, který vrací referenci `IElement` nebo `null`, pokud ID není přítomno. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Tip:** I když je náš markup malý, přidání kontroly na null vám ušetří problémy, když se stejná logika použije na větších, dynamických stránkách. + +## Vyhledání elementu podle ID – alternativní přístup + +Někdy můžete již mít referenci na kořen dokumentu a upřednostňovat vyhledávání ve stylu dotazu. Použití CSS selektorů (`QuerySelector`) je další způsob, jak **locate element by id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **Kdy použít který?** `GetElementById` je mírně rychlejší, protože jde o přímé vyhledávání v hash tabulce. `QuerySelector` vyniká, když potřebujete složité selektory (např. `div > p.highlight`). + +## Změna stylu HTML elementu – přidání tučného a kurzívního + +S elementem v ruce je dalším krokem **change HTML element style**. Aspose.Html poskytuje objekt `Style`, kde můžete upravit CSS vlastnosti nebo použít pohodlnou výčtovou hodnotu `WebFontStyle` k aplikaci více fontových vlastností najednou. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Ten jediný řádek nastaví `font-weight` elementu na `bold` a `font-style` na `italic`. Pod kapotou Aspose.Html překládá výčet na odpovídající CSS řetězec. + +### Kompletní funkční příklad + +Složení všech částí dohromady dává kompaktní, samostatný program, který můžete okamžitě zkompilovat a spustit: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Očekávaný výstup** + +``` +Rendered HTML: +

Hello world

+``` + +Tag `

` nyní obsahuje inline atribut `style`, který dělá text jak tučný, tak kurzívní – přesně to, co jsme chtěli. + +## Okrajové případy a časté úskalí + +| Situace | Na co si dát pozor | Jak řešit | +|-----------|-------------------|---------------| +| **ID neexistuje** | `GetElementById` vrací `null`. | Vyhoďte výjimku nebo přejděte na výchozí element. | +| **Více elementů sdílí stejné ID** | Specifikace HTML říká, že ID musí být unikátní, ale reálné stránky někdy pravidlo porušují. | `GetElementById` vrací první shodu; zvažte použití `QuerySelectorAll`, pokud potřebujete řešit duplikáty. | +| **Konflikty stylování** | Existující inline styly mohou být přepsány. | Přidejte k objektu `Style` místo nastavení celého řetězce `style`: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Renderování v prohlížeči** | Některé prohlížeče ignorují `WebFontStyle`, pokud má element již CSS třídu s vyšší specifikací. | Použijte `!important` pomocí `paragraph.Style.SetProperty("font-weight", "bold", "important");` pokud je potřeba. | + +## Profesionální tipy pro reálné projekty + +- **Ukládejte dokument do cache** pokud zpracováváte mnoho elementů; vytváření nového `HTMLDocument` pro každý malý úryvek může snížit výkon. +- **Kombinujte změny stylů** v jedné transakci `Style`, abyste se vyhnuli vícenásobným DOM reflow. +- **Využijte renderovací engine Aspose.Html** k exportu finálního dokumentu jako PDF nebo obrázek – skvělé pro reportovací nástroje. + +## Vizuální potvrzení (volitelné) + +Pokud raději chcete vidět výsledek v prohlížeči, můžete uložit renderovaný řetězec do souboru `.html`: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Otevřete `output.html` a uvidíte **Hello world** zobrazený tučně + kurzívou. + +![Příklad vytvoření HTML dokumentu C# zobrazující tučný a kurzívní odstavec](/images/create-html-document-csharp.png "Vytvoření HTML dokumentu C# – vykreslený výstup") + +*Alt text: Vytvoření HTML dokumentu C# – vykreslený výstup s tučným a kurzívním textem.* + +## Závěr + +Právě jsme **vytvořili HTML dokument v C#**, **získali element podle id**, **vyhledali element podle id**, **změnili styl HTML elementu** a nakonec **přidali tučný a kurzívní**—vše pomocí několika řádků s Aspose.Html. Přístup je jednoduchý, funguje v jakémkoli .NET prostředí a škáluje na větší manipulace s DOM. + +Jste připraveni na další krok? Zkuste nahradit `WebFontStyle` jinými výčty jako `Underline` nebo kombinovat více stylů ručně. Nebo experimentujte s načtením externího HTML souboru a aplikací stejné techniky na stovky elementů. Možnosti jsou neomezené a nyní máte pevný základ, na kterém můžete stavět. + +Šťastné programování! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/czech/net/html-extensions-and-conversions/_index.md b/html/czech/net/html-extensions-and-conversions/_index.md index dc8f6f072..9c0aa06e5 100644 --- a/html/czech/net/html-extensions-and-conversions/_index.md +++ b/html/czech/net/html-extensions-and-conversions/_index.md @@ -41,6 +41,8 @@ Aspose.HTML for .NET není jen knihovna; je to změna hry ve světě vývoje web Převeďte HTML do PDF bez námahy pomocí Aspose.HTML pro .NET. Postupujte podle našeho podrobného průvodce a uvolněte sílu převodu HTML do PDF. ### [Vytvořte PDF z HTML v C# – průvodce krok za krokem](./create-pdf-from-html-c-step-by-step-guide/) Naučte se, jak pomocí Aspose.HTML v C# převést HTML dokument do PDF pomocí podrobného průvodce krok za krokem. +### [Vytvořte PDF z HTML pomocí Aspose – krok za krokem průvodce v C#](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Naučte se, jak v C# pomocí Aspose.HTML krok za krokem převést HTML dokument do PDF pomocí podrobného průvodce. ### [Převeďte EPUB na obrázek v .NET pomocí Aspose.HTML](./convert-epub-to-image/) Přečtěte si, jak převést EPUB na obrázky pomocí Aspose.HTML pro .NET. Výukový program krok za krokem s příklady kódu a přizpůsobitelnými možnostmi. ### [Převeďte EPUB do PDF v .NET pomocí Aspose.HTML](./convert-epub-to-pdf/) @@ -65,14 +67,20 @@ Objevte, jak používat Aspose.HTML pro .NET k manipulaci a převodu HTML dokume Naučte se převádět HTML na TIFF pomocí Aspose.HTML pro .NET. Postupujte podle našeho podrobného průvodce pro efektivní optimalizaci webového obsahu. ### [Převeďte HTML na XPS v .NET pomocí Aspose.HTML](./convert-html-to-xps/) Objevte sílu Aspose.HTML pro .NET: Převeďte HTML na XPS bez námahy. Součástí jsou předpoklady, podrobný průvodce a často kladené otázky. +### [Převod HTML na obrázek v C# – Kompletní průvodce](./convert-html-to-image-in-c-complete-guide/) +Naučte se, jak v C# pomocí Aspose.HTML převést HTML na obrázek v podrobném kompletním průvodci. ### [Jak zkomprimovat HTML v C# – Uložit HTML do ZIP](./how-to-zip-html-in-c-save-html-to-zip/) Naučte se, jak pomocí Aspose.HTML pro .NET zabalit HTML soubor do ZIP archivu v C#. +### [Jak zkomprimovat HTML pomocí Aspose.HTML – Kompletní průvodce](./how-to-zip-html-with-aspose-html-complete-guide/) +Kompletní průvodce, jak pomocí Aspose.HTML zkomprimovat HTML soubor do ZIP archivu v .NET. ### [Vytvořte HTML dokument se stylovaným textem a exportujte do PDF – Kompletní průvodce](./create-html-document-with-styled-text-and-export-to-pdf-full/) Naučte se vytvořit HTML dokument se stylovaným textem a převést jej do PDF pomocí Aspose.HTML pro .NET. ### [Uložte HTML jako ZIP – Kompletní C# tutoriál](./save-html-as-zip-complete-c-tutorial/) 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 jako ZIP v C# – Kompletní průvodce s vlastním úložištěm](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Kompletní průvodce ukládáním HTML jako ZIP v C# s využitím vlastního úložiště pomocí Aspose.HTML. ## Závěr diff --git a/html/czech/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/czech/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..1886e4270 --- /dev/null +++ b/html/czech/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Převod HTML na obrázek pomocí Aspose.HTML v C#. Naučte se, jak uložit + HTML jako PNG, nastavit velikost vykreslování obrázku a zapsat obrázek do souboru + během několika kroků. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: cs +og_description: Rychle převádějte HTML na obrázek. Tento průvodce ukazuje, jak uložit + HTML jako PNG, nastavit velikost renderovaného obrázku a zapsat obrázek do souboru + pomocí Aspose.HTML. +og_title: Převod HTML na obrázek v C# – Průvodce krok za krokem +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Převod HTML na obrázek v C# – Kompletní průvodce +url: /cs/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Převod HTML na obrázek v C# – Kompletní průvodce + +Už jste někdy potřebovali **convert HTML to image** pro miniaturu dashboardu, náhled e‑mailu nebo PDF report? Je to situace, která se objevuje častěji, než byste čekali, zejména když pracujete s dynamickým webovým obsahem, který musí být vložen někde jinde. + +Dobrá zpráva? S Aspose.HTML můžete **convert HTML to image** během několika řádků a také se naučíte, jak *save HTML as PNG*, ovládat rozměry výstupu a *write image to file* bez potíží. + +V tomto tutoriálu projdeme vše, co potřebujete vědět: od načtení vzdálené stránky po úpravu velikosti renderování a nakonec uložení výsledku jako PNG souboru na disk. Žádné externí nástroje, žádné složité příkazy v příkazovém řádku — jen čistý C# kód, který můžete vložit do libovolného .NET projektu. + +## Co se naučíte + +- Jak **render webpage to PNG** pomocí třídy `HTMLDocument` z Aspose.HTML. +- Přesné kroky k **set image size rendering**, aby výstup odpovídal požadavkům na rozvržení. +- Způsoby, jak **write image to file** bezpečně, s manipulací se streamy a cestami k souborům. +- Tipy pro řešení běžných problémů, jako chybějící fonty nebo časová omezení sítě. + +### Předpoklady + +- .NET 6.0 nebo novější (API funguje i s .NET Framework, ale .NET 6+ se doporučuje). +- Odkaz na NuGet balíček Aspose.HTML for .NET (`Aspose.Html`). +- Základní znalost C# a async/await (volitelné, ale užitečné). + +Pokud už to máte, můžete okamžitě začít s převodem HTML na obrázek. + +## Krok 1: Načtení webové stránky — Základ převodu HTML na obrázek + +Než může dojít k jakémukoli renderování, potřebujete instanci `HTMLDocument`, která představuje stránku, kterou chcete zachytit. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Proč je to důležité:* `HTMLDocument` parsuje HTML, řeší CSS a vytváří DOM. Pokud se dokument nenačte (např. problém se sítí), následné renderování vytvoří prázdný obrázek. Vždy ověřte, že URL je dostupná, než budete pokračovat. + +## Krok 2: Nastavení velikosti renderování obrázku — Ovládání šířky, výšky a kvality + +Aspose.HTML vám umožňuje jemně doladit rozměry výstupu pomocí `ImageRenderingOptions`. Zde **set image size rendering** tak, aby odpovídalo vašemu cílovému rozvržení. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Tip:* Pokud vynecháte `Width` a `Height`, Aspose.HTML použije vnitřní velikost stránky, která může být pro responzivní design nepředvídatelná. Explicitní určení rozměrů zajistí, že výstup **save HTML as PNG** bude vypadat přesně tak, jak očekáváte. + +## Krok 3: Zapsání obrázku do souboru — Uložení vykresleného PNG + +Nyní, když je dokument připraven a nastaveny možnosti renderování, můžete konečně **write image to file**. Použití `FileStream` zaručuje, že soubor bude vytvořen bezpečně, i když složka ještě neexistuje. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +Po spuštění tohoto bloku najdete `page.png` na určeném místě. Právě jste **rendered webpage to PNG** a uložili jej na disk jedním jednoduchým krokem. + +### Očekávaný výsledek + +Otevřete `C:\Temp\page.png` v libovolném prohlížeči obrázků. Měli byste vidět věrný snímek `https://example.com`, vykreslený v rozlišení 1024 × 768 pixelů s hladkými hranami díky antialiasingu. Pokud stránka obsahuje dynamický obsah (např. elementy generované JavaScriptem), budou zachyceny, pokud je DOM plně načten před renderováním. + +## Krok 4: Řešení okrajových případů — Fonty, autentizace a velké stránky + +Zatímco základní postup funguje pro většinu veřejných stránek, reálné scénáře často přinášejí nečekané problémy: + +| Situace | Co dělat | +|-----------|------------| +| **Custom fonts not loading** | Vložte soubory fontů lokálně a nastavte `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Pages behind authentication** | Použijte přetížení `HTMLDocument`, které přijímá `HttpWebRequest` s cookies nebo tokeny. | +| **Very tall pages** | Zvyšte `Height` nebo povolte `PageScaling` v `ImageRenderingOptions`, aby nedošlo ke oříznutí. | +| **Memory usage spikes** | Renderujte po částech pomocí přetížení `RenderToImage`, které přijímá oblast `Rectangle`. | + +Řešení těchto nuancí *write image to file* zajišťuje, že váš pipeline `convert html to image` zůstane v produkci robustní. + +## Krok 5: Kompletní funkční příklad — Připravený ke zkopírování + +Níže je celý program připravený ke kompilaci. Obsahuje všechny kroky, zpracování chyb a komentáře, které potřebujete. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Spusťte tento program a v konzoli uvidíte potvrzovací zprávu. PNG soubor bude přesně to, co očekáváte, když **render webpage to PNG** ručně v prohlížeči a uděláte snímek obrazovky — pouze rychlejší a plně automatizovaný. + +## Často kladené otázky + +**Q: Můžu převést lokální HTML soubor místo URL?** +Určitě. Stačí nahradit URL cestou k souboru: `new HTMLDocument(@"C:\myPage.html")`. + +**Q: Potřebuji licenci pro Aspose.HTML?** +Bezplatná evaluační licence funguje pro vývoj a testování. Pro produkci zakupte licenci, která odstraní evaluační vodoznak. + +**Q: Co když stránka používá JavaScript k načtení obsahu po počátečním načtení?** +Aspose.HTML provádí JavaScript synchronně během parsování, ale dlouho běžící skripty mohou vyžadovat ruční zpoždění. Můžete použít `HTMLDocument.WaitForReadyState` před renderováním. + +## Závěr + +Nyní máte robustní end‑to‑end řešení pro **convert HTML to image** v C#. Dodržením výše uvedených kroků můžete **save HTML as PNG**, přesně **set image size rendering** a s jistotou **write image to file** na jakémkoli prostředí Windows nebo Linux. + +Od jednoduchých snímků po automatizovanou generaci reportů tato technika dobře škáluje. Dále zkuste experimentovat s dalšími výstupními formáty, jako JPEG nebo BMP, nebo integrujte kód do ASP.NET Core API, které vrací PNG přímo volajícím. Možnosti jsou prakticky neomezené. + +Šťastné kódování a ať vaše vykreslené obrázky vždy vypadají pixel‑perfektně! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/czech/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..78b952bde --- /dev/null +++ b/html/czech/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-03-21 +description: Rychle vytvořte PDF z HTML pomocí Aspose HTML. Naučte se vykreslovat + HTML do PDF, převádět HTML na PDF a jak používat Aspose v stručném tutoriálu. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: cs +og_description: Vytvořte PDF z HTML pomocí Aspose v C#. Tento průvodce ukazuje, jak + renderovat HTML do PDF, převést HTML na PDF a jak efektivně používat Aspose. +og_title: Vytvořte PDF z HTML – Kompletní tutoriál Aspose C# +tags: +- Aspose +- C# +- PDF generation +title: Vytvořte PDF z HTML pomocí Aspose – krok za krokem průvodce v C# +url: /cs/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření PDF z HTML pomocí Aspose – krok za krokem v C# + +Už jste někdy potřebovali **vytvořit PDF z HTML**, ale nebyli jste si jisti, která knihovna vám poskytne pixel‑perfektní výsledek? Nejste v tom sami. Mnoho vývojářů narazí na rozmazaný text nebo rozbitý layout, když se snaží převést webový úryvek na tisknutelný dokument. + +Dobrou zprávou je, že Aspose HTML celý proces zjednodušuje. V tomto tutoriálu projdeme přesný kód, který potřebujete k **renderování HTML do PDF**, vysvětlíme, proč je každé nastavení důležité, a ukážeme vám, jak **převést HTML do PDF** bez skrytých triků. Na konci budete vědět, **jak používat Aspose** pro spolehlivé generování PDF v jakémkoli .NET projektu. + +## Předpoklady – Co budete potřebovat před začátkem + +- **.NET 6.0 nebo novější** (příklad funguje také na .NET Framework 4.7+) +- **Visual Studio 2022** nebo jakékoli IDE podporující C# +- **Aspose.HTML for .NET** NuGet balíček (zdarma zkušební verze nebo licencovaná) +- Základní znalost syntaxe C# (hluboké znalosti PDF nejsou potřeba) + +Pokud to máte, můžete začít. Jinak si stáhněte nejnovější .NET SDK a nainstalujte NuGet balíček pomocí: + +```bash +dotnet add package Aspose.HTML +``` + +Tento jediný řádek načte vše, co potřebujete pro **aspose html to pdf** konverzi. + +--- + +## Krok 1: Nastavení projektu pro vytvoření PDF z HTML + +Prvním krokem je vytvořit novou konzolovou aplikaci (nebo integrovat kód do existující služby). Zde je minimální kostra `Program.cs`: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Tip:** Pokud ve starších ukázkách vidíte `Aspise.Html.Rendering.Text`, nahraďte ho `Aspose.Html.Rendering.Text`. Tato překlep způsobí chybu při kompilaci. + +Použití správných jmenných prostorů zajistí, že kompilátor najde třídu **TextOptions**, kterou později potřebujeme. + +## Krok 2: Vytvoření HTML dokumentu (Render HTML to PDF) + +Nyní vytvoříme zdrojové HTML. Aspose umožňuje předat čistý řetězec, cestu k souboru nebo dokonce URL. Pro tuto ukázku zvolíme jednoduchý řetězec: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Proč předat řetězec? Vyhnete se tak souborovým operacím, urychlíte konverzi a máte jistotu, že HTML v kódu je přesně to, co bude renderováno. Pokud raději načítáte ze souboru, stačí nahradit argument konstruktoru URI souboru. + +## Krok 3: Jemné doladění renderování textu (Convert HTML to PDF with Better Quality) + +Renderování textu často rozhoduje, zda bude PDF ostrý nebo rozmazaný. Aspose nabízí třídu `TextOptions`, která umožňuje zapnout sub‑pixel hinting – klíčové pro výstup s vysokým DPI. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Zapnutí `UseHinting` je zvláště užitečné, když vaše zdrojové HTML obsahuje vlastní fonty nebo malé velikosti písma. Bez toho můžete v konečném PDF vidět zubaté hrany. + +## Krok 4: Připojení Text Options k nastavení renderování PDF (How to Use Aspose) + +Dále svázeme tyto textové možnosti s PDF rendererem. Zde **aspose html to pdf** opravdu zazáří – vše od velikosti stránky po kompresi lze upravit. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +`PageSetup` můžete vynechat, pokud vám vyhovuje výchozí velikost A4. Hlavní myšlenka je, že objekt `TextOptions` žije uvnitř `PdfRenderingOptions` a tak říkáte Aspose *jak* má text renderovat. + +## Krok 5: Renderování HTML a uložení PDF (Convert HTML to PDF) + +Nakonec výstup streamujeme do souboru. Použití bloku `using` zaručuje, že souborový handle bude řádně uzavřen, i když dojde k výjimce. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Po spuštění programu najdete `output.pdf` vedle spustitelného souboru. Otevřete jej a uvidíte čistý nadpis a odstavec – přesně tak, jak je definováno v HTML řetězci. + +### Očekávaný výstup + +![create pdf from html example output](https://example.com/images/pdf-output.png "create pdf from html example output") + +*Screenshot ukazuje vygenerované PDF s nadpisem „Hello, Aspose!“ ostře vykresleným díky textovému hintingu.* + +--- + +## Často kladené otázky a okrajové případy + +### 1. Co když moje HTML odkazuje na externí zdroje (obrázky, CSS)? + +Aspose řeší relativní URL na základě základního URI dokumentu. Pokud předáváte čistý řetězec, nastavte základní URI ručně: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Nyní bude `` hledáno relativně k `C:/MyProject/`. + +### 2. Jak vložit fonty, které nejsou nainstalovány na serveru? + +Přidejte blok ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Krok 4: Nakonfigurujte možnosti uložení pro použití vlastního úložiště + +`HtmlSaveOptions` nám umožňuje říct Aspose, aby vše zabalil do ZIP souboru. Vlastnost `OutputStorage` (legacy) přijímá naši instanci `MyStorage`. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Poznámka:** V Aspose HTML 23.9+ se vlastnost jmenuje `OutputStorage`, ale je označena jako zastaralá. Moderní alternativou je `ZipOutputStorage`. Níže uvedený kód funguje s oběma, protože rozhraní je stejné. + +### Krok 5: Uložte dokument jako ZIP archiv + +Vyberte cílovou složku (nebo stream) a nechte Aspose udělat těžkou práci. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Po dokončení programu najdete `output.zip`, který obsahuje: + +* `index.html` – hlavní dokument. +* Všechny vložené obrázky, CSS soubory nebo skripty (pokud je váš HTML odkazoval). + +ZIP můžete otevřít v libovolném správci archivů a ověřit strukturu. + +--- + +## Ověření výsledku (volitelné) + +Pokud chcete programově prozkoumat archiv bez jeho rozbalení na disk: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Typický výstup: + +``` +- index.html (452 bytes) +``` + +Pokud byste měli obrázky nebo CSS, objeví se jako další položky. Tento rychlý kontrolní test potvrzuje, že **create html zip archive** fungoval podle očekávání. + +--- + +## Časté otázky a okrajové případy + +| Otázka | Odpověď | +|----------|--------| +| **Co když potřebuji zapsat ZIP přímo do response streamu?** | Vraťte `MemoryStream`, který získáte z `MyStorage` po `document.Save`. Přetypujte jej na `byte[]` a zapište do `HttpResponse.Body`. | +| **Můj HTML odkazuje na externí URL – budou staženy?** | Ne. Aspose balí pouze zdroje, které jsou *vložené* (např. `` nebo lokální soubory). Pro vzdálené assety je musíte nejprve stáhnout a upravit značky. | +| **Vlastnost `OutputStorage` je označena jako zastaralá – mám ji ignorovat?** | Stále funguje, ale novější `ZipOutputStorage` nabízí stejné API pod jiným názvem. Nahraďte `OutputStorage` za `ZipOutputStorage`, pokud chcete build bez varování. | +| **Mohu ZIP zašifrovat?** | Ano. Po uložení otevřete soubor pomocí `System.IO.Compression.ZipArchive` a nastavte heslo pomocí knihoven třetích stran, jako je `SharpZipLib`. Aspose samotné šifrování neposkytuje. | + +## Kompletní funkční příklad (kopíruj‑vlož) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Spusťte program, otevřete `output.zip` a uvidíte jediný soubor `index.html`, který při otevření v prohlížeči zobrazí nadpis „Hello from ZIP!“. + +## Závěr + +Nyní víte, **jak uložit HTML jako ZIP** v C# pomocí třídy **vlastního úložiště**, **jak exportovat HTML do ZIP** a **jak vytvořit HTML zip archiv**, který je připravený k distribuci. Vzor je flexibilní – můžete vyměnit `MemoryStream` za cloudový stream, přidat šifrování nebo jej integrovat do webového API, které ZIP vrací na vyžádání. + +Jste připraveni na další krok? Zkuste načíst kompletní webovou stránku s obrázky a styly, nebo připojte úložiště k Azure Blob Storage a úplně obejděte lokální souborový systém. Možnosti jsou neomezené, když zkombinujete ZIP schopnosti Aspose.HTML s vaší vlastní logikou úložiště. + +Šťastné programování a ať jsou vaše archivy vždy úhledné! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/dutch/net/generate-jpg-and-png-images/_index.md b/html/dutch/net/generate-jpg-and-png-images/_index.md index e05f0c0a7..b66f232c2 100644 --- a/html/dutch/net/generate-jpg-and-png-images/_index.md +++ b/html/dutch/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Leer hoe u Aspose.HTML voor .NET kunt gebruiken om HTML-documenten te bewerken, Leer hoe u antialiasing inschakelt bij het omzetten van DOCX-bestanden naar PNG- of JPG-afbeeldingen met Aspose.HTML. ### [docx naar png converteren – zip-archief maken C#-tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Leer hoe u een DOCX-bestand naar PNG converteert en de resultaten in een zip-archief opslaat met C# en Aspose.HTML. +### [HTML naar PNG converteren – volledige C#-gids met ZIP-export](./convert-html-to-png-full-c-guide-with-zip-export/) +Leer hoe u HTML naar PNG converteert en de afbeeldingen in een ZIP-archief exporteert met een volledige C#-handleiding. ## Conclusie diff --git a/html/dutch/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/dutch/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..9ffa17c34 --- /dev/null +++ b/html/dutch/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Converteer HTML naar PNG en render HTML als afbeelding terwijl je HTML + opslaat in een ZIP. Leer hoe je een lettertype‑stijl toepast op HTML en vet maakt + voor p‑elementen in slechts een paar stappen. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: nl +og_description: Converteer HTML snel naar PNG. Deze gids laat zien hoe je HTML als + afbeelding rendert, HTML opslaat in een ZIP, een lettertype‑stijl toepast op HTML + en vet maakt voor p‑elementen. +og_title: HTML naar PNG converteren – Complete C#‑tutorial +tags: +- Aspose +- C# +title: HTML naar PNG converteren – Volledige C#‑gids met ZIP‑export +url: /nl/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML naar PNG converteren – Volledige C#-gids met ZIP-export + +Heb je ooit **HTML naar PNG converteren** moeten, maar wist je niet welke bibliotheek dat kon doen zonder een headless browser te gebruiken? Je bent niet de enige. In veel projecten—e‑mailminiaturen, documentatie‑voorbeelden, of quick‑look‑afbeeldingen—het omzetten van een webpagina naar een statische afbeelding is een praktische noodzaak. + +Het goede nieuws? Met Aspose.HTML kun je **HTML als afbeelding renderen**, de markup ter plekke aanpassen, en zelfs **HTML naar ZIP opslaan** voor latere distributie. In deze tutorial lopen we een volledig, uitvoerbaar voorbeeld door dat **font style HTML toepast**, specifiek **vet maken van p**‑elementen, voordat een PNG‑bestand wordt geproduceerd. Aan het einde heb je een enkele C#‑klasse die alles doet, van het laden van een pagina tot het archiveren van de bronnen. + +## Wat je nodig hebt + +- .NET 6.0 of later (de API werkt ook op .NET Core) +- Aspose.HTML voor .NET 6+ (NuGet‑pakket `Aspose.Html`) +- Een basisbegrip van C#‑syntaxis (geen geavanceerde concepten vereist) + +Dat is alles. Geen externe browsers, geen phantomjs, alleen pure managed code. + +## Stap 1 – Laad het HTML‑document + +Eerst laden we het bronbestand (of URL) in een `HTMLDocument`‑object. Deze stap is de basis voor zowel **HTML als afbeelding renderen** als **HTML naar zip opslaan** later. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Waarom dit belangrijk is:* De `HTMLDocument`‑klasse parseert de markup, bouwt een DOM en lost gekoppelde bronnen op (CSS, afbeeldingen, lettertypen). Zonder een correct documentobject kun je geen stijlen manipuleren of iets renderen. + +## Stap 2 – Font style HTML toepassen (Vet maken van p) + +Nu gaan we **font style HTML toepassen** door over elk `

`‑element te itereren en de `font-weight` op vet (bold) te zetten. Dit is de programmeermethode om **vet te maken van p**‑tags zonder het originele bestand aan te passen. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Pro‑tip:* Als je alleen een deel vet wilt maken, wijzig dan de selector naar iets specifieker, bv. `"p.intro"`. + +## Stap 3 – HTML als afbeelding renderen (HTML naar PNG converteren) + +Met de DOM klaar, configureren we `ImageRenderingOptions` en roepen `RenderToImage` aan. Hier gebeurt de **convert html to png**‑magie. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Waarom de opties belangrijk zijn:* Het instellen van een vaste breedte/hoogte voorkomt dat de output te groot wordt, terwijl antialiasing een vloeiender visueel resultaat geeft. Je kunt `options` ook wijzigen naar `ImageFormat.Jpeg` als je een kleinere bestandsgrootte verkiest. + +## Stap 4 – HTML naar ZIP opslaan (Bronnen bundelen) + +Vaak moet je de originele HTML samen met de CSS, afbeeldingen en lettertypen leveren. Aspose.HTML’s `ZipArchiveSaveOptions` doet precies dat. We voegen ook een aangepaste `ResourceHandler` toe zodat alle externe assets naar dezelfde map als het archief worden geschreven. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Randgeval:* Als je HTML verwijst naar externe afbeeldingen die authenticatie vereisen, zal de standaard handler falen. In dat scenario kun je `MyResourceHandler` uitbreiden om HTTP‑headers toe te voegen. + +## Stap 5 – Alles samenvoegen in één converter‑klasse + +Hieronder staat de volledige, kant‑klaar‑te‑runnen klasse die alle vorige stappen samenvoegt. Je kunt deze kopiëren‑en‑plakken in een console‑app, `Convert` aanroepen, en de bestanden verschijnen zien. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Verwachte output + +Na het uitvoeren van de bovenstaande code vind je twee bestanden in `outputDirectory`: + +| Bestand | Beschrijving | +|------|-------------| +| `page.png` | Een 1200 × 800 PNG‑rendering van de bron‑HTML, waarbij elke alinea wordt weergegeven in **vet**. | +| `archive.zip` | Een ZIP‑bundel die de originele `input.html`, de CSS, afbeeldingen en eventuele web‑fonts bevat – perfect voor offline distributie. | + +Je kunt `page.png` openen in elke afbeeldingsviewer om te verifiëren dat de vette opmaak is toegepast, en `archive.zip` uitpakken om de onaangetaste HTML naast de assets te zien. + +## Veelgestelde vragen & valkuilen + +- **Wat als de HTML JavaScript bevat?** + Aspose.HTML voert **geen** scripts uit tijdens het renderen, dus dynamische inhoud verschijnt niet. Voor volledig gerenderde pagina's heb je een headless browser nodig, maar voor statische sjablonen is deze aanpak sneller en lichter. + +- **Kan ik het uitvoerformaat wijzigen naar JPEG of BMP?** + Ja—verander de `ImageFormat`‑eigenschap van `ImageRenderingOptions`, bijv. `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Moet ik de `HTMLDocument` handmatig vrijgeven?** + De klasse implementeert `IDisposable`. In een langdurige service wikkel je het in een `using`‑blok of roep je `document.Dispose()` aan nadat je klaar bent. + +- **Hoe werkt de aangepaste `MyResourceHandler`?** + Hij ontvangt elke externe bron (CSS, afbeeldingen, lettertypen) en schrijft deze naar de map die je opgeeft. Dit zorgt ervoor dat de ZIP een getrouwe kopie bevat van alles waar de HTML naar verwijst. + +## Conclusie + +Je hebt nu een compacte, productie‑klare oplossing die **convert html to png**, **render html as image**, **save html to zip**, **apply font style html**, en **add bold to p**—alles in een handvol C#‑regels. De code is zelfstandig, werkt met .NET 6+, en kan in elke backend‑service worden geïntegreerd die snelle visuele momentopnames van webinhoud nodig heeft. + +Klaar voor de volgende stap? Probeer de rendergrootte te wijzigen, experimenteer met andere CSS‑eigenschappen (zoals `font-family` of `color`), of integreer deze converter in een ASP.NET Core‑endpoint die de PNG op aanvraag retourneert. De mogelijkheden zijn eindeloos, en met Aspose.HTML vermijd je zware browser‑afhankelijkheden. + +Als je tegen problemen aanloopt of ideeën hebt voor uitbreidingen, laat dan een reactie achter. Veel plezier met coderen! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/dutch/net/html-document-manipulation/_index.md index 0639685af..1ea504dbd 100644 --- a/html/dutch/net/html-document-manipulation/_index.md +++ b/html/dutch/net/html-document-manipulation/_index.md @@ -59,6 +59,8 @@ Ontgrendel het potentieel van Aspose.HTML voor .NET met onze uitgebreide gids. L Leer hoe u de kracht van Aspose.HTML voor .NET kunt benutten. Geef uw webontwikkeling een boost met HTML-manipulatie en rendering. ### [Een document maken in .NET met Aspose.HTML](./creating-a-document/) Ontketen de kracht van Aspose.HTML voor .NET. Leer eenvoudig HTML- en SVG-documenten maken, manipuleren en optimaliseren. Bekijk stapsgewijze voorbeelden en veelgestelde vragen. +### [HTML-document maken in C# – Stapsgewijze gids](./create-html-document-c-step-by-step-guide/) +Leer hoe u met Aspose.HTML voor .NET een HTML-document in C# maakt, met duidelijke voorbeelden en stap‑voor‑stap instructies. ### [HTML maken vanuit een string in C# – Gids voor aangepaste resourcehandler](./create-html-from-string-in-c-custom-resource-handler-guide/) Leer hoe u HTML vanuit een string genereert in C# met een aangepaste resourcehandler, inclusief voorbeeldcode en stapsgewijze uitleg. ### [Een document bewerken in .NET met Aspose.HTML](./editing-a-document/) diff --git a/html/dutch/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/dutch/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..43d63b37f --- /dev/null +++ b/html/dutch/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: Maak een HTML‑document in C# en leer hoe je een element op id kunt ophalen, + een element op id kunt lokaliseren, de stijl van een HTML‑element kunt wijzigen + en vet en cursief kunt toevoegen met Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: nl +og_description: Maak een HTML‑document in C# en leer meteen hoe je een element op + ID kunt ophalen, een element op ID kunt vinden, de stijl van een HTML‑element kunt + wijzigen en vet en cursief kunt toevoegen, met duidelijke codevoorbeelden. +og_title: HTML-document maken met C# – Complete programmeergids +tags: +- Aspose.Html +- C# +- DOM manipulation +title: HTML-document maken met C# – Stapsgewijze handleiding +url: /nl/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML-document maken met C# – Stapsgewijze handleiding + +Heb je ooit **een HTML-document in C#** vanaf nul moeten maken en daarna het uiterlijk van één alinea moeten aanpassen? Je bent niet de enige. In veel web‑automatiseringsprojecten maak je een HTML‑bestand, zoek je een tag op basis van zijn ID, en pas je vervolgens wat opmaak toe—vaak vet + cursief—zonder ooit een browser te openen. + +In deze tutorial lopen we precies dat door: we maken een HTML‑document in C#, **get element by id**, **locate element by id**, **change HTML element style**, en tenslotte **add bold italic** met de Aspose.Html‑bibliotheek. Aan het einde heb je een volledig werkend fragment dat je in elk .NET‑project kunt gebruiken. + +## Wat je nodig hebt + +- .NET 6 of later (de code werkt ook op .NET Framework 4.7+) +- Visual Studio 2022 (of een andere editor naar keuze) +- Het **Aspose.Html** NuGet‑pakket (`Install-Package Aspose.Html`) + +Dat is alles—geen extra HTML‑bestanden, geen webserver, alleen een paar regels C#. + +## HTML-document maken met C# – Document initialiseren + +Allereerst: je hebt een levend `HTMLDocument`‑object nodig waar de Aspose.Html‑engine mee kan werken. Beschouw dit als het openen van een nieuw notitieboek waarin je je markup schrijft. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Waarom dit belangrijk is:** Door de ruwe string aan `HTMLDocument` door te geven, vermijd je bestands‑I/O en houd je alles in het geheugen—perfect voor unit‑tests of on‑the‑fly generatie. + +## Get Element by ID – De alinea vinden + +Nu het document bestaat, moeten we **get element by id** uitvoeren. De DOM‑API biedt `GetElementById`, die een `IElement`‑referentie teruggeeft of `null` als het ID niet bestaat. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Pro tip:** Ook al is onze markup klein, een null‑check bespaart je hoofdpijn wanneer dezelfde logica wordt hergebruikt op grotere, dynamische pagina's. + +## Locate Element by ID – Een alternatieve aanpak + +Soms heb je al een referentie naar de root van het document en geef je de voorkeur aan een query‑stijl zoekopdracht. Het gebruik van CSS‑selectoren (`QuerySelector`) is een andere manier om **locate element by id** uit te voeren: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **Wanneer welke gebruiken?** `GetElementById` is marginaler sneller omdat het een directe hash‑lookup is. `QuerySelector` blinkt uit wanneer je complexe selectors nodig hebt (bijv. `div > p.highlight`). + +## Change HTML Element Style – Vet cursief toevoegen + +Met het element in de hand is de volgende stap **change HTML element style**. Aspose.Html biedt een `Style`‑object waarin je CSS‑eigenschappen kunt aanpassen of de handige `WebFontStyle`‑enumeratie kunt gebruiken om meerdere lettertype‑eigenschappen tegelijk toe te passen. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Die ene regel zet de `font-weight` van het element op `bold` en `font-style` op `italic`. Intern vertaalt Aspose.Html de enum naar de juiste CSS‑string. + +### Volledig werkend voorbeeld + +Alle stukjes samenvoegen levert een compact, zelf‑voorzienend programma op dat je direct kunt compileren en uitvoeren: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Verwachte output** + +``` +Rendered HTML: +

Hello world

+``` + +De `

`‑tag bevat nu een inline `style`‑attribuut dat de tekst zowel vet als cursief maakt—precies wat we wilden. + +## Edge Cases & Common Pitfalls + +| Situatie | Waar je op moet letten | Hoe te handelen | +|-----------|-------------------|---------------| +| **ID bestaat niet** | `GetElementById` retourneert `null`. | Gooi een uitzondering of val terug op een standaard element. | +| **Meerdere elementen delen hetzelfde ID** | De HTML‑specificatie vereist unieke IDs, maar in de praktijk wordt die regel soms overtreden. | `GetElementById` geeft de eerste match terug; overweeg `QuerySelectorAll` te gebruiken als je duplicaten moet afhandelen. | +| **Stijlconflicten** | Bestaande inline‑stijlen kunnen worden overschreven. | Voeg toe aan het `Style`‑object in plaats van de hele `style`‑string te vervangen: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Weergave in een browser** | Sommige browsers negeren `WebFontStyle` als het element al een CSS‑klasse met hogere specificiteit heeft. | Gebruik `!important` via `paragraph.Style.SetProperty("font-weight", "bold", "important");` indien nodig. | + +## Pro Tips voor real‑world projecten + +- **Cache het document** als je veel elementen verwerkt; een nieuw `HTMLDocument` voor elk klein fragment kan de prestaties aantasten. +- **Combineer stijlwijzigingen** in één `Style`‑transactie om meerdere DOM‑reflows te vermijden. +- **Maak gebruik van Aspose.Html’s renderengine** om het uiteindelijke document als PDF of afbeelding te exporteren—handig voor rapportagetools. + +## Visuele bevestiging (optioneel) + +Als je het resultaat in een browser wilt zien, kun je de gerenderde string opslaan in een `.html`‑bestand: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Open `output.html` en je ziet **Hello world** weergegeven in vet + cursief. + +![Create HTML Document C# example showing bold italic paragraph](/images/create-html-document-csharp.png "Create HTML Document C# – rendered output") + +*Alt‑tekst: Create HTML Document C# – gerenderde output met vet cursieve tekst.* + +## Conclusie + +We hebben zojuist **een HTML-document in C#** gemaakt, **element op ID opgehaald**, **element op ID gelokaliseerd**, **HTML‑elementstijl gewijzigd**, en tenslotte **vet cursief toegevoegd**—allemaal met een handvol regels code via Aspose.Html. De aanpak is eenvoudig, werkt in elke .NET‑omgeving, en schaalt naar grotere DOM‑manipulaties. + +Klaar voor de volgende stap? Probeer `WebFontStyle` te vervangen door andere enums zoals `Underline` of combineer meerdere stijlen handmatig. Of experimenteer met het laden van een extern HTML‑bestand en pas dezelfde techniek toe op honderden elementen. De mogelijkheden zijn eindeloos, en nu heb je een solide basis om op voort te bouwen. + +Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/dutch/net/html-extensions-and-conversions/_index.md b/html/dutch/net/html-extensions-and-conversions/_index.md index fd924a78c..8864ff0ff 100644 --- a/html/dutch/net/html-extensions-and-conversions/_index.md +++ b/html/dutch/net/html-extensions-and-conversions/_index.md @@ -63,15 +63,23 @@ Ontdek hoe u Aspose.HTML voor .NET kunt gebruiken om HTML-documenten te manipule Leer hoe u HTML naar TIFF converteert met Aspose.HTML voor .NET. Volg onze stapsgewijze handleiding voor efficiënte optimalisatie van webinhoud. ### [Converteer HTML naar XPS in .NET met Aspose.HTML](./convert-html-to-xps/) Ontdek de kracht van Aspose.HTML voor .NET: Converteer HTML moeiteloos naar XPS. Vereisten, stapsgewijze handleiding en veelgestelde vragen inbegrepen. +### [Converteer HTML naar afbeelding in C# – Complete gids](./convert-html-to-image-in-c-complete-guide/) +Leer stap voor stap hoe u HTML naar verschillende afbeeldingsformaten converteert met Aspose.HTML voor .NET in C#. ### [HTML zippen in C# – HTML opslaan in zip](./how-to-zip-html-in-c-save-html-to-zip/) Leer hoe u HTML-bestanden comprimeert naar een zip‑archief met C# en Aspose.HTML voor .NET. +### [HTML opslaan als ZIP in C# – Complete gids met aangepaste opslag](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Leer hoe u HTML-bestanden opslaat als ZIP met C# en aangepaste opslagopties via Aspose.HTML voor .NET. +### [HTML zippen met Aspose.HTML – Complete gids](./how-to-zip-html-with-aspose-html-complete-guide/) +Leer stap voor stap hoe u HTML-bestanden comprimeert naar een ZIP‑archief met Aspose.HTML in .NET. ### [Maak HTML-document met opgemaakte tekst en exporteer naar PDF – Volledige gids](./create-html-document-with-styled-text-and-export-to-pdf-full/) Leer hoe u een HTML-document met opgemaakte tekst maakt en deze volledig naar PDF exporteert met Aspose.HTML voor .NET. ### [Maak PDF van HTML – C# Stapsgewijze handleiding](./create-pdf-from-html-c-step-by-step-guide/) Leer hoe u met Aspose.HTML voor .NET PDF's genereert vanuit HTML met een duidelijke C# stap‑voor‑stap handleiding. ### [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#. +Leer hoe u HTML-inhoud in het geheugen comprimeert en opslaat als ZIP‑bestand met Aspose.HTML voor .NET in C#. +### [PDF maken van HTML met Aspose – Stapsgewijze C#‑gids](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Leer hoe u PDF's genereert vanuit HTML met Aspose.HTML voor .NET met een duidelijke C# stap‑voor‑stap handleiding. ## Conclusie diff --git a/html/dutch/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/dutch/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..393701027 --- /dev/null +++ b/html/dutch/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Converteer HTML naar afbeelding met Aspose.HTML in C#. Leer hoe je HTML + opslaat als PNG, de afbeeldingsgrootte instelt bij het renderen en de afbeelding + naar een bestand schrijft in slechts een paar stappen. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: nl +og_description: Converteer HTML snel naar een afbeelding. Deze gids laat zien hoe + je HTML opslaat als PNG, de afbeeldingsgrootte instelt bij het renderen en de afbeelding + naar een bestand schrijft met Aspose.HTML. +og_title: HTML naar afbeelding converteren in C# – Stapsgewijze handleiding +tags: +- Aspose.HTML +- C# +- Image Rendering +title: HTML naar afbeelding converteren in C# – Complete gids +url: /nl/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML naar afbeelding converteren in C# – Complete gids + +Heb je ooit **HTML naar afbeelding moeten converteren** voor een dashboard‑thumbnail, een e‑mail‑preview of een PDF‑rapport? Het is een scenario dat vaker voorkomt dan je zou denken, vooral wanneer je werkt met dynamische webinhoud die ergens anders moet worden ingebed. + +Het goede nieuws? Met Aspose.HTML kun je **HTML naar afbeelding converteren** in slechts een handvol regels code, en leer je ook hoe je *HTML als PNG opslaat*, de uitvoerafmetingen regelt, en *afbeelding naar bestand schrijft* zonder enige moeite. + +In deze tutorial lopen we alles door wat je moet weten: van het laden van een externe pagina tot het aanpassen van de rendergrootte, en uiteindelijk het opslaan van het resultaat als een PNG‑bestand op schijf. Geen externe tools, geen ingewikkelde command‑line trucs—alleen pure C#‑code die je in elk .NET‑project kunt plaatsen. + +## Wat je leert + +- Hoe je **webpagina naar PNG rendert** met de `HTMLDocument`‑klasse van Aspose.HTML. +- De exacte stappen om **afbeeldingsgrootte‑rendering in te stellen** zodat de output overeenkomt met je lay‑outvereisten. +- Manieren om **afbeelding naar bestand te schrijven** op een veilige manier, met streams en bestandspaden. +- Tips voor het oplossen van veelvoorkomende valkuilen zoals ontbrekende lettertypen of netwerktime‑outs. + +### Vereisten + +- .NET 6.0 of later (de API werkt ook met .NET Framework, maar .NET 6+ wordt aanbevolen). +- Een referentie naar het Aspose.HTML for .NET NuGet‑pakket (`Aspose.Html`). +- Basiskennis van C# en async/await (optioneel maar handig). + +Als je deze zaken al hebt, kun je meteen beginnen met het converteren van HTML naar afbeelding. + +## Stap 1: De webpagina laden – De basis voor het converteren van HTML naar afbeelding + +Voordat er gerenderd kan worden, heb je een `HTMLDocument`‑instantie nodig die de pagina vertegenwoordigt die je wilt vastleggen. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Waarom dit belangrijk is:* De `HTMLDocument` parseert de HTML, lost CSS op en bouwt de DOM. Als het document niet kan worden geladen (bijv. netwerkprobleem), zal de daaropvolgende rendering een lege afbeelding opleveren. Controleer altijd of de URL bereikbaar is voordat je verder gaat. + +## Stap 2: Afbeeldingsgrootte‑rendering instellen – Breedte, hoogte en kwaliteit regelen + +Aspose.HTML laat je de uitvoerafmetingen fijn afstemmen met `ImageRenderingOptions`. Hier stel je **afbeeldingsgrootte‑rendering in** zodat deze overeenkomt met je doel‑lay‑out. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Pro‑tip:* Als je `Width` en `Height` weglaat, gebruikt Aspose.HTML de intrinsieke grootte van de pagina, wat onvoorspelbaar kan zijn voor responsieve ontwerpen. Het expliciet opgeven van afmetingen zorgt ervoor dat je **HTML als PNG opslaat** er precies uitziet zoals je verwacht. + +## Stap 3: Afbeelding naar bestand schrijven – De gerenderde PNG opslaan + +Nu het document klaar is en de renderopties zijn ingesteld, kun je eindelijk **afbeelding naar bestand schrijven**. Het gebruik van een `FileStream` garandeert dat het bestand veilig wordt aangemaakt, zelfs als de map nog niet bestaat. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +Na het uitvoeren van dit blok vind je `page.png` op de opgegeven locatie. Je hebt zojuist een **webpagina naar PNG gerenderd** en naar schijf geschreven in één eenvoudige bewerking. + +### Verwacht resultaat + +Open `C:\Temp\page.png` met een willekeurige afbeeldingsviewer. Je zou een getrouwe snapshot van `https://example.com` moeten zien, gerenderd op 1024 × 768 pixels met vloeiende randen dankzij antialiasing. Als de pagina dynamische inhoud bevat (bijv. door JavaScript gegenereerde elementen), worden deze vastgelegd zolang de DOM volledig is geladen vóór het renderen. + +## Stap 4: Randgevallen afhandelen – Lettertypen, authenticatie en grote pagina's + +Hoewel de basisstroom voor de meeste openbare sites werkt, brengen real‑world scenario’s vaak onverwachte uitdagingen met zich mee: + +| Situatie | Wat te doen | +|-----------|------------| +| **Aangepaste lettertypen worden niet geladen** | Voeg de lettertypebestanden lokaal toe en gebruik `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Pagina's achter authenticatie** | Gebruik de `HTMLDocument`‑overload die een `HttpWebRequest` met cookies of tokens accepteert. | +| **Zeer lange pagina's** | Verhoog `Height` of schakel `PageScaling` in bij `ImageRenderingOptions` om afkappen te voorkomen. | +| **Geheugengebruik piekt** | Render in delen met de `RenderToImage`‑overload die een `Rectangle`‑regio accepteert. | + +Door deze *afbeelding naar bestand schrijven* nuances aan te pakken, blijft je **HTML naar afbeelding converteren**‑pipeline robuust in productie. + +## Stap 5: Volledig werkend voorbeeld – Klaar om te kopiëren en plakken + +Hieronder staat het volledige programma, klaar om te compileren. Het bevat alle stappen, foutafhandeling en commentaren die je nodig hebt. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Voer dit programma uit, en je ziet het bevestigingsbericht in de console. Het PNG‑bestand zal precies zijn wat je zou verwachten wanneer je **webpagina naar PNG rendert** handmatig in een browser en een screenshot maakt—alleen sneller en volledig geautomatiseerd. + +## Veelgestelde vragen + +**V: Kan ik een lokaal HTML‑bestand converteren in plaats van een URL?** +Zeker. Vervang gewoon de URL door een bestandspad: `new HTMLDocument(@"C:\myPage.html")`. + +**V: Heb ik een licentie nodig voor Aspose.HTML?** +Een gratis evaluatielicentie werkt voor ontwikkeling en testen. Voor productie koop je een licentie om het evaluatiewatermerk te verwijderen. + +**V: Wat als de pagina JavaScript gebruikt om inhoud na de initiële load te laden?** +Aspose.HTML voert JavaScript synchroon uit tijdens het parsen, maar langdurige scripts kunnen een handmatige vertraging vereisen. Je kunt `HTMLDocument.WaitForReadyState` gebruiken vóór het renderen. + +## Conclusie + +Je beschikt nu over een solide, end‑to‑end‑oplossing om **HTML naar afbeelding te converteren** in C#. Door de bovenstaande stappen te volgen kun je **HTML als PNG opslaan**, nauwkeurig **afbeeldingsgrootte‑rendering instellen**, en met vertrouwen **afbeelding naar bestand schrijven** op elk Windows‑ of Linux‑systeem. + +Van eenvoudige screenshots tot geautomatiseerde rapportgeneratie, deze techniek schaalt moeiteloos. Probeer vervolgens andere outputformaten zoals JPEG of BMP, of integreer de code in een ASP.NET Core API die de PNG direct terugstuurt naar de aanroeper. De mogelijkheden zijn praktisch eindeloos. + +Happy coding, en moge je gerenderde afbeeldingen altijd pixel‑perfect zijn! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/dutch/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..96a576862 --- /dev/null +++ b/html/dutch/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-03-21 +description: Maak snel PDF's van HTML met Aspose HTML. Leer hoe je HTML naar PDF rendert, + HTML naar PDF converteert en hoe je Aspose gebruikt in een beknopte tutorial. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: nl +og_description: Maak PDF van HTML met Aspose in C#. Deze gids laat zien hoe je HTML + naar PDF rendert, HTML naar PDF converteert en hoe je Aspose effectief gebruikt. +og_title: PDF maken van HTML – Complete Aspose C# Tutorial +tags: +- Aspose +- C# +- PDF generation +title: PDF maken van HTML met Aspose – Stapsgewijze C#‑gids +url: /nl/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF maken van HTML met Aspose – Stap‑voor‑stap C#‑gids + +Heb je ooit **PDF maken van HTML** nodig gehad, maar wist je niet welke bibliotheek pixel‑perfecte resultaten levert? Je bent niet de enige. Veel ontwikkelaars struikelen wanneer ze een webfragment willen omzetten naar een afdrukbaar document, en eindigen met onscherpe tekst of kapotte lay‑outs. + +Het goede nieuws is dat Aspose HTML het hele proces moeiteloos maakt. In deze tutorial lopen we de exacte code door die je nodig hebt om **HTML naar PDF te renderen**, onderzoeken waarom elke instelling belangrijk is, en laten we je zien hoe je **HTML naar PDF kunt converteren** zonder verborgen trucjes. Aan het einde weet je **hoe je Aspose gebruikt** voor betrouwbare PDF‑generatie in elk .NET‑project. + +## Vereisten – Wat je nodig hebt voordat je begint + +- **.NET 6.0 of later** (het voorbeeld werkt ook op .NET Framework 4.7+) +- **Visual Studio 2022** of een IDE die C# ondersteunt +- **Aspose.HTML for .NET** NuGet‑pakket (gratis proefversie of gelicentieerde versie) +- Een basisbegrip van C#‑syntaxis (geen diepgaande PDF‑kennis vereist) + +Als je die hebt, ben je klaar om te beginnen. Anders haal je de nieuwste .NET SDK en installeer je het NuGet‑pakket met: + +```bash +dotnet add package Aspose.HTML +``` + +Die ene regel haalt alles op wat je nodig hebt voor **aspose html to pdf** conversie. + +## Stap 1: Stel je project in om PDF van HTML te maken + +Het eerste wat je doet is een nieuwe console‑app maken (of de code integreren in een bestaande service). Hier is een minimale `Program.cs`‑skelet: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** Als je `Aspise.Html.Rendering.Text` ziet in oudere voorbeelden, vervang dit door `Aspose.Html.Rendering.Text`. De typfout veroorzaakt een compileerfout. + +Het hebben van de juiste namespaces zorgt ervoor dat de compiler de **TextOptions**‑klasse kan vinden die we later nodig hebben. + +## Stap 2: Bouw het HTML‑document (HTML naar PDF renderen) + +Nu maken we de bron‑HTML. Aspose laat je een ruwe string, een bestandspad of zelfs een URL doorgeven. Voor deze demo houden we het simpel: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Waarom een string doorgeven? Het voorkomt bestands‑I/O, versnelt de conversie en garandeert dat de HTML die je in de code ziet exact is wat wordt gerenderd. Als je liever vanuit een bestand laadt, vervang dan gewoon het constructor‑argument door een bestands‑URI. + +## Stap 3: Fijn afstellen van tekstrendering (HTML naar PDF converteren met betere kwaliteit) + +Tekstrendering bepaalt vaak of je PDF scherp of wazig uitziet. Aspose biedt een `TextOptions`‑klasse waarmee je sub‑pixel hinting kunt inschakelen — essentieel voor high‑DPI‑output. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Het inschakelen van `UseHinting` is vooral nuttig wanneer je bron‑HTML aangepaste lettertypen of kleine lettergroottes bevat. Zonder dit kun je gekartelde randen in de uiteindelijke PDF opmerken. + +## Stap 4: Koppel tekstopties aan PDF‑renderconfiguratie (Hoe Aspose te gebruiken) + +Vervolgens koppelen we die tekstopties aan de PDF‑renderer. Hier komt **aspose html to pdf** echt tot zijn recht — alles van paginagrootte tot compressie kan worden aangepast. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Je kunt `PageSetup` weglaten als je tevreden bent met de standaard A4‑grootte. Het belangrijkste is dat het `TextOptions`‑object zich bevindt binnen `PdfRenderingOptions`, en zo vertel je Aspose *hoe* de tekst moet renderen. + +## Stap 5: Render de HTML en sla de PDF op (HTML naar PDF converteren) + +Tot slot streamen we de output naar een bestand. Het gebruik van een `using`‑blok garandeert dat de bestands‑handle correct wordt gesloten, zelfs als er een uitzondering optreedt. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Wanneer je het programma uitvoert, vind je `output.pdf` naast het uitvoerbare bestand. Open het, en je zou een nette kop en alinea moeten zien — precies zoals gedefinieerd in de HTML‑string. + +### Verwachte output + +![voorbeeld uitvoer van pdf maken van html](https://example.com/images/pdf-output.png "voorbeeld uitvoer van pdf maken van html") + +*De screenshot toont de gegenereerde PDF met de kop “Hello, Aspose!” scherp gerenderd dankzij tekst‑hinting.* + +## Veelgestelde vragen & randgevallen + +### 1. Wat als mijn HTML externe bronnen (afbeeldingen, CSS) verwijst? + +Aspose lostt relatieve URL's op basis van de basis‑URI van het document. Als je een ruwe string doorgeeft, stel dan handmatig de basis‑URI in: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Nu wordt elke `` opgezocht relatief ten opzichte van `C:/MyProject/`. + +### 2. Hoe embed ik lettertypen die niet op de server geïnstalleerd zijn? + +Voeg een ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Stap 4: Configureer opslaan‑opties om de aangepaste opslag te gebruiken + +`HtmlSaveOptions` stelt ons in staat Aspose te laten alles in een ZIP‑bestand verpakken. De `OutputStorage`‑eigenschap (legacy) ontvangt onze `MyStorage`‑instantie. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Opmerking:** In Aspose HTML 23.9+ heet de eigenschap `OutputStorage` maar is gemarkeerd als verouderd. Het moderne alternatief is `ZipOutputStorage`. De onderstaande code werkt met beide omdat de interface hetzelfde is. + +### Stap 5: Sla het document op als een ZIP‑archief + +Kies een doelmap (of stream) en laat Aspose het zware werk doen. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Wanneer het programma klaar is, vind je `output.zip` met: + +* `index.html` – het hoofd‑document. +* Alle ingesloten afbeeldingen, CSS‑bestanden of scripts (als je HTML ernaar verwees). + +Je kunt de ZIP openen met elke archiefbeheerder om de structuur te verifiëren. + +--- + +## Resultaat verifiëren (optioneel) + +Als je het archief programmatisch wilt inspecteren zonder het naar schijf uit te pakken: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Typische uitvoer: + +``` +- index.html (452 bytes) +``` + +Als je afbeeldingen of CSS had, zouden die als extra items verschijnen. Deze snelle controle bevestigt dat **create html zip archive** naar verwachting heeft gewerkt. + +## Veelgestelde vragen & randgevallen + +| Vraag | Antwoord | +|----------|--------| +| **Wat als ik de ZIP direct naar een response‑stream moet schrijven?** | Retourneer de `MemoryStream` die je krijgt van `MyStorage` na `document.Save`. Cast deze naar een `byte[]` en schrijf deze naar `HttpResponse.Body`. | +| **Mijn HTML verwijst naar externe URL's—worden die gedownload?** | Nee. Aspose verpakt alleen bronnen die *ingesloten* zijn (bijv. `` of lokale bestanden). Voor externe assets moet je ze eerst downloaden en de markup aanpassen. | +| **De eigenschap `OutputStorage` is gemarkeerd als verouderd—moet ik die negeren?** | Hij werkt nog steeds, maar de nieuwere `ZipOutputStorage` biedt dezelfde API met een andere naam. Vervang `OutputStorage` door `ZipOutputStorage` als je een waarschuwing‑vrije build wilt. | +| **Kan ik de ZIP versleutelen?** | Ja. Na het opslaan open je het bestand met `System.IO.Compression.ZipArchive` en stel je een wachtwoord in met behulp van third‑party bibliotheken zoals `SharpZipLib`. Aspose zelf biedt geen versleuteling. | + +## Volledig werkend voorbeeld (kopiëren‑plakken) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Voer het programma uit, open `output.zip`, en je ziet een enkel `index.html`‑bestand dat de koptekst “Hello from ZIP!” weergeeft wanneer het in een browser wordt geopend. + +## Conclusie + +Je weet nu **hoe je HTML opslaat als ZIP** in C# met een **aangepaste opslag**‑klasse, hoe je **HTML exporteert naar ZIP**, en hoe je **een HTML‑zip‑archief** maakt dat klaar is voor distributie. Het patroon is flexibel—verwissel `MemoryStream` voor een cloud‑stream, voeg versleuteling toe, of integreer het in een web‑API die de ZIP op aanvraag retourneert. De mogelijkheden zijn eindeloos wanneer je de ZIP‑mogelijkheden van Aspose.HTML combineert met je eigen opslaglogica. + +Klaar voor de volgende stap? Probeer een volledige webpagina met afbeeldingen en stijlen te verwerken, of koppel de opslag aan Azure Blob Storage om het lokale bestandssysteem volledig te omzeilen. De mogelijkheden zijn eindeloos wanneer je de ZIP‑mogelijkheden van Aspose.HTML combineert met je eigen opslaglogica. + +Veel plezier met coderen, en moge je archieven altijd netjes blijven! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/english/net/generate-jpg-and-png-images/_index.md b/html/english/net/generate-jpg-and-png-images/_index.md index 3cc4b6acd..1c7df63bd 100644 --- a/html/english/net/generate-jpg-and-png-images/_index.md +++ b/html/english/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Learn to use Aspose.HTML for .NET to manipulate HTML documents, convert HTML to Learn how to enable antialiasing for sharper PNG/JPG output when converting DOCX files using Aspose.HTML for .NET. ### [convert docx to png – create zip archive c# tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Learn how to convert DOCX files to PNG images and package them into a ZIP archive using C# and Aspose.HTML. +### [Convert HTML to PNG – Full C# Guide with ZIP Export](./convert-html-to-png-full-c-guide-with-zip-export/) +Comprehensive C# tutorial to convert HTML to PNG images and export them as a ZIP archive using Aspose.HTML. ## Conclusion diff --git a/html/english/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/english/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..d3d316a89 --- /dev/null +++ b/html/english/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-03-21 +description: Convert HTML to PNG and render HTML as image while saving HTML to ZIP. + Learn to apply font style HTML and add bold to p elements in just a few steps. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: en +og_description: Convert HTML to PNG quickly. This guide shows how to render HTML as + image, save HTML to ZIP, apply font style HTML and add bold to p elements. +og_title: Convert HTML to PNG – Complete C# Tutorial +tags: +- Aspose +- C# +title: Convert HTML to PNG – Full C# Guide with ZIP Export +url: /net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convert HTML to PNG – Full C# Guide with ZIP Export + +Ever needed to **convert HTML to PNG** but weren’t sure which library could do it without pulling in a headless browser? You’re not alone. In many projects—email thumbnails, documentation previews, or quick‑look images—turning a web page into a static picture is a real‑world need. + +The good news? With Aspose.HTML you can **render HTML as image**, tweak the markup on the fly, and even **save HTML to ZIP** for later distribution. In this tutorial we’ll walk through a complete, runnable example that **applies font style HTML**, specifically **add bold to p** elements, before producing a PNG file. By the end you’ll have a single C# class that does everything from loading a page to archiving its resources. + +## What You’ll Need + +- .NET 6.0 or later (the API works on .NET Core as well) +- Aspose.HTML for .NET 6+ (NuGet package `Aspose.Html`) +- A basic understanding of C# syntax (no advanced concepts required) + +That’s it. No external browsers, no phantomjs, just pure managed code. + +## Step 1 – Load the HTML Document + +First we bring the source file (or URL) into an `HTMLDocument` object. This step is the foundation for both **render html as image** and **save html to zip** later on. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Why this matters:* The `HTMLDocument` class parses the markup, builds a DOM, and resolves linked resources (CSS, images, fonts). Without a proper document object you can’t manipulate styles or render anything. + +## Step 2 – Apply Font Style HTML (Add Bold to p) + +Now we’ll **apply font style HTML** by iterating over every `

` element and setting its `font-weight` to bold. This is the programmatic way to **add bold to p** tags without touching the original file. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Pro tip:* If you only need to bold a subset, change the selector to something more specific, e.g., `"p.intro"`. + +## Step 3 – Render HTML as Image (Convert HTML to PNG) + +With the DOM ready, we configure `ImageRenderingOptions` and call `RenderToImage`. This is where the **convert html to png** magic happens. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Why the options matter:* Setting a fixed width/height prevents the output from being too large, while antialiasing gives a smoother visual result. You can also switch `options` to `ImageFormat.Jpeg` if you prefer a smaller file size. + +## Step 4 – Save HTML to ZIP (Bundle Resources) + +Often you need to ship the original HTML together with its CSS, images, and fonts. Aspose.HTML’s `ZipArchiveSaveOptions` does exactly that. We also plug in a custom `ResourceHandler` so all external assets are written to the same folder as the archive. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Edge case:* If your HTML references remote images that require authentication, the default handler will fail. In that scenario you can extend `MyResourceHandler` to inject HTTP headers. + +## Step 5 – Wire Everything Up in a Single Converter Class + +Below is the full, ready‑to‑run class that ties all the previous steps together. You can copy‑paste it into a console app, call `Convert`, and watch the files appear. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Expected Output + +After running the snippet above you’ll find two files in `outputDirectory`: + +| File | Description | +|------|-------------| +| `page.png` | A 1200 × 800 PNG rendering of the source HTML, with every paragraph displayed in **bold**. | +| `archive.zip` | A ZIP bundle containing the original `input.html`, its CSS, images, and any web‑fonts – perfect for offline distribution. | + +You can open `page.png` in any image viewer to verify that the bold styling was applied, and extract `archive.zip` to see the untouched HTML alongside its assets. + +## Common Questions & Gotchas + +- **What if the HTML contains JavaScript?** + Aspose.HTML does **not** execute scripts during rendering, so dynamic content won’t appear. For fully‑rendered pages you’d need a headless browser, but for static templates this approach is faster and lighter. + +- **Can I change the output format to JPEG or BMP?** + Yes—swap `ImageRenderingOptions`’ `ImageFormat` property, e.g., `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Do I need to dispose of the `HTMLDocument` manually?** + The class implements `IDisposable`. In a long‑running service wrap it in a `using` block or call `document.Dispose()` after you’re done. + +- **How does the custom `MyResourceHandler` work?** + It receives each external resource (CSS, images, fonts) and writes it to the folder you specify. This ensures the ZIP contains a faithful copy of everything the HTML references. + +## Conclusion + +You now have a compact, production‑ready solution that **convert html to png**, **render html as image**, **save html to zip**, **apply font style html**, and **add bold to p**—all in a handful of C# lines. The code is self‑contained, works with .NET 6+, and can be dropped into any backend service that needs quick visual snapshots of web content. + +Ready for the next step? Try swapping the rendering size, experiment with other CSS properties (like `font-family` or `color`), or integrate this converter into an ASP.NET Core endpoint that returns the PNG on demand. The possibilities are endless, and with Aspose.HTML you stay clear of heavyweight browser dependencies. + +If you ran into hiccups or have ideas for extensions, drop a comment below. Happy coding! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/english/net/html-document-manipulation/_index.md index ba25012a0..2e773c5bf 100644 --- a/html/english/net/html-document-manipulation/_index.md +++ b/html/english/net/html-document-manipulation/_index.md @@ -59,6 +59,8 @@ Unlock the potential of Aspose.HTML for .NET with our comprehensive guide. Learn Learn how to harness the power of Aspose.HTML for .NET. Boost your web development with HTML manipulation and rendering. ### [Creating a Document in .NET with Aspose.HTML](./creating-a-document/) Unleash the Power of Aspose.HTML for .NET. Learn to Create, Manipulate, and Optimize HTML and SVG Documents with Ease. Explore Step-By-Step Examples and FAQs. +### [Create HTML Document C# – Step‑by‑Step Guide](./create-html-document-c-step-by-step-guide/) +Learn how to create an HTML document in C# using Aspose.HTML with a clear, step‑by‑step guide. ### [Create HTML from String in C# – Custom Resource Handler Guide](./create-html-from-string-in-c-custom-resource-handler-guide/) Learn how to generate HTML from a string using a custom resource handler in C# with Aspose.HTML for .NET. ### [Editing a Document in .NET with Aspose.HTML](./editing-a-document/) diff --git a/html/english/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/english/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..9982fdcf0 --- /dev/null +++ b/html/english/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Create HTML document C# and learn how to get element by id, locate element + by id, change HTML element style and add bold italic using Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: en +og_description: Create HTML document C# and instantly learn to get element by id, + locate element by id, change HTML element style and add bold italic with clear code + examples. +og_title: Create HTML Document C# – Complete Programming Guide +tags: +- Aspose.Html +- C# +- DOM manipulation +title: Create HTML Document C# – Step‑by‑Step Guide +url: /net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create HTML Document C# – Step‑by‑Step Guide + +Ever needed to **create HTML document C#** from scratch and then tweak a single paragraph’s look? You’re not the only one. In many web‑automation projects you’ll spin up an HTML file, hunt down a tag by its ID, and then apply some styling—often bold + italic—without ever touching a browser. + +In this tutorial we’ll walk through exactly that: we’ll create an HTML document in C#, **get element by id**, **locate element by id**, **change HTML element style**, and finally **add bold italic** using the Aspose.Html library. By the end you’ll have a fully runnable snippet you can drop into any .NET project. + +## What You’ll Need + +- .NET 6 or later (the code works on .NET Framework 4.7+ as well) +- Visual Studio 2022 (or any editor you like) +- The **Aspose.Html** NuGet package (`Install-Package Aspose.Html`) + +That’s it—no extra HTML files, no web server, just a few lines of C#. + +## Create HTML Document C# – Initialize the Document + +First things first: you need a live `HTMLDocument` object that the Aspose.Html engine can work with. Think of this as opening a fresh notebook where you’ll write your markup. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Why this matters:** By passing the raw string to `HTMLDocument`, you avoid dealing with file I/O and keep everything in memory—perfect for unit tests or on‑the‑fly generation. + +## Get Element by ID – Finding the Paragraph + +Now that the document exists, we need to **get element by id**. The DOM API gives us `GetElementById`, which returns an `IElement` reference or `null` if the ID isn’t present. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Pro tip:** Even though our markup is tiny, adding a null‑check saves you headaches when the same logic is reused on larger, dynamic pages. + +## Locate Element by ID – An Alternative Approach + +Sometimes you might already have a reference to the document’s root and prefer a query‑style search. Using CSS selectors (`QuerySelector`) is another way to **locate element by id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **When to use which?** `GetElementById` is marginally faster because it’s a direct hash lookup. `QuerySelector` shines when you need complex selectors (e.g., `div > p.highlight`). + +## Change HTML Element Style – Adding Bold Italic + +With the element in hand, the next step is to **change HTML element style**. Aspose.Html exposes a `Style` object where you can adjust CSS properties or use the handy `WebFontStyle` enumeration to apply multiple font traits at once. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +That single line sets the element’s `font-weight` to `bold` and `font-style` to `italic`. Under the hood Aspose.Html translates the enum into the appropriate CSS string. + +### Full Working Example + +Putting all the pieces together yields a compact, self‑contained program you can compile and run immediately: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Expected output** + +``` +Rendered HTML: +

Hello world

+``` + +The `

` tag now carries an inline `style` attribute that makes the text both bold and italic—exactly what we wanted. + +## Edge Cases & Common Pitfalls + +| Situation | What to Watch For | How to Handle | +|-----------|-------------------|---------------| +| **ID does not exist** | `GetElementById` returns `null`. | Throw an exception or fallback to a default element. | +| **Multiple elements share the same ID** | HTML spec says IDs must be unique, but real‑world pages sometimes break the rule. | `GetElementById` returns the first match; consider using `QuerySelectorAll` if you need to handle duplicates. | +| **Styling conflicts** | Existing inline styles may be overwritten. | Append to the `Style` object instead of setting the whole `style` string: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Rendering in a browser** | Some browsers ignore `WebFontStyle` if the element already has a CSS class with higher specificity. | Use `!important` via `paragraph.Style.SetProperty("font-weight", "bold", "important");` if needed. | + +## Pro Tips for Real‑World Projects + +- **Cache the document** if you’re processing many elements; creating a new `HTMLDocument` for every tiny snippet can hurt performance. +- **Combine style changes** in a single `Style` transaction to avoid multiple DOM reflows. +- **Leverage Aspose.Html’s rendering engine** to export the final document as PDF or image—great for reporting tools. + +## Visual Confirmation (Optional) + +If you prefer to see the result in a browser, you can save the rendered string to an `.html` file: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Open `output.html` and you’ll see **Hello world** displayed in bold + italic. + +![Create HTML Document C# example showing bold italic paragraph](/images/create-html-document-csharp.png "Create HTML Document C# – rendered output") + +*Alt text: Create HTML Document C# – rendered output with bold italic text.* + +## Conclusion + +We’ve just **created an HTML document C#**, **got element by id**, **located element by id**, **changed HTML element style**, and finally **added bold italic**—all with a handful of lines using Aspose.Html. The approach is straightforward, works in any .NET environment, and scales to larger DOM manipulations. + +Ready for the next step? Try swapping the `WebFontStyle` for other enums like `Underline` or combine multiple styles manually. Or experiment with loading an external HTML file and applying the same technique to hundreds of elements. The sky’s the limit, and now you have a solid foundation to build on. + +Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/english/net/html-extensions-and-conversions/_index.md b/html/english/net/html-extensions-and-conversions/_index.md index a50bc9ccb..763461ae2 100644 --- a/html/english/net/html-extensions-and-conversions/_index.md +++ b/html/english/net/html-extensions-and-conversions/_index.md @@ -18,7 +18,7 @@ Are you eager to enhance your web development skills and unlock the power of HTM ## What Is Aspose.HTML for .NET? -Before we dive into the tutorials, let's take a moment to understand what Aspose.HTML for .NET is. Aspose.HTML is a powerful library that empowers developers to work with HTML documents in a variety of ways, including conversion, extraction, and manipulation. Whether you are building a website, working on a web application, or dealing with data extraction, Aspose.HTML for .NET can be your go-to tool. +Before we dive into the tutorials, let's take a moment to understand what Aspose.HTML for .NET is. Aspose.HTML is a powerful library that empowers developers to work with HTML documents in a variety of ways, including conversion, extraction, and manipulation. Whether you are building a website, working on a web application, or dealing with data extraction, Aspose.HTML for .NET can be your go‑to tool. ## HTML Extensions Demystified @@ -30,55 +30,63 @@ Web development often involves converting HTML documents into different formats. ## Get Started with Aspose.HTML -Are you ready to get started? Aspose.HTML for .NET tutorials cater to both beginners and experienced developers. Whether you are new to HTML extensions and conversions or seeking advanced tips, our step-by-step guides are designed to suit your needs. +Are you ready to get started? Aspose.HTML for .NET tutorials cater to both beginners and experienced developers. Whether you are new to HTML extensions and conversions or seeking advanced tips, our step‑by‑step guides are designed to suit your needs. ## Why Aspose.HTML for .NET? -Aspose.HTML for .NET is not just a library; it's a game-changer in the world of web development. It offers an extensive range of features and tools that streamline your HTML-related tasks. By the end of these tutorials, you'll be equipped with the knowledge and skills to maximize the potential of Aspose.HTML for .NET. +Aspose.HTML for .NET is not just a library; it's a game‑changer in the world of web development. It offers an extensive range of features and tools that streamline your HTML‑related tasks. By the end of these tutorials, you'll be equipped with the knowledge and skills to maximize the potential of Aspose.HTML for .NET. ## HTML Extensions and Conversions Tutorials ### [Convert HTML to PDF in .NET with Aspose.HTML](./convert-html-to-pdf/) -Convert HTML to PDF effortlessly with Aspose.HTML for .NET. Follow our step-by-step guide and unleash the power of HTML-to-PDF conversion. +Convert HTML to PDF effortlessly with Aspose.HTML for .NET. Follow our step‑by‑step guide and unleash the power of HTML‑to‑PDF conversion. ### [Create PDF from HTML – C# Step‑by‑Step Guide](./create-pdf-from-html-c-step-by-step-guide/) Learn how to generate PDF files from HTML using Aspose.HTML for .NET with a detailed C# step‑by‑step guide. +### [Create PDF from HTML with Aspose – Step‑by‑Step C# Guide](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Learn how to generate PDFs from HTML using Aspose.HTML for .NET with a detailed C# step‑by‑step guide. ### [Convert EPUB to Image in .NET with Aspose.HTML](./convert-epub-to-image/) -Learn how to convert EPUB to images using Aspose.HTML for .NET. Step-by-step tutorial with code examples and customizable options. +Learn how to convert EPUB to images using Aspose.HTML for .NET. Step‑by‑step tutorial with code examples and customizable options. ### [Convert EPUB to PDF in .NET with Aspose.HTML](./convert-epub-to-pdf/) -Learn how to convert EPUB to PDF using Aspose.HTML for .NET. This step-by-step guide covers customization options, FAQs, and more for seamless document conversion. +Learn how to convert EPUB to PDF using Aspose.HTML for .NET. This step‑by‑step guide covers customization options, FAQs, and more for seamless document conversion. ### [Convert EPUB to XPS in .NET with Aspose.HTML](./convert-epub-to-xps/) -Learn how to convert EPUB to XPS in .NET using Aspose.HTML for .NET. Follow our step-by-step guide for effortless conversions. +Learn how to convert EPUB to XPS in .NET using Aspose.HTML for .NET. Follow our step‑by‑step guide for effortless conversions. ### [Convert HTML to BMP in .NET with Aspose.HTML](./convert-html-to-bmp/) Learn how to convert HTML to BMP in .NET using Aspose.HTML for .NET. Comprehensive guide for web developers for Leveraging Aspose.HTML for .NET. ### [Convert HTML to DOC and DOCX in .NET with Aspose.HTML](./convert-html-to-doc-docx/) -Learn how to harness the power of Aspose.HTML for .NET in this step-by-step guide. Convert HTML to DOCX effortlessly and level up your .NET projects. Get started today! +Learn how to harness the power of Aspose.HTML for .NET in this step‑by‑step guide. Convert HTML to DOCX effortlessly and level up your .NET projects. Get started today! ### [Convert HTML to GIF in .NET with Aspose.HTML](./convert-html-to-gif/) -Discover the power of Aspose.HTML for .NET: A step-by-step guide to converting HTML to GIF. Prerequisites, code examples, FAQs, and more! Optimize your HTML manipulation with Aspose.HTML. +Discover the power of Aspose.HTML for .NET: A step‑by‑step guide to converting HTML to GIF. Prerequisites, code examples, FAQs, and more! Optimize your HTML manipulation with Aspose.HTML. ### [Convert HTML to JPEG in .NET with Aspose.HTML](./convert-html-to-jpeg/) -Learn how to convert HTML to JPEG in .NET with Aspose.HTML for .NET. A step-by-step guide to harnessing the power of Aspose.HTML for .NET. Optimize your web development tasks effortlessly. +Learn how to convert HTML to JPEG in .NET with Aspose.HTML for .NET. A step‑by‑step guide to harnessing the power of Aspose.HTML for .NET. Optimize your web development tasks effortlessly. ### [Convert HTML to Markdown in .NET with Aspose.HTML](./convert-html-to-markdown/) -Learn how to convert HTML to Markdown in .NET using Aspose.HTML for efficient content manipulation. Get step-by-step guidance for a seamless conversion process. +Learn how to convert HTML to Markdown in .NET using Aspose.HTML for efficient content manipulation. Get step‑by‑step guidance for a seamless conversion process. ### [Convert HTML to MHTML in .NET with Aspose.HTML](./convert-html-to-mhtml/) -Convert HTML to MHTML in .NET with Aspose.HTML - A step-by-step guide for efficient web content archiving. Learn how to use Aspose.HTML for .NET to create MHTML archives. +Convert HTML to MHTML in .NET with Aspose.HTML - A step‑by‑step guide for efficient web content archiving. Learn how to use Aspose.HTML for .NET to create MHTML archives. ### [Convert HTML to PNG in .NET with Aspose.HTML](./convert-html-to-png/) -Discover how to use Aspose.HTML for .NET to manipulate and convert HTML documents. Step-by-step guide for effective .NET development. +Discover how to use Aspose.HTML for .NET to manipulate and convert HTML documents. Step‑by‑step guide for effective .NET development. ### [Convert HTML to TIFF in .NET with Aspose.HTML](./convert-html-to-tiff/) -Learn how to convert HTML to TIFF with Aspose.HTML for .NET. Follow our step-by-step guide for efficient web content optimization. +Learn how to convert HTML to TIFF with Aspose.HTML for .NET. Follow our step‑by‑step guide for efficient web content optimization. ### [Convert HTML to XPS in .NET with Aspose.HTML](./convert-html-to-xps/) -Discover the power of Aspose.HTML for .NET: Convert HTML to XPS effortlessly. Prerequisites, step-by-step guide, and FAQs included. +Discover the power of Aspose.HTML for .NET: Convert HTML to XPS effortlessly. Prerequisites, step‑by‑step guide, and FAQs included. ### [How to Zip HTML in C# – Save HTML to Zip](./how-to-zip-html-in-c-save-html-to-zip/) -Learn how to zip HTML files in C# using Aspose.HTML, saving HTML content to a ZIP archive with step-by-step guidance. +Learn how to zip HTML files in C# using Aspose.HTML, saving HTML content to a ZIP archive with step‑by‑step guidance. +### [How to Zip HTML with Aspose.HTML – Complete Guide](./how-to-zip-html-with-aspose-html-complete-guide/) +Learn how to zip HTML files using Aspose.HTML in a complete step‑by‑step guide. ### [Create HTML Document with Styled Text and Export to PDF – Full Guide](./create-html-document-with-styled-text-and-export-to-pdf-full/) Learn how to create an HTML document with styled text and export it to PDF using Aspose.HTML for .NET in this comprehensive guide. ### [Save HTML as ZIP – Complete C# Tutorial](./save-html-as-zip-complete-c-tutorial/) Learn how to save HTML files as a ZIP archive using Aspose.HTML for .NET with a complete C# example. ### [Convert EPUB to Image in .NET with Aspose.HTML](./convert-epub-to-image/) -Learn how to convert EPUB to images using Aspose.HTML for .NET. Step-by-step tutorial with code examples and customizable options. +Learn how to convert EPUB to images using Aspose.HTML for .NET. Step‑by‑step tutorial with code examples and customizable options. ### [Convert EPUB to PDF in .NET with Aspose.HTML](./convert-epub-to-pdf/) -Learn how to convert EPUB to PDF using Aspose.HTML for .NET. This step-by-step guide covers customization options, FAQs, and more for seamless document conversion. +Learn how to convert EPUB to PDF using Aspose.HTML for .NET. This step‑by‑step guide covers customization options, FAQs, and more for seamless document conversion. ### [Convert EPUB to XPS in .NET with Aspose.HTML](./convert-epub-to-xps/) -Learn how to convert EPUB to XPS in .NET using Aspose.HTML for .NET. Follow our step-by-step guide for effortless conversions. +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. +Learn how to save HTML content into a ZIP archive in memory using C# and Aspose.HTML for .NET in a step‑by‑step tutorial. +### [Save HTML as ZIP in C# – Complete Guide with Custom Storage](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Learn how to save HTML content as a ZIP archive using custom storage options in C# with Aspose.HTML for .NET. +### [Convert HTML to Image in C# – Complete Guide](./convert-html-to-image-in-c-complete-guide/) +Learn how to convert HTML to various image formats using C# and Aspose.HTML for .NET in a comprehensive step‑by‑step guide. ## Conclusion diff --git a/html/english/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/english/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..79e95a5ee --- /dev/null +++ b/html/english/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,187 @@ +--- +category: general +date: 2026-03-21 +description: Convert HTML to image using Aspose.HTML in C#. Learn how to save HTML + as PNG, set image size rendering, and write image to file in just a few steps. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: en +og_description: Convert HTML to image quickly. This guide shows how to save HTML as + PNG, set image size rendering, and write image to file with Aspose.HTML. +og_title: Convert HTML to Image in C# – Step‑by‑Step Guide +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Convert HTML to Image in C# – Complete Guide +url: /net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convert HTML to Image in C# – Complete Guide + +Ever needed to **convert HTML to image** for a dashboard thumbnail, an email preview, or a PDF report? It’s a scenario that pops up more often than you’d expect, especially when you’re dealing with dynamic web content that must be embedded somewhere else. + +The good news? With Aspose.HTML you can **convert HTML to image** in just a handful of lines, and you’ll also learn how to *save HTML as PNG*, control the output dimensions, and *write image to file* without breaking a sweat. + +In this tutorial we’ll walk through everything you need to know: from loading a remote page to tweaking the rendering size, and finally persisting the result as a PNG file on disk. No external tools, no fiddly command‑line tricks—just pure C# code that you can drop into any .NET project. + +## What You’ll Learn + +- How to **render webpage to PNG** using Aspose.HTML’s `HTMLDocument` class. +- The exact steps to **set image size rendering** so the output matches your layout requirements. +- Ways to **write image to file** safely, handling streams and file paths. +- Tips for troubleshooting common pitfalls like missing fonts or network timeouts. + +### Prerequisites + +- .NET 6.0 or later (the API works with .NET Framework as well, but .NET 6+ is recommended). +- A reference to the Aspose.HTML for .NET NuGet package (`Aspose.Html`). +- Basic familiarity with C# and async/await (optional but helpful). + +If you already have those, you’re ready to start converting HTML to image right away. + +## Step 1: Load the Web Page – The Foundation of Converting HTML to Image + +Before any rendering can happen, you need an `HTMLDocument` instance that represents the page you want to capture. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Why this matters:* The `HTMLDocument` parses the HTML, resolves CSS, and builds the DOM. If the document can’t load (e.g., network issue), the subsequent rendering will produce a blank image. Always verify the URL is reachable before moving on. + +## Step 2: Set Image Size Rendering – Controlling Width, Height, and Quality + +Aspose.HTML lets you fine‑tune the output dimensions with `ImageRenderingOptions`. This is where you **set image size rendering** to match your target layout. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Pro tip:* If you omit `Width` and `Height`, Aspose.HTML will use the page’s intrinsic size, which can be unpredictable for responsive designs. Specifying explicit dimensions ensures your **save HTML as PNG** output looks exactly how you expect. + +## Step 3: Write Image to File – Persisting the Rendered PNG + +Now that the document is ready and the rendering options are set, you can finally **write image to file**. Using a `FileStream` guarantees the file is created safely, even if the folder doesn’t exist yet. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +After this block runs, you’ll find `page.png` at the location you specified. You’ve just **rendered webpage to PNG** and written it to disk in a single, straightforward operation. + +### Expected Result + +Open `C:\Temp\page.png` with any image viewer. You should see a faithful snapshot of `https://example.com`, rendered at 1024 × 768 pixels with smooth edges thanks to antialiasing. If the page contains dynamic content (e.g., JavaScript‑generated elements), they’ll be captured as long as the DOM is fully loaded before rendering. + +## Step 4: Handling Edge Cases – Fonts, Authentication, and Large Pages + +While the basic flow works for most public sites, real‑world scenarios often throw curveballs: + +| Situation | What to Do | +|-----------|------------| +| **Custom fonts not loading** | Embed the font files locally and set `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Pages behind authentication** | Use `HTMLDocument` overload that accepts `HttpWebRequest` with cookies or tokens. | +| **Very tall pages** | Increase `Height` or enable `PageScaling` in `ImageRenderingOptions` to avoid truncation. | +| **Memory usage spikes** | Render in chunks using `RenderToImage` overload that accepts a `Rectangle` region. | + +Addressing these *write image to file* nuances ensures your `convert html to image` pipeline stays robust in production. + +## Step 5: Full Working Example – Copy‑Paste Ready + +Below is the entire program, ready to compile. It includes all the steps, error handling, and comments you need. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Run this program, and you’ll see the confirmation message in the console. The PNG file will be exactly what you’d expect when you **render webpage to PNG** manually in a browser and take a screenshot—only faster and fully automated. + +## Frequently Asked Questions + +**Q: Can I convert a local HTML file instead of a URL?** +Absolutely. Just replace the URL with a file path: `new HTMLDocument(@"C:\myPage.html")`. + +**Q: Do I need a license for Aspose.HTML?** +A free evaluation license works for development and testing. For production, purchase a license to remove the evaluation watermark. + +**Q: What if the page uses JavaScript to load content after the initial load?** +Aspose.HTML executes JavaScript synchronously during parsing, but long‑running scripts might need a manual delay. You can use `HTMLDocument.WaitForReadyState` before rendering. + +## Conclusion + +You now have a solid, end‑to‑end solution to **convert HTML to image** in C#. By following the steps above you can **save HTML as PNG**, precisely **set image size rendering**, and confidently **write image to file** on any Windows or Linux environment. + +From simple screenshots to automated report generation, this technique scales nicely. Next, try experimenting with other output formats like JPEG or BMP, or integrate the code into an ASP.NET Core API that returns the PNG directly to callers. The possibilities are practically endless. + +Happy coding, and may your rendered images always look pixel‑perfect! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/english/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..a22137b97 --- /dev/null +++ b/html/english/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-03-21 +description: Create PDF from HTML quickly using Aspose HTML. Learn to render HTML + to PDF, convert HTML to PDF, and how to use Aspose in a concise tutorial. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: en +og_description: Create PDF from HTML with Aspose in C#. This guide shows how to render + HTML to PDF, convert HTML to PDF, and how to use Aspose effectively. +og_title: Create PDF from HTML – Complete Aspose C# Tutorial +tags: +- Aspose +- C# +- PDF generation +title: Create PDF from HTML with Aspose – Step‑by‑Step C# Guide +url: /net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create PDF from HTML with Aspose – Step‑by‑Step C# Guide + +Ever needed to **create PDF from HTML** but weren’t sure which library would give you pixel‑perfect results? You’re not alone. Many developers stumble when they try to turn a web snippet into a printable document, only to end up with blurry text or broken layouts. + +The good news is that Aspose HTML makes the whole process painless. In this tutorial we’ll walk through the exact code you need to **render HTML to PDF**, explore why each setting matters, and show you how to **convert HTML to PDF** without any hidden tricks. By the end, you’ll know **how to use Aspose** for reliable PDF generation in any .NET project. + +## Prerequisites – What You’ll Need Before You Start + +- **.NET 6.0 or later** (the example works on .NET Framework 4.7+ as well) +- **Visual Studio 2022** or any IDE that supports C# +- **Aspose.HTML for .NET** NuGet package (free trial or licensed version) +- A basic understanding of C# syntax (no deep PDF knowledge required) + +If you have those, you’re ready to roll. Otherwise, grab the latest .NET SDK and install the NuGet package with: + +```bash +dotnet add package Aspose.HTML +``` + +That single line pulls in everything you need for **aspose html to pdf** conversion. + +--- + +## Step 1: Set Up Your Project to Create PDF from HTML + +The first thing you do is create a new console app (or integrate the code into an existing service). Here’s a minimal `Program.cs` skeleton: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** If you see `Aspise.Html.Rendering.Text` in older samples, replace it with `Aspose.Html.Rendering.Text`. The typo will cause a compile error. + +Having the correct namespaces ensures the compiler can locate the **TextOptions** class we’ll need later. + +## Step 2: Build the HTML Document (Render HTML to PDF) + +Now we create the source HTML. Aspose lets you pass a raw string, a file path, or even a URL. For this demo we’ll keep it simple: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Why pass a string? It avoids filesystem I/O, speeds up the conversion, and guarantees that the HTML you see in the code is exactly what gets rendered. If you prefer loading from a file, just replace the constructor argument with a file URI. + +## Step 3: Fine‑Tune Text Rendering (Convert HTML to PDF with Better Quality) + +Text rendering often determines whether your PDF looks crisp or fuzzy. Aspose offers a `TextOptions` class that lets you enable sub‑pixel hinting—essential for high‑DPI output. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Enabling `UseHinting` is especially useful when your source HTML contains custom fonts or small font sizes. Without it, you might notice jagged edges in the final PDF. + +## Step 4: Attach Text Options to PDF Rendering Configuration (How to Use Aspose) + +Next, we bind those text options to the PDF renderer. This is where **aspose html to pdf** really shines—everything from page size to compression can be tweaked. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +You can omit `PageSetup` if you’re fine with the default A4 size. The key takeaway is that the `TextOptions` object lives inside `PdfRenderingOptions`, and that’s how you tell Aspose *how* to render the text. + +## Step 5: Render the HTML and Save the PDF (Convert HTML to PDF) + +Finally, we stream the output to a file. Using a `using` block guarantees the file handle is closed properly, even if an exception occurs. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +When you run the program, you’ll find `output.pdf` next to the executable. Open it, and you should see a clean heading and paragraph—exactly as defined in the HTML string. + +### Expected Output + +![create pdf from html example output](https://example.com/images/pdf-output.png "create pdf from html example output") + +*The screenshot shows the generated PDF with the heading “Hello, Aspose!” rendered sharply thanks to text hinting.* + +--- + +## Common Questions & Edge Cases + +### 1. What if my HTML references external resources (images, CSS)? + +Aspose resolves relative URLs based on the document’s base URI. If you’re feeding a raw string, set the base URI manually: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Now any `` will be looked up relative to `C:/MyProject/`. + +### 2. How do I embed fonts that aren’t installed on the server? + +Add a ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Step 4: Configure Save Options to Use the Custom Storage + +`HtmlSaveOptions` lets us tell Aspose to pack everything into a ZIP file. The `OutputStorage` property (legacy) receives our `MyStorage` instance. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Note:** In Aspose HTML 23.9+ the property is named `OutputStorage` but marked obsolete. The modern alternative is `ZipOutputStorage`. The code below works with both because the interface is the same. + +### Step 5: Save the Document as a ZIP Archive + +Pick a target folder (or stream) and let Aspose do the heavy lifting. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +When the program finishes you’ll find `output.zip` containing: + +* `index.html` – the main document. +* Any embedded images, CSS files, or scripts (if your HTML referenced them). + +You can open the ZIP with any archive manager to verify the structure. + +--- + +## Verifying the Result (Optional) + +If you want to programmatically inspect the archive without extracting it to disk: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Typical output: + +``` +- index.html (452 bytes) +``` + +If you had images or CSS, they would appear as additional entries. This quick check confirms that **create html zip archive** worked as expected. + +--- + +## Common Questions & Edge Cases + +| Question | Answer | +|----------|--------| +| **What if I need to write the ZIP directly to a response stream?** | Return the `MemoryStream` you get from `MyStorage` after `document.Save`. Cast it to a `byte[]` and write it to `HttpResponse.Body`. | +| **My HTML references external URLs—will they be downloaded?** | No. Aspose only packs resources that are *embedded* (e.g., `` or local files). For remote assets you must download them first and adjust the markup. | +| **The `OutputStorage` property is marked obsolete—should I ignore it?** | It still works, but the newer `ZipOutputStorage` offers the same API with a different name. Replace `OutputStorage` with `ZipOutputStorage` if you want a warning‑free build. | +| **Can I encrypt the ZIP?** | Yes. After saving, open the file with `System.IO.Compression.ZipArchive` and set a password using third‑party libraries like `SharpZipLib`. Aspose itself doesn’t provide encryption. | + +--- + +## Full Working Example (Copy‑Paste) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Run the program, open `output.zip`, and you’ll see a single `index.html` file that renders the “Hello from ZIP!” heading when opened in a browser. + +--- + +## Conclusion + +You now know **how to save HTML as ZIP** in C# using a **custom storage** class, how to **export HTML to ZIP**, and how to **create an HTML zip archive** that’s ready for distribution. The pattern is flexible—swap `MemoryStream` for a cloud stream, add encryption, or integrate it into a web API that returns the ZIP on demand. + +Ready for the next step? Try feeding a full‑blown web page with images and styles, or hook the storage into Azure Blob Storage to bypass the local file system entirely. The sky’s the limit when you combine Aspose.HTML’s ZIP capabilities with your own storage logic. + +Happy coding, and may your archives always be tidy! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/french/net/generate-jpg-and-png-images/_index.md b/html/french/net/generate-jpg-and-png-images/_index.md index 59ca2dad1..0659e6522 100644 --- a/html/french/net/generate-jpg-and-png-images/_index.md +++ b/html/french/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Apprenez à utiliser Aspose.HTML pour .NET pour manipuler des documents HTML, co Apprenez à activer l'anticrénelage pour améliorer la qualité des images PNG/JPG générées à partir de documents DOCX avec Aspose.HTML. ### [Convertir docx en png – créer une archive zip tutoriel C#](./convert-docx-to-png-create-zip-archive-c-tutorial/) Apprenez à convertir des fichiers DOCX en images PNG et à les compresser dans une archive ZIP avec C#. +### [Convertir HTML en PNG – Guide complet C# avec export ZIP](./convert-html-to-png-full-c-guide-with-zip-export/) +Apprenez à convertir du HTML en images PNG et à les archiver dans un fichier ZIP à l'aide de C#. ## Conclusion diff --git a/html/french/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/french/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..77fe355a9 --- /dev/null +++ b/html/french/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Convertir le HTML en PNG et rendre le HTML sous forme d’image tout en + enregistrant le HTML dans un ZIP. Apprenez à appliquer le style de police au HTML + et à ajouter du gras aux éléments 

en quelques étapes seulement. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: fr +og_description: Convertir HTML en PNG rapidement. Ce guide montre comment rendre HTML + en image, enregistrer HTML en ZIP, appliquer le style de police HTML et ajouter + du gras aux éléments p. +og_title: Convertir le HTML en PNG – Tutoriel complet C# +tags: +- Aspose +- C# +title: Convertir le HTML en PNG – Guide complet C# avec exportation ZIP +url: /fr/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir HTML en PNG – Guide complet C# avec export ZIP + +Vous avez déjà eu besoin de **convertir HTML en PNG** mais vous ne saviez pas quelle bibliothèque pouvait le faire sans recourir à un navigateur sans tête ? Vous n'êtes pas seul. Dans de nombreux projets—vignettes d'e‑mail, aperçus de documentation ou images d'aperçu rapide—transformer une page web en image statique est un besoin réel. + +Bonne nouvelle ? Avec Aspose.HTML vous pouvez **render HTML as image**, ajuster le balisage à la volée, et même **save HTML to ZIP** pour une distribution ultérieure. Dans ce tutoriel, nous parcourrons un exemple complet et exécutable qui **applies font style HTML**, spécifiquement **add bold to p** éléments, avant de produire un fichier PNG. À la fin, vous disposerez d’une seule classe C# qui fait tout, du chargement d’une page à l’archivage de ses ressources. + +## Ce dont vous avez besoin + +- .NET 6.0 ou version ultérieure (l'API fonctionne également sur .NET Core) +- Aspose.HTML pour .NET 6+ (package NuGet `Aspose.Html`) +- Une compréhension de base de la syntaxe C# (aucun concept avancé requis) + +C’est tout. Aucun navigateur externe, pas de phantomjs, juste du code géré pur. + +## Étape 1 – Charger le document HTML + +Tout d'abord, nous chargeons le fichier source (ou l'URL) dans un objet `HTMLDocument`. Cette étape constitue la base à la fois pour **render html as image** et **save html to zip** ultérieurement. + +```csharp +using Aspose.Html; +using System.IO; + +///

+/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Pourquoi c’est important :* La classe `HTMLDocument` analyse le balisage, construit un DOM et résout les ressources liées (CSS, images, polices). Sans un objet document approprié, vous ne pouvez pas manipuler les styles ni rendre quoi que ce soit. + +## Étape 2 – Appliquer le style de police HTML (Ajouter du gras aux p) + +Nous allons maintenant **apply font style HTML** en parcourant chaque élément `

` et en définissant son `font-weight` à bold. C’est la façon programmatique d'**add bold to p** les balises sans toucher au fichier original. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Astuce :* Si vous avez seulement besoin de mettre en gras un sous‑ensemble, modifiez le sélecteur pour quelque chose de plus spécifique, par ex., `"p.intro"`. + +## Étape 3 – Rendre le HTML en image (Convertir HTML en PNG) + +Avec le DOM prêt, nous configurons `ImageRenderingOptions` et appelons `RenderToImage`. C’est ici que la magie du **convert html to png** se produit. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Pourquoi les options sont importantes :* Définir une largeur/hauteur fixe empêche la sortie d’être trop grande, tandis que l'anticrénelage offre un rendu visuel plus lisse. Vous pouvez également changer `options` en `ImageFormat.Jpeg` si vous préférez une taille de fichier plus petite. + +## Étape 4 – Enregistrer le HTML en ZIP (Regrouper les ressources) + +Souvent, vous devez livrer le HTML original avec son CSS, ses images et ses polices. `ZipArchiveSaveOptions` d’Aspose.HTML fait exactement cela. Nous intégrons également un `ResourceHandler` personnalisé afin que toutes les ressources externes soient écrites dans le même dossier que l’archive. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Cas particulier :* Si votre HTML référence des images distantes nécessitant une authentification, le gestionnaire par défaut échouera. Dans ce scénario, vous pouvez étendre `MyResourceHandler` pour injecter des en‑têtes HTTP. + +## Étape 5 – Assembler le tout dans une classe convertisseur unique + +Ci-dessous se trouve la classe complète, prête à l’exécution, qui regroupe toutes les étapes précédentes. Vous pouvez la copier‑coller dans une application console, appeler `Convert`, et voir les fichiers apparaître. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Résultat attendu + +Après avoir exécuté l’extrait ci‑dessus, vous trouverez deux fichiers dans `outputDirectory` : + +| Fichier | Description | +|------|-------------| +| `page.png` | Un rendu PNG 1200 × 800 du HTML source, avec chaque paragraphe affiché en **bold**. | +| `archive.zip` | Un bundle ZIP contenant le `input.html` original, son CSS, ses images et toutes les web‑fonts – parfait pour la distribution hors ligne. | + +Vous pouvez ouvrir `page.png` avec n’importe quel visualiseur d’image pour vérifier que le style gras a été appliqué, et extraire `archive.zip` pour voir le HTML intact avec ses ressources. + +## Questions fréquentes & pièges + +- **Et si le HTML contient du JavaScript ?** + Aspose.HTML **n’exécute pas** les scripts lors du rendu, donc le contenu dynamique n’apparaîtra pas. Pour des pages entièrement rendues, vous auriez besoin d’un navigateur sans tête, mais pour des modèles statiques cette approche est plus rapide et plus légère. + +- **Puis‑je changer le format de sortie en JPEG ou BMP ?** + Oui—modifiez la propriété `ImageFormat` de `ImageRenderingOptions`, par ex., `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Dois‑je libérer manuellement le `HTMLDocument` ?** + La classe implémente `IDisposable`. Dans un service de longue durée, encapsulez‑la dans un bloc `using` ou appelez `document.Dispose()` une fois terminé. + +- **Comment fonctionne le `MyResourceHandler` personnalisé ?** + Il reçoit chaque ressource externe (CSS, images, polices) et l’écrit dans le dossier que vous spécifiez. Cela garantit que le ZIP contient une copie fidèle de tout ce que le HTML référence. + +## Conclusion + +Vous disposez maintenant d’une solution compacte, prête pour la production, qui **convert html to png**, **render html as image**, **save html to zip**, **apply font style html**, et **add bold to p**—le tout en quelques lignes C#. Le code est autonome, fonctionne avec .NET 6+, et peut être intégré à n’importe quel service backend nécessitant des instantanés visuels rapides du contenu web. + +Prêt pour l’étape suivante ? Essayez de modifier la taille de rendu, expérimentez d’autres propriétés CSS (comme `font-family` ou `color`), ou intégrez ce convertisseur dans un point de terminaison ASP.NET Core qui renvoie le PNG à la demande. Les possibilités sont infinies, et avec Aspose.HTML vous évitez les dépendances de navigateurs lourds. + +Si vous avez rencontré des problèmes ou avez des idées d’extensions, laissez un commentaire ci‑dessous. Bon codage ! + +![convert html to png example](example.png "convert html to png example") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/french/net/html-document-manipulation/_index.md b/html/french/net/html-document-manipulation/_index.md index 134ab9f67..7a748bba3 100644 --- a/html/french/net/html-document-manipulation/_index.md +++ b/html/french/net/html-document-manipulation/_index.md @@ -59,6 +59,8 @@ Libérez le potentiel d'Aspose.HTML pour .NET avec notre guide complet. Découvr Découvrez comment exploiter la puissance d'Aspose.HTML pour .NET. Boostez votre développement Web grâce à la manipulation et au rendu HTML. ### [Créer un document en .NET avec Aspose.HTML](./creating-a-document/) Exploitez la puissance d'Aspose.HTML pour .NET. Apprenez à créer, manipuler et optimiser facilement des documents HTML et SVG. Découvrez des exemples étape par étape et des FAQ. +### [Créer un document HTML en C# – Guide étape par étape](./create-html-document-c-step-by-step-guide/) +Apprenez à créer un document HTML en C# avec Aspose.HTML grâce à un guide détaillé étape par étape. ### [Modification d'un document dans .NET avec Aspose.HTML](./editing-a-document/) Créez du contenu Web captivant avec Aspose.HTML pour .NET. Apprenez à manipuler HTML, CSS et bien plus encore. ### [Enregistrer un document dans .NET avec Aspose.HTML](./saving-a-document/) diff --git a/html/french/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/french/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..ce3ecf407 --- /dev/null +++ b/html/french/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: Créer un document HTML en C# et apprendre comment obtenir un élément + par son id, localiser un élément par son id, modifier le style d’un élément HTML + et ajouter du gras et de l’italique à l’aide d’Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: fr +og_description: Créez un document HTML en C# et apprenez immédiatement à obtenir un + élément par son id, le localiser, modifier le style d’un élément HTML et ajouter + du gras et de l’italique avec des exemples de code clairs. +og_title: Créer un document HTML C# – Guide complet de programmation +tags: +- Aspose.Html +- C# +- DOM manipulation +title: Créer un document HTML C# – Guide étape par étape +url: /fr/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer un document HTML C# – Guide étape par étape + +Vous avez déjà eu besoin de **créer un document HTML C#** à partir de zéro puis d’ajuster l’apparence d’un seul paragraphe ? Vous n’êtes pas le seul. Dans de nombreux projets d’automatisation web, vous générez un fichier HTML, recherchez une balise par son ID, puis appliquez un style—souvent gras + italique—sans jamais toucher à un navigateur. + +Dans ce tutoriel, nous allons passer en revue exactement cela : nous créerons un document HTML en C#, **get element by id**, **locate element by id**, **change HTML element style**, et enfin **add bold italic** en utilisant la bibliothèque Aspose.Html. À la fin, vous disposerez d’un extrait entièrement exécutable que vous pourrez insérer dans n’importe quel projet .NET. + +## Ce dont vous avez besoin + +- .NET 6 ou ultérieur (le code fonctionne également sur .NET Framework 4.7+) +- Visual Studio 2022 (ou tout éditeur de votre choix) +- Le package NuGet **Aspose.Html** (`Install-Package Aspose.Html`) + +C’est tout—pas de fichiers HTML supplémentaires, pas de serveur web, juste quelques lignes de C#. + +## Créer un document HTML C# – Initialiser le document + +Première chose à faire : vous avez besoin d’un objet `HTMLDocument` actif avec lequel le moteur Aspose.Html peut travailler. Considérez cela comme l’ouverture d’un nouveau cahier où vous écrirez votre balisage. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Pourquoi c’est important :** En passant la chaîne brute à `HTMLDocument`, vous évitez de gérer les entrées/sorties de fichiers et gardez tout en mémoire—idéal pour les tests unitaires ou la génération à la volée. + +## Get Element by ID – Trouver le paragraphe + +Maintenant que le document existe, nous devons **get element by id**. L’API DOM nous fournit `GetElementById`, qui renvoie une référence `IElement` ou `null` si l’ID n’est pas présent. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Astuce :** Même si notre balisage est minuscule, ajouter une vérification de null évite bien des maux de tête lorsque la même logique est réutilisée sur des pages plus grandes et dynamiques. + +## Locate Element by ID – Une approche alternative + +Parfois, vous avez déjà une référence à la racine du document et préférez une recherche de type requête. Utiliser les sélecteurs CSS (`QuerySelector`) est une autre façon de **locate element by id** : + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **Quand utiliser l’un ou l’autre ?** `GetElementById` est légèrement plus rapide car il s’agit d’une recherche directe dans un hachage. `QuerySelector` brille lorsque vous avez besoin de sélecteurs complexes (par ex., `div > p.highlight`). + +## Change HTML Element Style – Ajouter du gras italique + +Avec l’élément en main, l’étape suivante consiste à **change HTML element style**. Aspose.Html expose un objet `Style` où vous pouvez ajuster les propriétés CSS ou utiliser l’énumération pratique `WebFontStyle` pour appliquer plusieurs attributs de police en même temps. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Cette ligne unique définit le `font-weight` de l’élément à `bold` et le `font-style` à `italic`. En interne, Aspose.Html traduit l’énumération en la chaîne CSS appropriée. + +### Exemple complet fonctionnel + +Assembler toutes les pièces donne un programme compact et autonome que vous pouvez compiler et exécuter immédiatement : + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Sortie attendue** + +``` +Rendered HTML: +

Hello world

+``` + +La balise `

` possède maintenant un attribut `style` en ligne qui rend le texte à la fois gras et italique—exactement ce que nous voulions. + +## Cas limites & pièges courants + +| Situation | À surveiller | Comment gérer | +|-----------|--------------|---------------| +| **L'ID n'existe pas** | `GetElementById` renvoie `null`. | Lancer une exception ou revenir à un élément par défaut. | +| **Plusieurs éléments partagent le même ID** | La spécification HTML indique que les ID doivent être uniques, mais les pages réelles enfreignent parfois la règle. | `GetElementById` renvoie la première correspondance ; envisagez d’utiliser `QuerySelectorAll` si vous devez gérer les doublons. | +| **Conflits de style** | Les styles en ligne existants peuvent être écrasés. | Ajoutez au objet `Style` au lieu de définir toute la chaîne `style` : `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Rendu dans un navigateur** | Certains navigateurs ignorent `WebFontStyle` si l’élément possède déjà une classe CSS avec une spécificité plus élevée. | Utilisez `!important` via `paragraph.Style.SetProperty("font-weight", "bold", "important");` si nécessaire. | + +## Astuces pro pour les projets réels + +- **Mettez en cache le document** si vous traitez de nombreux éléments ; créer un nouveau `HTMLDocument` pour chaque petit extrait peut nuire aux performances. +- **Combinez les changements de style** en une seule transaction `Style` pour éviter plusieurs reflows du DOM. +- **Exploitez le moteur de rendu d’Aspose.Html** pour exporter le document final en PDF ou image—idéal pour les outils de reporting. + +## Confirmation visuelle (optionnel) + +Si vous préférez voir le résultat dans un navigateur, vous pouvez enregistrer la chaîne rendue dans un fichier `.html` : + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Ouvrez `output.html` et vous verrez **Hello world** affiché en gras + italique. + +![Exemple de création de document HTML C# montrant un paragraphe gras italique](/images/create-html-document-csharp.png "Création de document HTML C# – rendu") + +*Texte alternatif : Création de document HTML C# – rendu avec texte gras italique.* + +## Conclusion + +Nous venons de **créer un document HTML C#**, **obtenir un élément par id**, **localiser un élément par id**, **modifier le style d’un élément HTML**, et enfin **ajouter du gras italique**—tout cela avec quelques lignes grâce à Aspose.Html. L’approche est simple, fonctionne dans n’importe quel environnement .NET, et s’adapte aux manipulations DOM plus importantes. + +Prêt pour l’étape suivante ? Essayez de remplacer le `WebFontStyle` par d’autres énumérations comme `Underline` ou combinez plusieurs styles manuellement. Ou expérimentez le chargement d’un fichier HTML externe et appliquez la même technique à des centaines d’éléments. Le ciel est la limite, et vous avez maintenant une base solide sur laquelle construire. + +Bon codage! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/french/net/html-extensions-and-conversions/_index.md b/html/french/net/html-extensions-and-conversions/_index.md index f4e02735c..38acd9699 100644 --- a/html/french/net/html-extensions-and-conversions/_index.md +++ b/html/french/net/html-extensions-and-conversions/_index.md @@ -41,6 +41,8 @@ Aspose.HTML pour .NET n'est pas seulement une bibliothèque ; c'est un outil ré Convertissez facilement du HTML en PDF avec Aspose.HTML pour .NET. Suivez notre guide étape par étape et exploitez la puissance de la conversion HTML en PDF. ### [Créer un PDF à partir de HTML – Guide étape par étape en C#](./create-pdf-from-html-c-step-by-step-guide/) Apprenez à créer un PDF à partir de HTML en C# avec Aspose.HTML, guide complet pas à pas. +### [Créer un PDF à partir de HTML avec Aspose – Guide complet C#](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Apprenez à créer un PDF à partir de HTML avec Aspose, guide complet pas à pas en C#. ### [Créer un document HTML avec du texte stylisé et l'exporter en PDF – Guide complet](./create-html-document-with-styled-text-and-export-to-pdf-full/) Apprenez à créer un document HTML avec du texte formaté et à le convertir en PDF à l'aide d'Aspose.HTML pour .NET. Convertisez facilement du HTML en PDF avec Aspose.HTML pour .NET. Suivez notre guide étape par étape et exploitez la puissance de la conversion HTML en PDF. @@ -68,12 +70,18 @@ Découvrez comment utiliser Aspose.HTML pour .NET pour manipuler et convertir de Découvrez comment convertir du HTML en TIFF avec Aspose.HTML pour .NET. Suivez notre guide étape par étape pour une optimisation efficace du contenu Web. ### [Convertir HTML en XPS dans .NET avec Aspose.HTML](./convert-html-to-xps/) Découvrez la puissance d'Aspose.HTML pour .NET : convertissez facilement du HTML en XPS. Prérequis, guide étape par étape et FAQ inclus. +### [Convertir HTML en image en C# – Guide complet](./convert-html-to-image-in-c-complete-guide/) +Apprenez à convertir du HTML en image en C# avec Aspose.HTML, guide complet pas à pas. ### [Comment zipper du HTML en C# – Enregistrer le HTML dans un zip](./how-to-zip-html-in-c-save-html-to-zip/) Apprenez à compresser du HTML en un fichier zip avec C# grâce à notre guide détaillé. ### [Enregistrer le HTML en ZIP – Tutoriel complet C#](./save-html-as-zip-complete-c-tutorial/) 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 en C# – Guide complet avec stockage personnalisé](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Apprenez à enregistrer un document HTML dans un fichier ZIP en C# avec Aspose.HTML, incluant le stockage personnalisé. +### [Comment zipper du HTML avec Aspose.HTML – Guide complet](./how-to-zip-html-with-aspose-html-complete-guide/) +Apprenez à compresser du HTML dans un fichier ZIP avec Aspose.HTML grâce à notre guide complet étape par étape. ## Conclusion diff --git a/html/french/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/french/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..783adff78 --- /dev/null +++ b/html/french/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Convertir du HTML en image avec Aspose.HTML en C#. Apprenez comment enregistrer + le HTML au format PNG, définir la taille de rendu de l'image et écrire l'image dans + un fichier en quelques étapes seulement. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: fr +og_description: Convertissez rapidement du HTML en image. Ce guide montre comment + enregistrer le HTML au format PNG, définir la taille du rendu de l'image et écrire + l'image dans un fichier avec Aspose.HTML. +og_title: Convertir le HTML en image en C# – Guide étape par étape +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Convertir le HTML en image en C# – Guide complet +url: /fr/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir HTML en image en C# – Guide complet + +Vous avez déjà eu besoin de **convertir HTML en image** pour une vignette de tableau de bord, un aperçu d’e‑mail ou un rapport PDF ? C’est un scénario qui apparaît plus souvent que vous ne le pensez, surtout lorsque vous devez intégrer du contenu web dynamique ailleurs. + +Bonne nouvelle ? Avec Aspose.HTML, vous pouvez **convertir HTML en image** en quelques lignes seulement, et vous apprendrez également à *enregistrer HTML en PNG*, à contrôler les dimensions de sortie, et à *écrire l’image dans un fichier* sans effort. + +Dans ce tutoriel, nous passerons en revue tout ce qu’il faut savoir : du chargement d’une page distante à l’ajustement de la taille de rendu, jusqu’à la persistance du résultat sous forme de fichier PNG sur le disque. Aucun outil externe, aucune astuce en ligne de commande—juste du code C# pur que vous pouvez intégrer à n’importe quel projet .NET. + +## Ce que vous allez apprendre + +- Comment **render webpage to PNG** avec la classe `HTMLDocument` d’Aspose.HTML. +- Les étapes exactes pour **set image size rendering** afin que la sortie corresponde à vos exigences de mise en page. +- Les méthodes pour **write image to file** en toute sécurité, en gérant les flux et les chemins de fichiers. +- Des astuces pour dépanner les problèmes courants comme les polices manquantes ou les délais d’attente réseau. + +### Prérequis + +- .NET 6.0 ou supérieur (l’API fonctionne également avec .NET Framework, mais .NET 6+ est recommandé). +- Une référence au package NuGet Aspose.HTML for .NET (`Aspose.Html`). +- Une connaissance de base du C# et de async/await (optionnel mais utile). + +Si vous avez déjà tout cela, vous êtes prêt à commencer à convertir HTML en image immédiatement. + +## Étape 1 : Charger la page web – La base de la conversion HTML en image + +Avant tout rendu, vous avez besoin d’une instance `HTMLDocument` qui représente la page que vous souhaitez capturer. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Pourquoi c’est important :* `HTMLDocument` analyse le HTML, résout le CSS et construit le DOM. Si le document ne peut pas être chargé (p. ex. problème réseau), le rendu suivant produira une image blanche. Vérifiez toujours que l’URL est accessible avant de continuer. + +## Étape 2 : Définir le rendu de la taille d’image – Contrôler largeur, hauteur et qualité + +Aspose.HTML vous permet d’ajuster finement les dimensions de sortie avec `ImageRenderingOptions`. C’est ici que vous **set image size rendering** pour correspondre à votre mise en page cible. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Astuce :* Si vous omettez `Width` et `Height`, Aspose.HTML utilisera la taille intrinsèque de la page, ce qui peut être imprévisible pour les designs responsives. Spécifier des dimensions explicites garantit que votre sortie **save HTML as PNG** ressemble exactement à ce que vous attendez. + +## Étape 3 : Écrire l’image dans un fichier – Persister le PNG rendu + +Une fois le document prêt et les options de rendu définies, vous pouvez enfin **write image to file**. L’utilisation d’un `FileStream` assure que le fichier est créé en toute sécurité, même si le dossier n’existe pas encore. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +Après l’exécution de ce bloc, vous trouverez `page.png` à l’emplacement que vous avez indiqué. Vous avez ainsi **rendered webpage to PNG** et l’avez écrit sur le disque en une seule opération simple. + +### Résultat attendu + +Ouvrez `C:\Temp\page.png` avec n’importe quel visualiseur d’images. Vous devriez voir un instantané fidèle de `https://example.com`, rendu à 1024 × 768 pixels avec des bords lisses grâce à l’antialiasing. Si la page contient du contenu dynamique (p. ex. éléments générés par JavaScript), ils seront capturés tant que le DOM est entièrement chargé avant le rendu. + +## Étape 4 : Gestion des cas particuliers – Polices, authentification et pages volumineuses + +Si le flux de base fonctionne pour la plupart des sites publics, les scénarios réels introduisent souvent des complications : + +| Situation | Que faire | +|-----------|-----------| +| **Polices personnalisées qui ne se chargent pas** | Intégrez les fichiers de police localement et ajoutez `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Pages protégées par authentification** | Utilisez la surcharge de `HTMLDocument` qui accepte un `HttpWebRequest` avec cookies ou jetons. | +| **Pages très longues** | Augmentez `Height` ou activez `PageScaling` dans `ImageRenderingOptions` pour éviter la troncature. | +| **Pics de consommation mémoire** | Rendre par morceaux en utilisant la surcharge `RenderToImage` qui accepte une région `Rectangle`. | + +Prendre en compte ces nuances de *write image to file* garantit que votre pipeline **convert html to image** reste robuste en production. + +## Étape 5 : Exemple complet – Prêt à copier‑coller + +Voici le programme complet, prêt à être compilé. Il inclut toutes les étapes, la gestion des erreurs et les commentaires nécessaires. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Exécutez ce programme, et vous verrez le message de confirmation dans la console. Le fichier PNG sera exactement ce que vous attendriez en **rendering webpage to PNG** manuellement dans un navigateur puis en prenant une capture d’écran—seulement plus rapide et entièrement automatisé. + +## Foire aux questions + +**Q : Puis‑je convertir un fichier HTML local au lieu d’une URL ?** +Absolument. Remplacez simplement l’URL par un chemin de fichier : `new HTMLDocument(@"C:\myPage.html")`. + +**Q : Ai‑je besoin d’une licence pour Aspose.HTML ?** +Une licence d’évaluation gratuite suffit pour le développement et les tests. En production, achetez une licence pour supprimer le filigrane d’évaluation. + +**Q : Et si la page utilise JavaScript pour charger du contenu après le chargement initial ?** +Aspose.HTML exécute le JavaScript de façon synchrone pendant l’analyse, mais les scripts longs peuvent nécessiter un délai manuel. Vous pouvez appeler `HTMLDocument.WaitForReadyState` avant le rendu. + +## Conclusion + +Vous disposez maintenant d’une solution complète, de bout en bout, pour **convertir HTML en image** en C#. En suivant les étapes ci‑dessus, vous pouvez **save HTML as PNG**, **set image size rendering** avec précision, et **write image to file** en toute confiance sur n’importe quel environnement Windows ou Linux. + +Des captures d’écran simples à la génération automatisée de rapports, cette technique s’adapte facilement. Ensuite, essayez d’expérimenter avec d’autres formats de sortie comme JPEG ou BMP, ou intégrez le code dans une API ASP.NET Core qui renvoie directement le PNG aux appelants. Les possibilités sont pratiquement infinies. + +Bon codage, et que vos images rendues soient toujours pixel‑perfect ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/french/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/french/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..02e7a0e37 --- /dev/null +++ b/html/french/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-03-21 +description: Créez un PDF à partir de HTML rapidement avec Aspose HTML. Apprenez à + rendre le HTML en PDF, à convertir le HTML en PDF et à utiliser Aspose dans un tutoriel + concis. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: fr +og_description: Créer un PDF à partir de HTML avec Aspose en C#. Ce guide montre comment + rendre le HTML en PDF, convertir le HTML en PDF et comment utiliser Aspose efficacement. +og_title: Créer un PDF à partir de HTML – Tutoriel complet Aspose C# +tags: +- Aspose +- C# +- PDF generation +title: Créer un PDF à partir de HTML avec Aspose – Guide C# étape par étape +url: /fr/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer un PDF à partir de HTML avec Aspose – Guide étape par étape C# + +Vous avez déjà eu besoin de **créer un PDF à partir de HTML** mais vous n'étiez pas sûr de la bibliothèque qui vous offrirait des résultats pixel‑parfait ? Vous n'êtes pas seul. De nombreux développeurs rencontrent des difficultés lorsqu'ils essaient de transformer un extrait web en document imprimable, pour finir avec du texte flou ou des mises en page cassées. + +La bonne nouvelle, c'est qu'Aspose HTML rend tout le processus indolore. Dans ce tutoriel, nous passerons en revue le code exact dont vous avez besoin pour **render HTML to PDF**, expliquerons pourquoi chaque paramètre est important, et vous montrerons comment **convert HTML to PDF** sans aucun tour de passe‑passe. À la fin, vous saurez **how to use Aspose** pour une génération fiable de PDF dans n'importe quel projet .NET. + +## Prérequis – Ce dont vous aurez besoin avant de commencer + +- **.NET 6.0 ou supérieur** (l'exemple fonctionne également sur .NET Framework 4.7+). +- **Visual Studio 2022** ou tout IDE supportant C#. +- **Aspose.HTML for .NET** package NuGet (version d'essai gratuite ou version sous licence). +- Une compréhension de base de la syntaxe C# (pas besoin de connaissances approfondies sur les PDF). + +Si vous avez tout cela, vous êtes prêt à démarrer. Sinon, récupérez le dernier SDK .NET et installez le package NuGet avec : + +```bash +dotnet add package Aspose.HTML +``` + +Cette ligne unique récupère tout ce dont vous avez besoin pour la conversion **aspose html to pdf**. + +--- + +## Étape 1 : Configurer votre projet pour créer un PDF à partir de HTML + +La première chose à faire est de créer une nouvelle application console (ou d'intégrer le code dans un service existant). Voici un squelette minimal `Program.cs` : + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Astuce :** Si vous voyez `Aspise.Html.Rendering.Text` dans d'anciens exemples, remplacez-le par `Aspose.Html.Rendering.Text`. La faute de frappe provoquera une erreur de compilation. + +Utiliser les bons espaces de noms garantit que le compilateur peut localiser la classe **TextOptions** dont nous aurons besoin plus tard. + +## Étape 2 : Construire le document HTML (Render HTML to PDF) + +Nous créons maintenant le HTML source. Aspose vous permet de passer une chaîne brute, un chemin de fichier ou même une URL. Pour cette démo, nous restons simples : + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Pourquoi passer une chaîne ? Cela évite les I/O du système de fichiers, accélère la conversion et garantit que le HTML que vous voyez dans le code est exactement celui qui sera rendu. Si vous préférez charger depuis un fichier, remplacez simplement l'argument du constructeur par une URI de fichier. + +## Étape 3 : Affiner le rendu du texte (Convert HTML to PDF with Better Quality) + +Le rendu du texte détermine souvent si votre PDF apparaît net ou flou. Aspose propose une classe `TextOptions` qui vous permet d'activer le sous‑pixel hinting—essentiel pour les sorties haute‑DPI. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Activer `UseHinting` est particulièrement utile lorsque votre HTML source contient des polices personnalisées ou des tailles de police petites. Sans cela, vous pourriez remarquer des bords dentelés dans le PDF final. + +## Étape 4 : Attacher les options de texte à la configuration du rendu PDF (How to Use Aspose) + +Ensuite, nous associons ces options de texte au moteur de rendu PDF. C'est ici que **aspose html to pdf** brille vraiment—tout, de la taille de page à la compression, peut être ajusté. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Vous pouvez omettre `PageSetup` si la taille A4 par défaut vous convient. L'essentiel est que l'objet `TextOptions` réside à l'intérieur de `PdfRenderingOptions`, et c'est ainsi que vous indiquez à Aspose *comment* rendre le texte. + +## Étape 5 : Rendre le HTML et enregistrer le PDF (Convert HTML to PDF) + +Enfin, nous diffusons la sortie vers un fichier. Utiliser un bloc `using` garantit que le handle du fichier est correctement fermé, même en cas d'exception. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Lorsque vous exécuterez le programme, vous trouverez `output.pdf` à côté de l'exécutable. Ouvrez‑le, et vous devriez voir un titre et un paragraphe propres—exactement comme définis dans la chaîne HTML. + +### Résultat attendu + +![create pdf from html example output](https://example.com/images/pdf-output.png "create pdf from html example output") + +*La capture d'écran montre le PDF généré avec le titre « Hello, Aspose! » rendu nettement grâce à l'optimisation du texte.* + +--- + +## Questions fréquentes et cas particuliers + +### 1. Et si mon HTML référence des ressources externes (images, CSS) ? + +Aspose résout les URL relatives en fonction de l'URI de base du document. Si vous alimentez une chaîne brute, définissez l'URI de base manuellement : + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Désormais, tout `` sera recherché relativement à `C:/MyProject/`. + +### 2. Comment incorporer des polices qui ne sont pas installées sur le serveur ? + +Ajoutez un bloc ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Étape 4 : Configurer les options d’enregistrement pour utiliser le stockage personnalisé + +`HtmlSaveOptions` nous permet d’indiquer à Aspose d’emballer tout dans un fichier ZIP. La propriété `OutputStorage` (héritée) reçoit notre instance `MyStorage`. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Remarque :** Dans Aspose HTML 23.9+ la propriété s’appelle `OutputStorage` mais est marquée comme obsolète. L’alternative moderne est `ZipOutputStorage`. Le code ci‑dessous fonctionne avec les deux car l’interface est identique. + +### Étape 5 : Enregistrer le document en tant qu’archive ZIP + +Choisissez un dossier cible (ou un flux) et laissez Aspose faire le travail lourd. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Lorsque le programme se termine, vous trouverez `output.zip` contenant : + +* `index.html` – le document principal. +* Toutes les images, fichiers CSS ou scripts incorporés (si votre HTML les référence). + +Vous pouvez ouvrir le ZIP avec n’importe quel gestionnaire d’archives pour vérifier la structure. + +--- + +## Vérification du résultat (optionnel) + +Si vous souhaitez inspecter le contenu de l’archive de façon programmatique sans l’extraire sur le disque : + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Sortie typique : + +``` +- index.html (452 bytes) +``` + +Si vous aviez des images ou du CSS, elles apparaîtraient comme des entrées supplémentaires. Cette vérification rapide confirme que **create html zip archive** a fonctionné comme prévu. + +--- + +## Questions fréquentes et cas particuliers + +| Question | Réponse | +|----------|--------| +| **Et si je dois écrire le ZIP directement dans un flux de réponse ?** | Retournez le `MemoryStream` obtenu depuis `MyStorage` après `document.Save`. Convertissez‑le en `byte[]` et écrivez‑le dans `HttpResponse.Body`. | +| **Mon HTML référence des URL externes—seront‑elles téléchargées ?** | Non. Aspose ne regroupe que les ressources *intégrées* (ex. `` ou fichiers locaux). Pour les actifs distants, vous devez les télécharger au préalable et ajuster le markup. | +| **La propriété `OutputStorage` est marquée comme obsolète—dois‑je l’ignorer ?** | Elle fonctionne toujours, mais le nouveau `ZipOutputStorage` offre la même API sous un nom différent. Remplacez `OutputStorage` par `ZipOutputStorage` si vous voulez une compilation sans avertissements. | +| **Puis‑je chiffrer le ZIP ?** | Oui. Après l’enregistrement, ouvrez le fichier avec `System.IO.Compression.ZipArchive` et appliquez un mot de passe via des bibliothèques tierces comme `SharpZipLib`. Aspose ne fournit pas de chiffrement natif. | + +--- + +## Exemple complet (copier‑coller) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Exécutez le programme, ouvrez `output.zip`, et vous verrez un seul fichier `index.html` qui affiche le titre « Hello from ZIP! » lorsqu’il est ouvert dans un navigateur. + +--- + +## Conclusion + +Vous savez maintenant **comment enregistrer du HTML en ZIP** en C# en utilisant une **classe de stockage personnalisée**, comment **exporter du HTML vers un ZIP**, et comment **créer une archive HTML zip** prête à être distribuée. Le modèle est flexible — remplacez `MemoryStream` par un flux cloud, ajoutez du chiffrement, ou intégrez‑le dans une API web qui renvoie le ZIP à la demande. + +Prêt pour l’étape suivante ? Essayez avec une page web complète contenant images et styles, ou connectez le stockage à Azure Blob Storage pour éviter complètement le système de fichiers local. Le ciel est la limite lorsque vous combinez les capacités ZIP d’Aspose.HTML avec votre propre logique de stockage. + +Bon codage, et que vos archives restent toujours bien rangées ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/german/net/generate-jpg-and-png-images/_index.md b/html/german/net/generate-jpg-and-png-images/_index.md index 8c24c4537..a993d4494 100644 --- a/html/german/net/generate-jpg-and-png-images/_index.md +++ b/html/german/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML-Dokumente bearbeiten, HTML Erfahren Sie, wie Sie beim Konvertieren von DOCX-Dokumenten in PNG oder JPG Antialiasing aktivieren, um hochwertige Bilder zu erhalten. ### [DOCX in PNG konvertieren – ZIP-Archiv erstellen C#‑Tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Erfahren Sie, wie Sie DOCX‑Dateien in PNG‑Bilder umwandeln und diese in ein ZIP‑Archiv packen – Schritt‑für‑Schritt‑Anleitung in C#. +### [HTML in PNG konvertieren – Vollständiger C#‑Leitfaden mit ZIP‑Export](./convert-html-to-png-full-c-guide-with-zip-export/) +Erfahren Sie, wie Sie HTML in PNG-Bilder umwandeln und die Ergebnisse in ein ZIP-Archiv exportieren – komplette C#‑Anleitung. ## Abschluss diff --git a/html/german/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/german/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..5b11d6dd8 --- /dev/null +++ b/html/german/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Konvertiere HTML zu PNG und rendere HTML als Bild, während du HTML in + ein ZIP‑Archiv speicherst. Lerne, Schriftstile in HTML anzuwenden und füge p‑Elementen + fett hinzu – in nur wenigen Schritten. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: de +og_description: HTML schnell in PNG konvertieren. Diese Anleitung zeigt, wie man HTML + als Bild rendert, HTML in ein ZIP speichert, Schriftstile auf HTML anwendet und + p‑Elemente fett formatiert. +og_title: HTML in PNG konvertieren – Vollständiges C#‑Tutorial +tags: +- Aspose +- C# +title: HTML in PNG konvertieren – Vollständiger C#‑Leitfaden mit ZIP‑Export +url: /de/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML zu PNG konvertieren – Vollständige C#‑Anleitung mit ZIP‑Export + +Haben Sie schon einmal **HTML zu PNG konvertieren** müssen, waren sich aber nicht sicher, welche Bibliothek das ohne einen Headless‑Browser erledigen kann? Sie sind nicht allein. In vielen Projekten – E‑Mail‑Thumbnails, Dokumentations‑Vorschauen oder Quick‑Look‑Bilder – ist das Umwandeln einer Webseite in ein statisches Bild ein echtes Anwendungsproblem. + +Die gute Nachricht? Mit Aspose.HTML können Sie **HTML als Bild rendern**, das Markup zur Laufzeit anpassen und sogar **HTML in ZIP speichern** für die spätere Verteilung. In diesem Tutorial gehen wir Schritt für Schritt durch ein vollständiges, ausführbares Beispiel, das **Font‑Style‑HTML anwendet**, konkret **fett zu p‑Elementen hinzufügt**, bevor ein PNG‑File erzeugt wird. Am Ende haben Sie eine einzelne C#‑Klasse, die alles von Laden einer Seite bis zum Archivieren ihrer Ressourcen erledigt. + +## Was Sie benötigen + +- .NET 6.0 oder höher (die API funktioniert auch unter .NET Core) +- Aspose.HTML für .NET 6+ (NuGet‑Paket `Aspose.Html`) +- Grundlegendes Verständnis von C#‑Syntax (keine fortgeschrittenen Konzepte nötig) + +Das war’s. Keine externen Browser, kein phantomjs, nur reiner Managed‑Code. + +## Schritt 1 – HTML‑Dokument laden + +Zuerst bringen wir die Quelldatei (oder URL) in ein `HTMLDocument`‑Objekt. Dieser Schritt ist die Grundlage sowohl für **render html as image** als auch für **save html to zip** später. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Warum das wichtig ist:* Die Klasse `HTMLDocument` parsed das Markup, baut ein DOM auf und löst verknüpfte Ressourcen (CSS, Bilder, Fonts) auf. Ohne ein korrektes Dokument‑Objekt können Sie keine Styles manipulieren oder etwas rendern. + +## Schritt 2 – Font‑Style‑HTML anwenden (Fett zu p hinzufügen) + +Jetzt **wenden wir Font‑Style‑HTML** an, indem wir über jedes `

`‑Element iterieren und dessen `font-weight` auf bold setzen. Das ist der programmatische Weg, **bold zu p**‑Tags hinzuzufügen, ohne die Originaldatei zu verändern. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Profi‑Tipp:* Wenn Sie nur einen Teil fett machen wollen, ändern Sie den Selektor zu etwas Spezifischerem, z. B. `"p.intro"`. + +## Schritt 3 – HTML als Bild rendern (HTML zu PNG konvertieren) + +Mit dem fertig vorbereiteten DOM konfigurieren wir `ImageRenderingOptions` und rufen `RenderToImage` auf. Hier passiert die **convert html to png**‑Magie. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Warum die Optionen wichtig sind:* Das Festlegen einer festen Breite/Höhe verhindert, dass die Ausgabe zu groß wird, während Antialiasing ein glatteres visuelles Ergebnis liefert. Sie können `options` auch zu `ImageFormat.Jpeg` ändern, wenn Sie eine kleinere Dateigröße bevorzugen. + +## Schritt 4 – HTML in ZIP speichern (Ressourcen bündeln) + +Oft muss das originale HTML zusammen mit CSS, Bildern und Fonts ausgeliefert werden. Aspose.HTMLs `ZipArchiveSaveOptions` erledigt genau das. Zusätzlich binden wir einen benutzerdefinierten `ResourceHandler` ein, sodass alle externen Assets im selben Ordner wie das Archiv geschrieben werden. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Randfall:* Wenn Ihr HTML entfernte Bilder referenziert, die Authentifizierung benötigen, schlägt der Standard‑Handler fehl. In diesem Szenario können Sie `MyResourceHandler` erweitern, um HTTP‑Header zu injizieren. + +## Schritt 5 – Alles in einer einzigen Converter‑Klasse zusammenführen + +Unten finden Sie die vollständige, sofort ausführbare Klasse, die alle vorherigen Schritte verknüpft. Sie können sie in eine Konsolen‑App kopieren, `Convert` aufrufen und die Dateien erscheinen sehen. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Erwartete Ausgabe + +Nach dem Ausführen des obigen Snippets finden Sie zwei Dateien im `outputDirectory`: + +| Datei | Beschreibung | +|------|-------------| +| `page.png` | Ein 1200 × 800 PNG‑Rendering des Quell‑HTMLs, wobei jeder Absatz **fett** dargestellt wird. | +| `archive.zip` | Ein ZIP‑Bundle, das das originale `input.html`, dessen CSS, Bilder und alle Web‑Fonts enthält – ideal für die Offline‑Verteilung. | + +Sie können `page.png` mit jedem Bildbetrachter öffnen, um zu prüfen, ob die fette Formatierung angewendet wurde, und `archive.zip` extrahieren, um das unveränderte HTML zusammen mit seinen Assets zu sehen. + +## Häufige Fragen & Stolperfallen + +- **Was, wenn das HTML JavaScript enthält?** + Aspose.HTML führt während des Renderns **keine** Skripte aus, sodass dynamischer Inhalt nicht erscheint. Für vollständig gerenderte Seiten benötigen Sie einen Headless‑Browser, aber für statische Vorlagen ist dieser Ansatz schneller und leichter. + +- **Kann ich das Ausgabeformat zu JPEG oder BMP ändern?** + Ja – tauschen Sie die `ImageRenderingOptions`‑Eigenschaft `ImageFormat` aus, z. B. `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Muss ich das `HTMLDocument` manuell freigeben?** + Die Klasse implementiert `IDisposable`. In einem langlebigen Service sollten Sie sie in einem `using`‑Block einbetten oder `document.Dispose()` nach Gebrauch aufrufen. + +- **Wie funktioniert der benutzerdefinierte `MyResourceHandler`?** + Er erhält jede externe Ressource (CSS, Bilder, Fonts) und schreibt sie in den von Ihnen angegebenen Ordner. Das stellt sicher, dass das ZIP eine getreue Kopie aller vom HTML referenzierten Dateien enthält. + +## Fazit + +Sie haben nun eine kompakte, produktionsreife Lösung, die **convert html to png**, **render html as image**, **save html to zip**, **apply font style html** und **add bold to p** – alles in wenigen C#‑Zeilen. Der Code ist eigenständig, funktioniert mit .NET 6+ und lässt sich in jeden Backend‑Service einbinden, der schnelle visuelle Schnappschüsse von Web‑Inhalten benötigt. + +Bereit für den nächsten Schritt? Ändern Sie die Render‑Größe, experimentieren Sie mit anderen CSS‑Eigenschaften (wie `font-family` oder `color`) oder integrieren Sie diesen Converter in einen ASP.NET Core‑Endpoint, der das PNG auf Abruf zurückgibt. Die Möglichkeiten sind endlos, und mit Aspose.HTML kommen Sie ohne schwere Browser‑Abhängigkeiten aus. + +Wenn Sie auf Probleme stoßen oder Ideen für Erweiterungen haben, hinterlassen Sie unten einen Kommentar. Viel Spaß beim Coden! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/german/net/html-document-manipulation/_index.md index 1e5420dd7..4607fedf5 100644 --- a/html/german/net/html-document-manipulation/_index.md +++ b/html/german/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Erfahren Sie, wie Sie Aspose.HTML für .NET verwenden. Importieren Sie Namespace Schöpfen Sie das Potenzial der Webentwicklung mit Aspose.HTML für .NET. Erstellen, konvertieren und bearbeiten Sie HTML-Dokumente ganz einfach. ### [HTML aus String in C# erstellen – Leitfaden für benutzerdefinierten Ressourcen-Handler](./create-html-from-string-in-c-custom-resource-handler-guide/) Erfahren Sie, wie Sie mit einem benutzerdefinierten Ressourcen-Handler HTML aus einem String in C# generieren und rendern. +### [HTML-Dokument in C# erstellen – Schritt‑für‑Schritt‑Anleitung](./create-html-document-c-step-by-step-guide/) +Erfahren Sie, wie Sie mit Aspose.HTML für .NET ein HTML-Dokument in C# Schritt für Schritt erstellen. ## Abschluss diff --git a/html/german/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/german/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..f2c3663e6 --- /dev/null +++ b/html/german/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: Erstelle ein HTML‑Dokument in C# und lerne, wie man ein Element per ID + abruft, ein Element per ID findet, den Stil eines HTML‑Elements ändert und fett/kursiv + hinzufügt, indem man Aspose.Html verwendet. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: de +og_description: Erstelle ein HTML-Dokument in C# und lerne sofort, wie man ein Element + per ID abruft, ein Element per ID findet, den Stil eines HTML-Elements ändert und + fett/kursiv hinzufügt – mit klaren Codebeispielen. +og_title: HTML-Dokument mit C# erstellen – Vollständiger Programmierleitfaden +tags: +- Aspose.Html +- C# +- DOM manipulation +title: HTML-Dokument mit C# erstellen – Schritt‑für‑Schritt‑Anleitung +url: /de/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML-Dokument in C# erstellen – Schritt‑für‑Schritt‑Anleitung + +Haben Sie jemals **HTML-Dokument in C#** von Grund auf erstellen und dann das Aussehen eines einzelnen Absatzes anpassen müssen? Sie sind nicht allein. In vielen Web‑Automatisierungsprojekten erzeugen Sie eine HTML‑Datei, suchen ein Tag anhand seiner ID und wenden dann etwas Styling an – oft fett + kursiv – ohne jemals einen Browser zu berühren. + +In diesem Tutorial gehen wir genau das durch: Wir erstellen ein HTML‑Dokument in C#, **get element by id**, **locate element by id**, **change HTML element style** und schließlich **add bold italic** mit der Aspose.Html‑Bibliothek. Am Ende haben Sie ein vollständig ausführbares Snippet, das Sie in jedes .NET‑Projekt einbinden können. + +## Was Sie benötigen + +- .NET 6 oder höher (der Code funktioniert auch mit .NET Framework 4.7+) +- Visual Studio 2022 (oder ein beliebiger Editor Ihrer Wahl) +- Das **Aspose.Html** NuGet‑Paket (`Install-Package Aspose.Html`) + +Das war’s – keine zusätzlichen HTML‑Dateien, kein Web‑Server, nur ein paar Zeilen C#. + +## HTML-Dokument in C# erstellen – Dokument initialisieren + +Zuerst benötigen Sie ein lebendes `HTMLDocument`‑Objekt, mit dem die Aspose.Html‑Engine arbeiten kann. Stellen Sie sich das vor wie das Öffnen eines frischen Notizbuchs, in das Sie Ihr Markup schreiben. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Warum das wichtig ist:** Durch das Übergeben des rohen Strings an `HTMLDocument` vermeiden Sie Dateiein‑/ausgabe und halten alles im Speicher – perfekt für Unit‑Tests oder die Generierung zur Laufzeit. + +## Element per ID abrufen – den Absatz finden + +Jetzt, wo das Dokument existiert, müssen wir **get element by id**. Die DOM‑API stellt uns `GetElementById` zur Verfügung, das eine `IElement`‑Referenz oder `null` zurückgibt, wenn die ID nicht vorhanden ist. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Pro‑Tipp:** Auch wenn unser Markup winzig ist, verhindert ein Null‑Check Kopfschmerzen, wenn dieselbe Logik auf größeren, dynamischen Seiten wiederverwendet wird. + +## Element per ID lokalisieren – ein alternativer Ansatz + +Manchmal haben Sie bereits eine Referenz auf die Wurzel des Dokuments und bevorzugen eine abfragebasierte Suche. Die Verwendung von CSS‑Selektoren (`QuerySelector`) ist ein weiterer Weg, um **locate element by id** zu erreichen: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **Wann welches verwenden?** `GetElementById` ist etwas schneller, da es eine direkte Hash‑Suche ist. `QuerySelector` glänzt, wenn Sie komplexe Selektoren benötigen (z. B. `div > p.highlight`). + +## HTML‑Elementstil ändern – Fett + Kursiv hinzufügen + +Mit dem Element in der Hand ist der nächste Schritt, **change HTML element style**. Aspose.Html stellt ein `Style`‑Objekt bereit, mit dem Sie CSS‑Eigenschaften anpassen oder die praktische `WebFontStyle`‑Aufzählung verwenden können, um mehrere Schriftmerkmale gleichzeitig anzuwenden. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Diese eine Zeile setzt das `font-weight` des Elements auf `bold` und `font-style` auf `italic`. Im Hintergrund übersetzt Aspose.Html die Aufzählung in den entsprechenden CSS‑String. + +### Vollständiges funktionierendes Beispiel + +Wenn man alle Teile zusammenfügt, entsteht ein kompaktes, eigenständiges Programm, das Sie sofort kompilieren und ausführen können: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Erwartete Ausgabe** + +``` +Rendered HTML: +

Hello world

+``` + +Das `

`‑Tag enthält jetzt ein Inline‑`style`‑Attribut, das den Text sowohl fett als auch kursiv macht – genau das, was wir wollten. + +## Randfälle & häufige Stolperfallen + +| Situation | Worauf zu achten ist | Wie zu handeln | +|-----------|----------------------|----------------| +| **ID existiert nicht** | `GetElementById` gibt `null` zurück. | Wirf eine Ausnahme oder greife auf ein Standard‑Element zurück. | +| **Mehrere Elemente teilen dieselbe ID** | Der HTML‑Standard verlangt eindeutige IDs, aber reale Seiten brechen die Regel manchmal. | `GetElementById` gibt das erste gefundene Element zurück; erwägen Sie `QuerySelectorAll` zu verwenden, wenn Sie Duplikate behandeln müssen. | +| **Styling‑Konflikte** | Bestehende Inline‑Styles können überschrieben werden. | Fügen Sie dem `Style`‑Objekt hinzu, anstatt die gesamte `style`‑Zeichenkette zu setzen: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Rendering im Browser** | Einige Browser ignorieren `WebFontStyle`, wenn das Element bereits eine CSS‑Klasse mit höherer Spezifität hat. | Verwenden Sie `!important` über `paragraph.Style.SetProperty("font-weight", "bold", "important");` falls nötig. | + +## Pro‑Tipps für reale Projekte + +- **Cache das Dokument**, wenn Sie viele Elemente verarbeiten; das Erstellen eines neuen `HTMLDocument` für jedes winzige Snippet kann die Leistung beeinträchtigen. +- **Kombinieren Sie Stiländerungen** in einer einzigen `Style`‑Transaktion, um mehrere DOM‑Reflows zu vermeiden. +- **Nutzen Sie die Rendering‑Engine von Aspose.Html** zum Export des finalen Dokuments als PDF oder Bild – ideal für Reporting‑Tools. + +## Visuelle Bestätigung (optional) + +Wenn Sie das Ergebnis lieber in einem Browser sehen möchten, können Sie den gerenderten String in einer `.html`‑Datei speichern: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Öffnen Sie `output.html` und Sie sehen **Hello world** fett + kursiv dargestellt. + +![Beispiel für HTML-Dokument in C# mit fett‑kursiv‑Absatz](/images/create-html-document-csharp.png "HTML-Dokument in C# – gerenderte Ausgabe") + +*Alt‑Text: HTML‑Dokument in C# – gerenderte Ausgabe mit fett‑kursiv‑Text.* + +## Fazit + +Wir haben gerade **ein HTML‑Dokument in C# erstellt**, **ein Element per ID abgerufen**, **ein Element per ID lokalisiert**, **den HTML‑Elementstil geändert** und schließlich **fett‑kursiv hinzugefügt** – alles mit ein paar Zeilen Code unter Verwendung von Aspose.Html. Der Ansatz ist unkompliziert, funktioniert in jeder .NET‑Umgebung und skaliert zu größeren DOM‑Manipulationen. + +Bereit für den nächsten Schritt? Versuchen Sie, `WebFontStyle` durch andere Aufzählungen wie `Underline` zu ersetzen oder mehrere Stile manuell zu kombinieren. Oder experimentieren Sie mit dem Laden einer externen HTML‑Datei und wenden die gleiche Technik auf Hunderte von Elementen an. Der Himmel ist die Grenze, und jetzt haben Sie ein solides Fundament zum Weiterbauen. + +Viel Spaß beim Coden! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/german/net/html-extensions-and-conversions/_index.md b/html/german/net/html-extensions-and-conversions/_index.md index 607896d28..b1d00bf8a 100644 --- a/html/german/net/html-extensions-and-conversions/_index.md +++ b/html/german/net/html-extensions-and-conversions/_index.md @@ -38,41 +38,49 @@ Aspose.HTML für .NET ist nicht nur eine Bibliothek; es verändert die Welt der ## Tutorials zu HTML-Erweiterungen und -Konvertierungen ### [Konvertieren Sie HTML in .NET in PDF mit Aspose.HTML](./convert-html-to-pdf/) -Konvertieren Sie HTML mühelos in PDF mit Aspose.HTML für .NET. Folgen Sie unserer Schritt-für-Schritt-Anleitung und entfesseln Sie die Leistungsfähigkeit der HTML-zu-PDF-Konvertierung. +Konvertieren Sie HTML mühelos in PDF mit Aspose.HTML für .NET. Folgen Sie unserer Schritt‑für‑Schritt‑Anleitung und entfesseln Sie die Leistungsfähigkeit der HTML‑zu‑PDF‑Konvertierung. ### [Konvertieren Sie EPUB in .NET mit Aspose.HTML in ein Bild](./convert-epub-to-image/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in Bilder konvertieren. Schritt-für-Schritt-Anleitung mit Codebeispielen und anpassbaren Optionen. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in Bilder konvertieren. Schritt‑für‑Schritt‑Anleitung mit Codebeispielen und anpassbaren Optionen. ### [Konvertieren Sie EPUB in .NET mit Aspose.HTML in PDF](./convert-epub-to-pdf/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in PDF konvertieren. Diese Schritt-für-Schritt-Anleitung umfasst Anpassungsoptionen, FAQs und mehr für eine nahtlose Dokumentkonvertierung. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in PDF konvertieren. Diese Schritt‑für‑Schritt‑Anleitung umfasst Anpassungsoptionen, FAQs und mehr für eine nahtlose Dokumentkonvertierung. ### [Konvertieren Sie EPUB in XPS in .NET mit Aspose.HTML](./convert-epub-to-xps/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in XPS in .NET konvertieren. Folgen Sie unserer Schritt-für-Schritt-Anleitung für mühelose Konvertierungen. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET EPUB in XPS in .NET konvertieren. Folgen Sie unserer Schritt‑für‑Schritt‑Anleitung für mühelose Konvertierungen. ### [Konvertieren Sie HTML in BMP in .NET mit Aspose.HTML](./convert-html-to-bmp/) Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in BMP in .NET konvertieren. Umfassender Leitfaden für Webentwickler zur Nutzung von Aspose.HTML für .NET. ### [Konvertieren Sie HTML in .NET in DOC und DOCX mit Aspose.HTML](./convert-html-to-doc-docx/) -Erfahren Sie in dieser Schritt-für-Schritt-Anleitung, wie Sie die Leistung von Aspose.HTML für .NET nutzen. Konvertieren Sie HTML mühelos in DOCX und verbessern Sie Ihre .NET-Projekte. Legen Sie noch heute los! +Erfahren Sie in dieser Schritt‑für‑Schritt‑Anleitung, wie Sie die Leistung von Aspose.HTML für .NET nutzen. Konvertieren Sie HTML mühelos in DOCX und verbessern Sie Ihre .NET‑Projekte. Legen Sie noch heute los! ### [Konvertieren Sie HTML in GIF in .NET mit Aspose.HTML](./convert-html-to-gif/) -Entdecken Sie die Leistungsfähigkeit von Aspose.HTML für .NET: Eine Schritt-für-Schritt-Anleitung zur Konvertierung von HTML in GIF. Voraussetzungen, Codebeispiele, FAQs und mehr! Optimieren Sie Ihre HTML-Manipulation mit Aspose.HTML. +Entdecken Sie die Leistungsfähigkeit von Aspose.HTML für .NET: Eine Schritt‑für‑Schritt‑Anleitung zur Konvertierung von HTML in GIF. Voraussetzungen, Codebeispiele, FAQs und mehr! Optimieren Sie Ihre HTML‑Manipulation mit Aspose.HTML. ### [Konvertieren Sie HTML in JPEG in .NET mit Aspose.HTML](./convert-html-to-jpeg/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in JPEG in .NET konvertieren. Eine Schritt-für-Schritt-Anleitung zur Nutzung der Leistungsfähigkeit von Aspose.HTML für .NET. Optimieren Sie Ihre Webentwicklungsaufgaben mühelos. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in JPEG in .NET konvertieren. Eine Schritt‑für‑Schritt‑Anleitung zur Nutzung der Leistungsfähigkeit von Aspose.HTML für .NET. Optimieren Sie Ihre Webentwicklungsaufgaben mühelos. ### [Konvertieren Sie HTML in .NET in Markdown mit Aspose.HTML](./convert-html-to-markdown/) -Erfahren Sie, wie Sie HTML in .NET mit Aspose.HTML in Markdown konvertieren, um Inhalte effizient zu bearbeiten. Erhalten Sie eine Schritt-für-Schritt-Anleitung für einen nahtlosen Konvertierungsprozess. +Erfahren Sie, wie Sie HTML in .NET mit Aspose.HTML in Markdown konvertieren, um Inhalte effizient zu bearbeiten. Erhalten Sie eine Schritt‑für‑Schritt‑Anleitung für einen nahtlosen Konvertierungsprozess. ### [Konvertieren Sie HTML in MHTML in .NET mit Aspose.HTML](./convert-html-to-mhtml/) -Konvertieren Sie HTML in .NET in MHTML mit Aspose.HTML – Eine Schritt-für-Schritt-Anleitung zum effizienten Archivieren von Webinhalten. Erfahren Sie, wie Sie mit Aspose.HTML für .NET MHTML-Archive erstellen. +Konvertieren Sie HTML in .NET in MHTML mit Aspose.HTML – Eine Schritt‑für‑Schritt‑Anleitung zum effizienten Archivieren von Webinhalten. Erfahren Sie, wie Sie mit Aspose.HTML für .NET MHTML‑Archive erstellen. ### [Konvertieren Sie HTML in PNG in .NET mit Aspose.HTML](./convert-html-to-png/) -Entdecken Sie, wie Sie mit Aspose.HTML für .NET HTML-Dokumente bearbeiten und konvertieren. Schritt-für-Schritt-Anleitung für effektive .NET-Entwicklung. +Entdecken Sie, wie Sie mit Aspose.HTML für .NET HTML‑Dokumente bearbeiten und konvertieren. Schritt‑für‑Schritt‑Anleitung für effektive .NET‑Entwicklung. +### [HTML in Bild konvertieren – Komplettanleitung für C#](./convert-html-to-image-in-c-complete-guide/) +Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in Bildformate konvertieren. Schritt‑für‑Schritt‑Anleitung mit Codebeispielen und Optionen. ### [Konvertieren Sie HTML in TIFF in .NET mit Aspose.HTML](./convert-html-to-tiff/) -Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in TIFF konvertieren. Folgen Sie unserer Schritt-für-Schritt-Anleitung zur effizienten Optimierung von Webinhalten. +Erfahren Sie, wie Sie mit Aspose.HTML für .NET HTML in TIFF konvertieren. Folgen Sie unserer Schritt‑für‑Schritt‑Anleitung zur effizienten Optimierung von Webinhalten. ### [Konvertieren Sie HTML in XPS in .NET mit Aspose.HTML](./convert-html-to-xps/) -Entdecken Sie die Leistungsfähigkeit von Aspose.HTML für .NET: Konvertieren Sie HTML mühelos in XPS. Voraussetzungen, Schritt-für-Schritt-Anleitung und FAQs inklusive. +Entdecken Sie die Leistungsfähigkeit von Aspose.HTML für .NET: Konvertieren Sie HTML mühelos in XPS. Voraussetzungen, Schritt‑für‑Schritt‑Anleitung und FAQs inklusive. ### [HTML in C# zippen – HTML in Zip speichern](./how-to-zip-html-in-c-save-html-to-zip/) -Erfahren Sie, wie Sie HTML-Inhalte mit Aspose.HTML für .NET in eine ZIP-Datei komprimieren und speichern. -### [HTML-Dokument mit formatiertem Text erstellen und in PDF exportieren – Vollständige Anleitung](./create-html-document-with-styled-text-and-export-to-pdf-full/) -Erfahren Sie, wie Sie ein HTML-Dokument mit formatiertem Text erstellen und es mit Aspose.HTML für .NET in ein PDF exportieren. +Erfahren Sie, wie Sie HTML‑Inhalte mit Aspose.HTML für .NET in eine ZIP‑Datei komprimieren und speichern. +### [HTML zippen mit Aspose.HTML – Komplettanleitung](./how-to-zip-html-with-aspose-html-complete-guide/) +Erfahren Sie, wie Sie HTML‑Inhalte mit Aspose.HTML in ein ZIP‑Archiv komprimieren und speichern – vollständige Schritt‑für‑Schritt‑Anleitung. +### [HTML‑Dokument mit formatiertem Text erstellen und in PDF exportieren – Vollständige Anleitung](./create-html-document-with-styled-text-and-export-to-pdf-full/) +Erfahren Sie, wie Sie ein HTML‑Dokument mit formatiertem Text erstellen und es mit Aspose.HTML für .NET in ein PDF exportieren. ### [PDF aus HTML erstellen – C# Schritt‑für‑Schritt‑Anleitung](./create-pdf-from-html-c-step-by-step-guide/) Erstellen Sie PDF aus HTML mit C# – eine detaillierte Schritt‑für‑Schritt‑Anleitung mit Aspose.HTML für .NET. +### [PDF aus HTML mit Aspose erstellen – Schritt‑für‑Schritt C#‑Leitfaden](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Erfahren Sie, wie Sie mit Aspose.HTML für .NET PDF aus HTML erstellen. Detaillierte Schritt‑für‑Schritt‑Anleitung in C#. ### [HTML als ZIP speichern – Komplettes C#‑Tutorial](./save-html-as-zip-complete-c-tutorial/) Erfahren Sie, wie Sie HTML‑Inhalte mit Aspose.HTML für .NET in ein ZIP‑Archiv speichern – vollständige Schritt‑für‑Schritt‑Anleitung in C#. ### [HTML in ZIP speichern in C# – Komplettes In‑Memory‑Beispiel](./save-html-to-zip-in-c-complete-in-memory-example/) -Speichern Sie HTML-Inhalte in ein ZIP-Archiv komplett im Speicher mit Aspose.HTML für .NET. Schritt‑für‑Schritt‑Anleitung. +Speichern Sie HTML‑Inhalte in ein ZIP‑Archiv komplett im Speicher mit Aspose.HTML für .NET. Schritt‑für‑Schritt‑Anleitung. +### [HTML als ZIP speichern in C# – Vollständige Anleitung mit benutzerdefiniertem Speicher](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Erfahren Sie, wie Sie HTML‑Inhalte mit Aspose.HTML für .NET in ein ZIP‑Archiv mit benutzerdefiniertem Speicher komprimieren und speichern. ## Abschluss diff --git a/html/german/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/german/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..9da5eb4c3 --- /dev/null +++ b/html/german/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: HTML mit Aspose.HTML in C# in ein Bild konvertieren. Erfahren Sie, wie + Sie HTML als PNG speichern, die Bildgröße beim Rendern festlegen und das Bild in + wenigen Schritten in eine Datei schreiben. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: de +og_description: HTML schnell in ein Bild konvertieren. Dieser Leitfaden zeigt, wie + man HTML als PNG speichert, die Bildgröße beim Rendern festlegt und das Bild mit + Aspose.HTML in eine Datei schreibt. +og_title: HTML in ein Bild konvertieren in C# – Schritt‑für‑Schritt‑Anleitung +tags: +- Aspose.HTML +- C# +- Image Rendering +title: HTML in Bild konvertieren in C# – Vollständiger Leitfaden +url: /de/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML in Bild konvertieren in C# – Komplett‑Anleitung + +Haben Sie schon einmal **HTML in ein Bild konvertieren** müssen, etwa für ein Dashboard‑Thumbnail, eine E‑Mail‑Vorschau oder einen PDF‑Report? Das kommt öfter vor, als man denkt, besonders wenn dynamische Web‑Inhalte an anderer Stelle eingebettet werden müssen. + +Die gute Nachricht? Mit Aspose.HTML können Sie **HTML in ein Bild konvertieren** mit nur wenigen Zeilen Code, und Sie lernen außerdem, wie man *HTML als PNG speichert*, die Ausgabeabmessungen steuert und *Bild in Datei schreibt* – ganz ohne Schweiß. + +In diesem Tutorial gehen wir alles durch, was Sie wissen müssen: vom Laden einer Remote‑Seite über das Anpassen der Render‑Größe bis hin zum Persistieren des Ergebnisses als PNG‑Datei auf der Festplatte. Keine externen Tools, keine umständlichen Befehlszeilen‑Tricks – nur reiner C#‑Code, den Sie in jedes .NET‑Projekt einbinden können. + +## Was Sie lernen werden + +- Wie man **Webseite zu PNG rendert** mit der `HTMLDocument`‑Klasse von Aspose.HTML. +- Die genauen Schritte, um **Bildgröße beim Rendern** festzulegen, sodass die Ausgabe Ihren Layout‑Anforderungen entspricht. +- Möglichkeiten, **Bild in Datei zu schreiben** sicher zu handhaben, inklusive Streams und Dateipfaden. +- Tipps zur Fehlersuche bei typischen Problemen wie fehlenden Schriften oder Netzwerk‑Timeouts. + +### Voraussetzungen + +- .NET 6.0 oder höher (die API funktioniert auch mit .NET Framework, aber .NET 6+ wird empfohlen). +- Ein Verweis auf das NuGet‑Paket **Aspose.HTML for .NET** (`Aspose.Html`). +- Grundkenntnisse in C# und async/await (optional, aber hilfreich). + +Wenn Sie das bereits haben, können Sie sofort mit der Konvertierung von HTML in Bild beginnen. + +## Schritt 1: Web‑Seite laden – Die Basis für das Konvertieren von HTML in Bild + +Bevor irgendein Rendering stattfinden kann, benötigen Sie eine `HTMLDocument`‑Instanz, die die Seite repräsentiert, die Sie erfassen wollen. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Warum das wichtig ist:* Das `HTMLDocument` analysiert das HTML, löst CSS auf und baut den DOM auf. Wenn das Dokument nicht geladen werden kann (z. B. wegen Netzwerkproblemen), erzeugt das nachfolgende Rendering ein leeres Bild. Überprüfen Sie immer, ob die URL erreichbar ist, bevor Sie fortfahren. + +## Schritt 2: Bildgröße beim Rendern festlegen – Breite, Höhe und Qualität steuern + +Aspose.HTML ermöglicht das Feintuning der Ausgabedimensionen mit `ImageRenderingOptions`. Hier legen Sie **Bildgröße beim Rendern** fest, um Ihr Ziel‑Layout zu treffen. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Pro‑Tipp:* Wenn Sie `Width` und `Height` weglassen, verwendet Aspose.HTML die intrinsische Größe der Seite, was bei responsiven Designs unvorhersehbar sein kann. Durch explizite Angabe der Dimensionen stellen Sie sicher, dass Ihre **save HTML as PNG**‑Ausgabe exakt so aussieht, wie Sie es erwarten. + +## Schritt 3: Bild in Datei schreiben – Das gerenderte PNG persistieren + +Jetzt, wo das Dokument bereit und die Render‑Optionen gesetzt sind, können Sie endlich **Bild in Datei schreiben**. Die Verwendung eines `FileStream` garantiert, dass die Datei sicher erstellt wird, selbst wenn das Verzeichnis noch nicht existiert. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +Nachdem dieser Block ausgeführt wurde, finden Sie `page.png` an dem von Ihnen angegebenen Ort. Sie haben gerade **Webseite zu PNG gerendert** und in einem einzigen, unkomplizierten Vorgang auf die Festplatte geschrieben. + +### Erwartetes Ergebnis + +Öffnen Sie `C:\Temp\page.png` mit einem Bildbetrachter. Sie sollten einen genauen Schnappschuss von `https://example.com` sehen, gerendert mit 1024 × 768 Pixel und glatten Kanten dank Antialiasing. Enthält die Seite dynamische Inhalte (z. B. JavaScript‑generierte Elemente), werden diese erfasst, solange der DOM vor dem Rendering vollständig geladen ist. + +## Schritt 4: Sonderfälle behandeln – Schriften, Authentifizierung und große Seiten + +Während der Basis‑Ablauf für die meisten öffentlichen Seiten funktioniert, bringen reale Szenarien oft Stolpersteine mit sich: + +| Situation | Was zu tun ist | +|-----------|----------------| +| **Benutzerdefinierte Schriften werden nicht geladen** | Betten Sie die Schriftdateien lokal ein und setzen Sie `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Seiten hinter Authentifizierung** | Verwenden Sie die `HTMLDocument`‑Überladung, die ein `HttpWebRequest` mit Cookies oder Tokens akzeptiert. | +| **Sehr lange Seiten** | Erhöhen Sie `Height` oder aktivieren Sie `PageScaling` in `ImageRenderingOptions`, um Abschneiden zu vermeiden. | +| **Speicherspitzen** | Rendern Sie in Teilen mit der `RenderToImage`‑Überladung, die einen `Rectangle`‑Bereich akzeptiert. | + +Durch das Berücksichtigen dieser *write image to file*‑Nuancen bleibt Ihre **convert html to image**‑Pipeline in der Produktion robust. + +## Schritt 5: Vollständiges Beispiel – Zum Kopieren und Einfügen bereit + +Unten finden Sie das komplette Programm, fertig zum Kompilieren. Es enthält alle Schritte, Fehlerbehandlung und Kommentare, die Sie benötigen. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Führen Sie dieses Programm aus, und Sie sehen die Bestätigungsnachricht in der Konsole. Die PNG‑Datei wird genau das sein, was Sie erwarten, wenn Sie **Webseite zu PNG** manuell im Browser öffnen und einen Screenshot machen – nur schneller und vollständig automatisiert. + +## Häufig gestellte Fragen + +**F: Kann ich eine lokale HTML‑Datei anstelle einer URL konvertieren?** +Ja. Ersetzen Sie einfach die URL durch einen Dateipfad: `new HTMLDocument(@"C:\myPage.html")`. + +**F: Benötige ich eine Lizenz für Aspose.HTML?** +Eine kostenlose Evaluierungslizenz funktioniert für Entwicklung und Tests. Für die Produktion erwerben Sie eine Lizenz, um das Evaluierungs‑Wasserzeichen zu entfernen. + +**F: Was, wenn die Seite JavaScript verwendet, um Inhalte nach dem ersten Laden zu holen?** +Aspose.HTML führt JavaScript synchron beim Parsen aus, aber langlaufende Skripte benötigen möglicherweise eine manuelle Verzögerung. Sie können `HTMLDocument.WaitForReadyState` vor dem Rendern verwenden. + +## Fazit + +Sie haben nun eine solide End‑zu‑End‑Lösung, um **HTML in ein Bild zu konvertieren** in C#. Durch Befolgen der obigen Schritte können Sie **HTML als PNG speichern**, exakt **Bildgröße beim Rendern festlegen** und zuverlässig **Bild in Datei schreiben** – sowohl unter Windows als auch Linux. + +Von einfachen Screenshots bis hin zur automatisierten Berichtserstellung skaliert diese Technik hervorragend. Als Nächstes können Sie mit anderen Ausgabeformaten wie JPEG oder BMP experimentieren oder den Code in eine ASP.NET Core API integrieren, die das PNG direkt an Aufrufer zurückgibt. Die Möglichkeiten sind praktisch unbegrenzt. + +Viel Spaß beim Coden, und mögen Ihre gerenderten Bilder stets pixel‑perfekt sein! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/german/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..111e6a5d7 --- /dev/null +++ b/html/german/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-03-21 +description: Erstellen Sie PDFs schnell aus HTML mit Aspose HTML. Lernen Sie, HTML + in PDF zu rendern, HTML in PDF zu konvertieren und wie Sie Aspose in einem kurzen + Tutorial verwenden. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: de +og_description: PDF aus HTML mit Aspose in C# erstellen. Dieser Leitfaden zeigt, wie + man HTML zu PDF rendert, HTML in PDF konvertiert und Aspose effektiv nutzt. +og_title: PDF aus HTML erstellen – Vollständiges Aspose C#‑Tutorial +tags: +- Aspose +- C# +- PDF generation +title: PDF aus HTML mit Aspose erstellen – Schritt‑für‑Schritt C#‑Leitfaden +url: /de/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF aus HTML mit Aspose erstellen – Schritt‑für‑Schritt C# Anleitung + +Haben Sie jemals **PDF aus HTML erstellen** müssen, waren sich aber nicht sicher, welche Bibliothek pixel‑perfekte Ergebnisse liefert? Sie sind nicht allein. Viele Entwickler stolpern, wenn sie versuchen, einen Web‑Ausschnitt in ein druckbares Dokument zu verwandeln, und am Ende unscharfen Text oder fehlerhafte Layouts erhalten. + +Die gute Nachricht ist, dass Aspose HTML den gesamten Prozess mühelos macht. In diesem Tutorial führen wir Sie durch den genauen Code, den Sie benötigen, um **HTML zu PDF zu rendern**, erklären, warum jede Einstellung wichtig ist, und zeigen Ihnen, wie Sie **HTML zu PDF konvertieren** ohne versteckte Tricks. Am Ende wissen Sie **wie man Aspose verwendet** für zuverlässige PDF‑Erstellung in jedem .NET‑Projekt. + +## Voraussetzungen – Was Sie benötigen, bevor Sie beginnen + +- **.NET 6.0 oder höher** (das Beispiel funktioniert ebenfalls mit .NET Framework 4.7+) +- **Visual Studio 2022** oder jede IDE, die C# unterstützt +- **Aspose.HTML for .NET** NuGet‑Paket (Kostenlose Testversion oder lizenzierte Version) +- Grundlegendes Verständnis der C#‑Syntax (keine tiefgehenden PDF‑Kenntnisse erforderlich) + +Wenn Sie diese haben, können Sie loslegen. Andernfalls holen Sie sich das neueste .NET‑SDK und installieren das NuGet‑Paket mit: + +```bash +dotnet add package Aspose.HTML +``` + +Diese einzelne Zeile zieht alles, was Sie für die **aspose html to pdf**‑Konvertierung benötigen, ein. + +## Schritt 1: Richten Sie Ihr Projekt ein, um PDF aus HTML zu erstellen + +Das Erste, was Sie tun, ist ein neues Konsolen‑App zu erstellen (oder den Code in einen bestehenden Service zu integrieren). Hier ist ein minimales `Program.cs`‑Gerüst: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro‑Tipp:** Wenn Sie in älteren Beispielen `Aspise.Html.Rendering.Text` sehen, ersetzen Sie es durch `Aspose.Html.Rendering.Text`. Der Tippfehler führt zu einem Kompilierungsfehler. + +Die korrekten Namespaces zu haben, stellt sicher, dass der Compiler die **TextOptions**‑Klasse finden kann, die wir später benötigen. + +## Schritt 2: Erstellen Sie das HTML‑Dokument (HTML zu PDF rendern) + +Jetzt erstellen wir das Quell‑HTML. Aspose erlaubt das Übergeben eines rohen Strings, eines Dateipfads oder sogar einer URL. Für diese Demo halten wir es einfach: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Warum einen String übergeben? Es vermeidet Dateisystem‑I/O, beschleunigt die Konvertierung und garantiert, dass das HTML, das Sie im Code sehen, exakt das ist, was gerendert wird. Wenn Sie lieber aus einer Datei laden, ersetzen Sie einfach das Konstruktor‑Argument durch eine Datei‑URI. + +## Schritt 3: Feinabstimmung der Textdarstellung (HTML zu PDF mit besserer Qualität konvertieren) + +Die Textdarstellung bestimmt häufig, ob Ihr PDF scharf oder unscharf aussieht. Aspose bietet eine `TextOptions`‑Klasse, mit der Sie Sub‑Pixel‑Hinting aktivieren können – essenziell für High‑DPI‑Ausgabe. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Das Aktivieren von `UseHinting` ist besonders nützlich, wenn Ihr Quell‑HTML benutzerdefinierte Schriften oder kleine Schriftgrößen enthält. Ohne diese Einstellung könnten Sie gezackte Kanten im finalen PDF bemerken. + +## Schritt 4: Textoptionen an die PDF‑Renderkonfiguration anhängen (Wie man Aspose verwendet) + +Als Nächstes binden wir diese Textoptionen an den PDF‑Renderer. Hier kommt **aspose html to pdf** wirklich zum Einsatz – alles von Seitengröße bis Kompression kann angepasst werden. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Sie können `PageSetup` weglassen, wenn Ihnen die Standard‑A4‑Größe passt. Die zentrale Erkenntnis ist, dass das `TextOptions`‑Objekt innerhalb von `PdfRenderingOptions` lebt, und so teilen Sie Aspose mit, *wie* der Text gerendert werden soll. + +## Schritt 5: Rendern Sie das HTML und speichern Sie das PDF (HTML zu PDF konvertieren) + +Abschließend streamen wir die Ausgabe in eine Datei. Die Verwendung eines `using`‑Blocks stellt sicher, dass das Dateihandle ordnungsgemäß geschlossen wird, selbst wenn eine Ausnahme auftritt. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Wenn Sie das Programm ausführen, finden Sie `output.pdf` neben der ausführbaren Datei. Öffnen Sie sie, und Sie sollten eine klare Überschrift und einen Absatz sehen – exakt wie im HTML‑String definiert. + +### Erwartete Ausgabe + +![Beispielausgabe PDF aus HTML erstellen](https://example.com/images/pdf-output.png "Beispielausgabe PDF aus HTML erstellen") + +*Der Screenshot zeigt das erzeugte PDF mit der Überschrift „Hello, Aspose!“ scharf gerendert dank Text‑Hinting.* + +## Häufige Fragen & Sonderfälle + +### 1. Was ist, wenn mein HTML externe Ressourcen (Bilder, CSS) referenziert? + +Aspose löst relative URLs basierend auf der Basis‑URI des Dokuments auf. Wenn Sie einen rohen String übergeben, setzen Sie die Basis‑URI manuell: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Jetzt wird jedes `` relativ zu `C:/MyProject/` gesucht. + +### 2. Wie bette ich Schriftarten ein, die nicht auf dem Server installiert sind? + +Fügen Sie einen ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Schritt 4: Speicheroptionen konfigurieren, um den benutzerdefinierten Speicher zu verwenden + +`HtmlSaveOptions` ermöglicht es uns, Aspose anzuweisen, alles in eine ZIP‑Datei zu packen. Die Eigenschaft `OutputStorage` (Legacy) erhält unsere `MyStorage`‑Instanz. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Hinweis:** In Aspose HTML 23.9+ heißt die Eigenschaft `OutputStorage`, ist aber als veraltet markiert. Die moderne Alternative ist `ZipOutputStorage`. Der untenstehende Code funktioniert mit beiden, weil das Interface identisch ist. + +### Schritt 5: Das Dokument als ZIP‑Archiv speichern + +Wählen Sie einen Zielordner (oder Stream) und lassen Sie Aspose die schwere Arbeit erledigen. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Wenn das Programm beendet ist, finden Sie `output.zip` mit folgendem Inhalt: + +* `index.html` – das Hauptdokument. +* Alle eingebetteten Bilder, CSS‑Dateien oder Skripte (falls Ihr HTML sie referenziert hat). + +Sie können das ZIP mit jedem Archiv‑Manager öffnen, um die Struktur zu überprüfen. + +## Ergebnis überprüfen (optional) + +Falls Sie das Archiv programmgesteuert prüfen möchten, ohne es auf die Festplatte zu extrahieren: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Typische Ausgabe: + +``` +- index.html (452 bytes) +``` + +Falls Sie Bilder oder CSS hatten, würden sie als zusätzliche Einträge erscheinen. Diese schnelle Prüfung bestätigt, dass **create html zip archive** wie erwartet funktioniert hat. + +## Häufige Fragen & Sonderfälle + +| Frage | Antwort | +|----------|--------| +| **Was, wenn ich das ZIP direkt in einen Response‑Stream schreiben muss?** | Geben Sie den `MemoryStream` zurück, den Sie von `MyStorage` nach `document.Save` erhalten. Casten Sie ihn zu einem `byte[]` und schreiben Sie ihn in `HttpResponse.Body`. | +| **Mein HTML verweist auf externe URLs – werden diese heruntergeladen?** | Nein. Aspose packt nur Ressourcen, die *eingebettet* sind (z. B. `` oder lokale Dateien). Für entfernte Assets müssen Sie diese zuerst herunterladen und das Markup anpassen. | +| **Die Eigenschaft `OutputStorage` ist als veraltet markiert – sollte ich sie ignorieren?** | Sie funktioniert weiterhin, aber das neuere `ZipOutputStorage` bietet dieselbe API unter einem anderen Namen. Ersetzen Sie `OutputStorage` durch `ZipOutputStorage`, wenn Sie einen build ohne Warnungen wünschen. | +| **Kann ich das ZIP verschlüsseln?** | Ja. Nach dem Speichern öffnen Sie die Datei mit `System.IO.Compression.ZipArchive` und setzen ein Passwort mithilfe von Drittanbieter‑Bibliotheken wie `SharpZipLib`. Aspose selbst bietet keine Verschlüsselung. | + +## Vollständiges funktionierendes Beispiel (Kopieren‑Einfügen) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Führen Sie das Programm aus, öffnen Sie `output.zip`, und Sie sehen eine einzelne `index.html`‑Datei, die die Überschrift „Hello from ZIP!“ rendert, wenn sie im Browser geöffnet wird. + +## Fazit + +Sie wissen jetzt, **wie man HTML als ZIP** in C# mit einer **benutzerdefinierten Speicher**‑Klasse speichert, **wie man HTML nach ZIP exportiert** und **wie man ein HTML‑ZIP‑Archiv** erstellt, das bereit für die Verteilung ist. Das Muster ist flexibel – tauschen Sie `MemoryStream` gegen einen Cloud‑Stream aus, fügen Sie Verschlüsselung hinzu oder integrieren Sie es in eine Web‑API, die das ZIP bei Bedarf zurückgibt. + +Bereit für den nächsten Schritt? Versuchen Sie, eine vollwertige Webseite mit Bildern und Styles zu verarbeiten, oder verbinden Sie den Speicher mit Azure Blob Storage, um das lokale Dateisystem vollständig zu umgehen. Der Himmel ist die Grenze, wenn Sie die ZIP‑Funktionen von Aspose.HTML mit Ihrer eigenen Speicher‑Logik kombinieren. + +Viel Spaß beim Coden, und möge Ihr Archiv stets ordentlich sein! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/greek/net/generate-jpg-and-png-images/_index.md b/html/greek/net/generate-jpg-and-png-images/_index.md index 5fd47cce3..c33fc13f2 100644 --- a/html/greek/net/generate-jpg-and-png-images/_index.md +++ b/html/greek/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ url: /el/net/generate-jpg-and-png-images/ Μάθετε πώς να βελτιώσετε την ποιότητα των εικόνων ενεργοποιώντας το antialiasing κατά τη μετατροπή αρχείων DOCX σε PNG ή JPG. ### [Μετατροπή docx σε png – δημιουργία αρχείου zip με C# σεμινάριο](./convert-docx-to-png-create-zip-archive-c-tutorial/) Μάθετε πώς να μετατρέψετε αρχεία DOCX σε PNG και να δημιουργήσετε αρχείο ZIP χρησιμοποιώντας C#. +### [Μετατροπή HTML σε PNG – Πλήρης Οδηγός C# με Εξαγωγή ZIP](./convert-html-to-png-full-c-guide-with-zip-export/) +Μάθετε πώς να μετατρέψετε HTML σε PNG με πλήρη οδηγό C# και εξαγωγή σε αρχείο ZIP. ## Σύναψη diff --git a/html/greek/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/greek/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..c97b036c1 --- /dev/null +++ b/html/greek/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Μετατρέψτε το HTML σε PNG και αποδώστε το HTML ως εικόνα ενώ αποθηκεύετε + το HTML σε ZIP. Μάθετε πώς να εφαρμόζετε στυλ γραμματοσειράς στο HTML και να προσθέτετε + έντονη γραφή στα στοιχεία p σε λίγα μόνο βήματα. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: el +og_description: Μετατρέψτε το HTML σε PNG γρήγορα. Αυτός ο οδηγός δείχνει πώς να αποδώσετε + το HTML ως εικόνα, να αποθηκεύσετε το HTML σε ZIP, να εφαρμόσετε στυλ γραμματοσειράς + στο HTML και να προσθέσετε έντονη γραφή στα στοιχεία p. +og_title: Μετατροπή HTML σε PNG – Πλήρης οδηγός C# +tags: +- Aspose +- C# +title: Μετατροπή HTML σε PNG – Πλήρης Οδηγός C# με Εξαγωγή ZIP +url: /el/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Μετατροπή HTML σε PNG – Πλήρης Οδηγός C# με Εξαγωγή ZIP + +Έχετε ποτέ χρειαστεί να **convert HTML to PNG** αλλά δεν ήσασταν σίγουροι ποια βιβλιοθήκη μπορεί να το κάνει χωρίς να χρησιμοποιήσει headless browser; Δεν είστε μόνοι σας. Σε πολλά έργα—μικρογραφίες email, προεπισκοπήσεις τεκμηρίωσης ή εικόνες γρήγορης προβολής—η μετατροπή μιας ιστοσελίδας σε στατική εικόνα είναι μια πραγματική ανάγκη. + +Τα καλά νέα; Με το Aspose.HTML μπορείτε να **render HTML as image**, να τροποποιήσετε το markup εν κινήσει, και ακόμη να **save HTML to ZIP** για μετέπειτα διανομή. Σε αυτό το tutorial θα περάσουμε από ένα πλήρες, εκτελέσιμο παράδειγμα που **applies font style HTML**, συγκεκριμένα **add bold to p** στοιχεία, πριν δημιουργήσουμε ένα αρχείο PNG. Στο τέλος θα έχετε μια μοναδική κλάση C# που κάνει τα πάντα, από τη φόρτωση μιας σελίδας μέχρι την αρχειοθέτηση των πόρων της. + +## Τι Θα Χρειαστεί + +- .NET 6.0 ή νεότερο (το API λειτουργεί και σε .NET Core) +- Aspose.HTML για .NET 6+ (πακέτο NuGet `Aspose.Html`) +- Βασική κατανόηση της σύνταξης C# (δεν απαιτούνται προχωρημένες έννοιες) + +Αυτό είναι όλο. Χωρίς εξωτερικά browsers, χωρίς phantomjs, μόνο καθαρός διαχειριζόμενος κώδικας. + +## Βήμα 1 – Φόρτωση του HTML Εγγράφου + +Αρχικά φέρνουμε το αρχείο πηγής (ή URL) σε ένα αντικείμενο `HTMLDocument`. Αυτό το βήμα είναι η βάση τόσο για **render html as image** όσο και για **save html to zip** αργότερα. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Γιατί είναι σημαντικό:* Η κλάση `HTMLDocument` αναλύει το markup, δημιουργεί ένα DOM και επιλύει τους συνδεδεμένους πόρους (CSS, εικόνες, γραμματοσειρές). Χωρίς ένα σωστό αντικείμενο εγγράφου δεν μπορείτε να χειριστείτε στυλ ή να αποδώσετε κάτι. + +## Βήμα 2 – Εφαρμογή Font Style HTML (Add Bold to p) + +Τώρα θα **apply font style HTML** επαναλαμβάνοντας κάθε στοιχείο `

` και ορίζοντας το `font-weight` σε bold. Αυτός είναι ο προγραμματιστικός τρόπος για **add bold to p** ετικέτες χωρίς να αγγίξετε το αρχικό αρχείο. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Συμβουλή:* Αν χρειάζεστε να κάνετε bold μόνο ένα υποσύνολο, αλλάξτε τον selector σε κάτι πιο συγκεκριμένο, π.χ., `"p.intro"`. + +## Βήμα 3 – Render HTML as Image (Convert HTML to PNG) + +Με το DOM έτοιμο, διαμορφώνουμε το `ImageRenderingOptions` και καλούμε το `RenderToImage`. Εδώ συμβαίνει η μαγεία του **convert html to png**. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Γιατί οι επιλογές είναι σημαντικές:* Ο καθορισμός σταθερού πλάτους/ύψους αποτρέπει το αποτέλεσμα να είναι πολύ μεγάλο, ενώ το antialiasing προσφέρει πιο ομαλή οπτική εμφάνιση. Μπορείτε επίσης να αλλάξετε το `options` σε `ImageFormat.Jpeg` αν προτιμάτε μικρότερο μέγεθος αρχείου. + +## Βήμα 4 – Save HTML to ZIP (Bundle Resources) + +Συχνά χρειάζεται να διανείμετε το αρχικό HTML μαζί με το CSS, τις εικόνες και τις γραμματοσειρές του. Το `ZipArchiveSaveOptions` του Aspose.HTML κάνει ακριβώς αυτό. Επίσης ενσωματώνουμε έναν προσαρμοσμένο `ResourceHandler` ώστε όλα τα εξωτερικά assets να γράφονται στον ίδιο φάκελο με το αρχείο. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Ακραία περίπτωση:* Αν το HTML σας αναφέρει απομακρυσμένες εικόνες που απαιτούν πιστοποίηση, ο προεπιλεγμένος handler θα αποτύχει. Σε αυτήν την περίπτωση μπορείτε να επεκτείνετε το `MyResourceHandler` για να εισάγετε HTTP headers. + +## Βήμα 5 – Συνδέστε Όλα σε Μία Μονάδα Converter Class + +Παρακάτω είναι η πλήρης, έτοιμη‑για‑εκτέλεση κλάση που ενώνει όλα τα προηγούμενα βήματα. Μπορείτε να την αντιγράψετε‑και‑επικολλήσετε σε μια εφαρμογή console, να καλέσετε το `Convert`, και να δείτε τα αρχεία να εμφανίζονται. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Αναμενόμενο Αποτέλεσμα + +Αφού εκτελέσετε το παραπάνω snippet, θα βρείτε δύο αρχεία στο `outputDirectory`: + +| Αρχείο | Περιγραφή | +|------|-------------| +| `page.png` | Μια απόδοση PNG 1200 × 800 του πηγαίου HTML, με κάθε παράγραφο εμφανιζόμενη σε **bold**. | +| `archive.zip` | Ένα πακέτο ZIP που περιέχει το αρχικό `input.html`, το CSS, τις εικόνες και τυχόν web‑fonts – ιδανικό για offline διανομή. | + +Μπορείτε να ανοίξετε το `page.png` σε οποιονδήποτε προβολέα εικόνων για να επαληθεύσετε ότι το bold styling εφαρμόστηκε, και να εξάγετε το `archive.zip` για να δείτε το αμετάβλητο HTML μαζί με τα assets του. + +## Συχνές Ερωτήσεις & Προβλήματα + +- **Τι γίνεται αν το HTML περιέχει JavaScript;** + Το Aspose.HTML **δεν** εκτελεί scripts κατά το rendering, έτσι το δυναμικό περιεχόμενο δεν θα εμφανιστεί. Για πλήρως αποδομένες σελίδες θα χρειαστείτε headless browser, αλλά για στατικά templates αυτή η προσέγγιση είναι πιο γρήγορη και ελαφριά. + +- **Μπορώ να αλλάξω τη μορφή εξόδου σε JPEG ή BMP;** + Ναι—αλλάξτε την ιδιότητα `ImageFormat` του `ImageRenderingOptions`, π.χ., `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Πρέπει να απελευθερώσω το `HTMLDocument` χειροκίνητα;** + Η κλάση υλοποιεί `IDisposable`. Σε μια υπηρεσία που τρέχει συνεχώς, τυλίξτε το σε block `using` ή καλέστε `document.Dispose()` όταν τελειώσετε. + +- **Πώς λειτουργεί ο προσαρμοσμένος `MyResourceHandler`;** + Λαμβάνει κάθε εξωτερικό πόρο (CSS, εικόνες, γραμματοσειρές) και τον γράφει στον φάκελο που καθορίζετε. Αυτό εξασφαλίζει ότι το ZIP περιέχει ακριβή αντίγραφο όλων των πόρων που αναφέρει το HTML. + +## Συμπέρασμα + +Τώρα έχετε μια συμπαγή, έτοιμη για παραγωγή λύση που **convert html to png**, **render html as image**, **save html to zip**, **apply font style html**, και **add bold to p**—όλα σε λίγες γραμμές C#. Ο κώδικας είναι αυτόνομος, λειτουργεί με .NET 6+, και μπορεί να ενσωματωθεί σε οποιαδήποτε υπηρεσία backend που χρειάζεται γρήγορα οπτικά στιγμιότυπα του web περιεχομένου. + +Έτοιμοι για το επόμενο βήμα; Δοκιμάστε να αλλάξετε το μέγεθος rendering, πειραματιστείτε με άλλες ιδιότητες CSS (όπως `font-family` ή `color`), ή ενσωματώστε αυτόν τον converter σε ένα endpoint ASP.NET Core που επιστρέφει το PNG κατόπιν αιτήματος. Οι δυνατότητες είναι ατελείωτες, και με το Aspose.HTML αποφεύγετε τις βαριές εξαρτήσεις από browsers. + +Αν αντιμετωπίσατε προβλήματα ή έχετε ιδέες για επεκτάσεις, αφήστε ένα σχόλιο παρακάτω. Καλό κώδικα! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/greek/net/html-document-manipulation/_index.md index c0ee23857..a744f33a2 100644 --- a/html/greek/net/html-document-manipulation/_index.md +++ b/html/greek/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ url: /el/net/html-document-manipulation/ Μάθετε να χρησιμοποιείτε το Aspose.HTML για .NET. Εισαγάγετε χώρο ονομάτων, συγχώνευση HTML με XML και βελτιώστε τις δεξιότητές σας στην ανάπτυξη ιστού με αυτόν τον περιεκτικό οδηγό. ### [Δημιουργήστε έγγραφα XPS από το XpsDevice σε .NET με Aspose.HTML](./generate-xps-documents-by-xpsdevice/) Ξεκλειδώστε τις δυνατότητες ανάπτυξης ιστού με το Aspose.HTML για .NET. Δημιουργήστε, μετατρέψτε και χειριστείτε εύκολα έγγραφα HTML. +### [Δημιουργία εγγράφου HTML C# – Οδηγός βήμα‑βήμα](./create-html-document-c-step-by-step-guide/) +Μάθετε πώς να δημιουργήσετε έγγραφο HTML σε C# με οδηγίες βήμα‑βήμα. ## Σύναψη diff --git a/html/greek/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/greek/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..b6dfe4c2d --- /dev/null +++ b/html/greek/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: Δημιουργήστε έγγραφο HTML με C# και μάθετε πώς να λαμβάνετε στοιχείο + με id, να εντοπίζετε στοιχείο με id, να αλλάζετε το στυλ του στοιχείου HTML και + να προσθέτετε έντονη πλάγια γραφή χρησιμοποιώντας το Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: el +og_description: Δημιουργήστε έγγραφο HTML C# και μάθετε αμέσως πώς να παίρνετε στοιχείο + με id, να εντοπίζετε στοιχείο με id, να αλλάζετε το στυλ του στοιχείου HTML και + να προσθέτετε έντονη πλάγια γραφή με σαφή παραδείγματα κώδικα. +og_title: Δημιουργία εγγράφου HTML C# – Πλήρης οδηγός προγραμματισμού +tags: +- Aspose.Html +- C# +- DOM manipulation +title: Δημιουργία εγγράφου HTML C# – Οδηγός βήμα‑προς‑βήμα +url: /el/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία Εγγράφου HTML C# – Οδηγός Βήμα‑βήμα + +Κάποτε χρειάστηκε να **δημιουργήσετε έγγραφο HTML C#** από το μηδέν και μετά να τροποποιήσετε την εμφάνιση μιας παραγράφου; Δεν είστε ο μόνος. Σε πολλά έργα αυτοματοποίησης web θα δημιουργήσετε ένα αρχείο HTML, θα εντοπίσετε ένα στοιχείο με το ID του και θα εφαρμόσετε στυλ—συχνά έντονο + πλάγιο—χωρίς ποτέ να ανοίξετε έναν περιηγητή. + +Σε αυτό το tutorial θα περάσουμε ακριβώς από αυτό: θα δημιουργήσουμε ένα έγγραφο HTML σε C#, **get element by id**, **locate element by id**, **change HTML element style**, και τέλος **add bold italic** χρησιμοποιώντας τη βιβλιοθήκη Aspose.Html. Στο τέλος θα έχετε ένα πλήρως εκτελέσιμο snippet που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο .NET. + +## Τι Θα Χρειαστείτε + +- .NET 6 ή νεότερο (ο κώδικας λειτουργεί επίσης σε .NET Framework 4.7+) +- Visual Studio 2022 (ή οποιονδήποτε επεξεργαστή προτιμάτε) +- Το πακέτο **Aspose.Html** NuGet (`Install-Package Aspose.Html`) + +Αυτό είναι όλο—χωρίς επιπλέον αρχεία HTML, χωρίς web server, μόνο λίγες γραμμές C#. + +## Create HTML Document C# – Αρχικοποίηση του Εγγράφου + +Πρώτα απ’ όλα: χρειάζεστε ένα ζωντανό αντικείμενο `HTMLDocument` ώστε η μηχανή Aspose.Html να μπορεί να δουλέψει. Σκεφτείτε το σαν το άνοιγμα ενός φρέσκου σημειωματάριου όπου θα γράψετε το markup σας. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Γιατί είναι σημαντικό:** Με το πέρασμα της ακατέργαστης συμβολοσειράς στο `HTMLDocument`, αποφεύγετε την ανάγνωση/εγγραφή αρχείων και κρατάτε τα πάντα στη μνήμη—ιδανικό για unit tests ή δημιουργία «on‑the‑fly». + +## Get Element by ID – Εύρεση της Παραγράφου + +Τώρα που υπάρχει το έγγραφο, πρέπει να **get element by id**. Το DOM API παρέχει τη μέθοδο `GetElementById`, η οποία επιστρέφει μια αναφορά `IElement` ή `null` αν το ID δεν υπάρχει. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Pro tip:** Παρόλο που το markup μας είναι μικρό, ένας έλεγχος για null αποτρέπει προβλήματα όταν η ίδια λογική επαναχρησιμοποιείται σε μεγαλύτερες, δυναμικές σελίδες. + +## Locate Element by ID – Εναλλακτική Προσέγγιση + +Μερικές φορές μπορεί να έχετε ήδη μια αναφορά στη ρίζα του εγγράφου και να προτιμάτε μια αναζήτηση τύπου query. Η χρήση CSS selectors (`QuerySelector`) είναι ένας άλλος τρόπος **locate element by id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **Πότε να χρησιμοποιήσετε ποιον;** Η `GetElementById` είναι ελαφρώς ταχύτερη επειδή κάνει άμεση αναζήτηση hash. Η `QuerySelector` ξεχωρίζει όταν χρειάζεστε σύνθετους selectors (π.χ., `div > p.highlight`). + +## Change HTML Element Style – Προσθήκη Έντονου Πλάγιου + +Με το στοιχείο στα χέρια, το επόμενο βήμα είναι να **change HTML element style**. Η Aspose.Html εκθέτει ένα αντικείμενο `Style` όπου μπορείτε να ρυθμίσετε ιδιότητες CSS ή να χρησιμοποιήσετε την χρήσιμη απαρίθμηση `WebFontStyle` για να εφαρμόσετε πολλαπλά χαρακτηριστικά γραμματοσειράς ταυτόχρονα. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Αυτή η μοναδική γραμμή θέτει το `font-weight` του στοιχείου σε `bold` και το `font-style` σε `italic`. Στο παρασκήνιο η Aspose.Html μετατρέπει την enum στην κατάλληλη συμβολοσειρά CSS. + +### Πλήρες Παράδειγμα Λειτουργίας + +Συνδυάζοντας όλα τα κομμάτια παίρνουμε ένα συμπαγές, αυτόνομο πρόγραμμα που μπορείτε να μεταγλωττίσετε και να τρέξετε αμέσως: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Αναμενόμενο αποτέλεσμα** + +``` +Rendered HTML: +

Hello world

+``` + +Η ετικέτα `

` τώρα περιέχει ένα ενσωματωμένο χαρακτηριστικό `style` που κάνει το κείμενο τόσο έντονο όσο και πλάγιο—ακριβώς αυτό που θέλαμε. + +## Edge Cases & Common Pitfalls + +| Κατάσταση | Σε τι Πρέπει να Προσέξετε | Πώς να το Διαχειριστείτε | +|-----------|---------------------------|--------------------------| +| **Το ID δεν υπάρχει** | Η `GetElementById` επιστρέφει `null`. | Ρίξτε εξαίρεση ή επιστρέψτε ένα προεπιλεγμένο στοιχείο. | +| **Πολλά στοιχεία μοιράζονται το ίδιο ID** | Η προδιαγραφή HTML απαιτεί μοναδικά IDs, αλλά στην πράξη συμβαίνουν παραβιάσεις. | Η `GetElementById` επιστρέφει το πρώτο αποτέλεσμα· σκεφτείτε τη χρήση `QuerySelectorAll` αν χρειάζεται να χειριστείτε διπλότυπα. | +| **Σύγκρουση στυλ** | Τα υπάρχοντα inline στυλ μπορεί να αντικατασταθούν. | Προσθέστε στο αντικείμενο `Style` αντί να ορίσετε ολόκληρη τη συμβολοσειρά `style`: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Απόδοση σε περιηγητή** | Κάποιοι browsers αγνοούν το `WebFontStyle` αν το στοιχείο έχει ήδη κλάση CSS με υψηλότερη ειδικότητα. | Χρησιμοποιήστε `!important` μέσω `paragraph.Style.SetProperty("font-weight", "bold", "important");` αν χρειαστεί. | + +## Pro Tips για Πραγματικά Έργα + +- **Κρατήστε στην μνήμη το έγγραφο** αν επεξεργάζεστε πολλά στοιχεία· η δημιουργία νέου `HTMLDocument` για κάθε μικρό κομμάτι μπορεί να μειώσει την απόδοση. +- **Συνδυάστε αλλαγές στυλ** σε μια ενιαία συναλλαγή `Style` για να αποφύγετε πολλαπλές επανασχεδιάσεις DOM. +- **Εκμεταλλευτείτε τη μηχανή απόδοσης της Aspose.Html** για να εξάγετε το τελικό έγγραφο ως PDF ή εικόνα—ιδανικό για εργαλεία αναφοράς. + +## Οπτική Επιβεβαίωση (Προαιρετικό) + +Αν προτιμάτε να δείτε το αποτέλεσμα σε περιηγητή, μπορείτε να αποθηκεύσετε τη δημιουργημένη συμβολοσειρά σε αρχείο `.html`: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Ανοίξτε το `output.html` και θα δείτε το **Hello world** εμφανιζόμενο σε έντονο + πλάγιο. + +![Create HTML Document C# example showing bold italic paragraph](/images/create-html-document-csharp.png "Create HTML Document C# – rendered output") + +*Κείμενο alt: Create HTML Document C# – rendered output with bold italic text.* + +## Συμπέρασμα + +Μόλις **δημιουργήσαμε ένα έγγραφο HTML C#**, **got element by id**, **located element by id**, **changed HTML element style**, και τέλος **added bold italic**—όλα με λίγες γραμμές κώδικα χρησιμοποιώντας την Aspose.Html. Η προσέγγιση είναι απλή, λειτουργεί σε οποιοδήποτε περιβάλλον .NET και κλιμακώνεται σε μεγαλύτερες επεμβάσεις DOM. + +Έτοιμοι για το επόμενο βήμα; Δοκιμάστε να αντικαταστήσετε το `WebFontStyle` με άλλες enum τιμές όπως `Underline` ή συνδυάστε πολλαπλά στυλ χειροκίνητα. Ή πειραματιστείτε με τη φόρτωση εξωτερικού αρχείου HTML και την εφαρμογή της ίδιας τεχνικής σε εκατοντάδες στοιχεία. Ο ουρανός είναι το όριο, και τώρα έχετε μια σταθερή βάση για να χτίσετε πάνω της. + +Καλή προγραμματιστική! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/greek/net/html-extensions-and-conversions/_index.md b/html/greek/net/html-extensions-and-conversions/_index.md index 013b0ec4b..0462a947a 100644 --- a/html/greek/net/html-extensions-and-conversions/_index.md +++ b/html/greek/net/html-extensions-and-conversions/_index.md @@ -41,6 +41,8 @@ url: /el/net/html-extensions-and-conversions/ Μετατρέψτε HTML σε PDF χωρίς κόπο με το Aspose.HTML για .NET. Ακολουθήστε τον οδηγό βήμα προς βήμα και απελευθερώστε τη δύναμη της μετατροπής HTML σε PDF. ### [Δημιουργία PDF από HTML – Οδηγός βήμα‑βήμα C#](./create-pdf-from-html-c-step-by-step-guide/) Δημιουργήστε PDF από HTML με C# χρησιμοποιώντας το Aspose.HTML. Οδηγός βήμα‑βήμα για γρήγορη και εύκολη υλοποίηση. +### [Δημιουργία PDF από HTML με Aspose – Οδηγός βήμα‑βήμα C#](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Μάθετε πώς να δημιουργήσετε PDF από HTML χρησιμοποιώντας το Aspose με C# σε έναν πλήρη βήμα‑βήμα οδηγό. ### [Μετατρέψτε το EPUB σε Εικόνα στο .NET με το Aspose.HTML](./convert-epub-to-image/) Μάθετε πώς να μετατρέπετε το EPUB σε εικόνες χρησιμοποιώντας το Aspose.HTML για .NET. Βήμα προς βήμα μάθημα με παραδείγματα κώδικα και προσαρμόσιμες επιλογές. ### [Μετατροπή EPUB σε PDF σε .NET με Aspose.HTML](./convert-epub-to-pdf/) @@ -65,15 +67,22 @@ url: /el/net/html-extensions-and-conversions/ Μάθετε πώς να μετατρέπετε HTML σε TIFF με το Aspose.HTML για .NET. Ακολουθήστε τον βήμα προς βήμα οδηγό μας για αποτελεσματική βελτιστοποίηση περιεχομένου ιστού. ### [Μετατροπή HTML σε XPS σε .NET με Aspose.HTML](./convert-html-to-xps/) Ανακαλύψτε τη δύναμη του Aspose.HTML για .NET: Μετατρέψτε HTML σε XPS χωρίς κόπο. Περιλαμβάνονται προαπαιτούμενα, οδηγός βήμα προς βήμα και συχνές ερωτήσεις. +### [Μετατροπή HTML σε Εικόνα σε C# – Πλήρης Οδηγός](./convert-html-to-image-in-c-complete-guide/) +Μάθετε πώς να μετατρέπετε HTML σε εικόνα με C# χρησιμοποιώντας το Aspose.HTML – βήμα‑βήμα οδηγός. ### [Πώς να συμπιέσετε 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-as-zip-in-c-complete-guide-with-custom-storage/) +Μάθετε πώς να αποθηκεύετε HTML σε αρχείο ZIP με C# χρησιμοποιώντας προσαρμοσμένη αποθήκευση στο Aspose.HTML. ### [Αποθήκευση HTML σε ZIP σε C# – Πλήρες Παράδειγμα Εντός Μνήμης](./save-html-to-zip-in-c-complete-in-memory-example/) Μάθετε πώς να αποθηκεύετε HTML σε αρχείο ZIP με C# χρησιμοποιώντας πλήρες παράδειγμα εντός μνήμης. +### [Πώς να συμπιέσετε HTML με Aspose.HTML – Πλήρης Οδηγός](./how-to-zip-html-with-aspose-html-complete-guide/) +Μάθετε πώς να δημιουργείτε αρχείο ZIP από HTML χρησιμοποιώντας το Aspose.HTML σε .NET – βήμα‑βήμα οδηγός. + ## Σύναψη Συμπερασματικά, οι επεκτάσεις και οι μετατροπές HTML είναι βασικά στοιχεία της σύγχρονης ανάπτυξης ιστού. Το Aspose.HTML για .NET απλοποιεί τη διαδικασία και το καθιστά προσβάσιμο σε προγραμματιστές όλων των επιπέδων. Ακολουθώντας τα σεμινάρια μας, θα είστε σε καλό δρόμο για να γίνετε ικανός προγραμματιστής ιστού με ευρύ σύνολο δεξιοτήτων. diff --git a/html/greek/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/greek/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..b8fc4c6ac --- /dev/null +++ b/html/greek/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Μετατρέψτε το HTML σε εικόνα χρησιμοποιώντας το Aspose.HTML σε C#. Μάθετε + πώς να αποθηκεύετε το HTML ως PNG, να ορίζετε το μέγεθος απόδοσης της εικόνας και + να γράφετε την εικόνα σε αρχείο σε λίγα μόνο βήματα. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: el +og_description: Μετατρέψτε το HTML σε εικόνα γρήγορα. Αυτός ο οδηγός δείχνει πώς να + αποθηκεύσετε το HTML ως PNG, να ορίσετε το μέγεθος απόδοσης της εικόνας και να γράψετε + την εικόνα σε αρχείο με το Aspose.HTML. +og_title: Μετατροπή HTML σε Εικόνα σε C# – Οδηγός Βήμα‑προς‑Βήμα +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Μετατροπή HTML σε Εικόνα με C# – Πλήρης Οδηγός +url: /el/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Μετατροπή HTML σε Εικόνα σε C# – Πλήρης Οδηγός + +Έχετε χρειαστεί ποτέ να **μετατρέψετε HTML σε εικόνα** για μια μικρογραφία πίνακα ελέγχου, μια προεπισκόπηση email ή μια αναφορά PDF; Είναι ένα σενάριο που εμφανίζεται πιο συχνά από όσο θα περιμένατε, ειδικά όταν δουλεύετε με δυναμικό web περιεχόμενο που πρέπει να ενσωματωθεί κάπου αλλού. + +Τα καλά νέα; Με το Aspose.HTML μπορείτε να **μετατρέψετε HTML σε εικόνα** με λίγες μόνο γραμμές κώδικα, και θα μάθετε επίσης πώς να *αποθηκεύσετε HTML ως PNG*, να ελέγξετε τις διαστάσεις εξόδου και να *γράψετε εικόνα σε αρχείο* χωρίς κόπο. + +Σε αυτό το tutorial θα περάσουμε από όλα όσα χρειάζεστε: από τη φόρτωση μιας απομακρυσμένης σελίδας μέχρι τη ρύθμιση του μεγέθους απόδοσης, και τέλος την αποθήκευση του αποτελέσματος ως αρχείο PNG στον δίσκο. Χωρίς εξωτερικά εργαλεία, χωρίς περίπλοκες εντολές γραμμής εντολών — μόνο καθαρός κώδικας C# που μπορείτε να ενσωματώσετε σε οποιοδήποτε .NET project. + +## Τι Θα Μάθετε + +- Πώς να **αποδώσετε ιστοσελίδα σε PNG** χρησιμοποιώντας την κλάση `HTMLDocument` του Aspose.HTML. +- Τα ακριβή βήματα για **ρύθμιση μεγέθους εικόνας κατά την απόδοση** ώστε η έξοδος να ταιριάζει με τις απαιτήσεις του layout σας. +- Τρόπους για **γραφή εικόνας σε αρχείο** με ασφάλεια, διαχειριζόμενοι streams και διαδρομές αρχείων. +- Συμβουλές για την αντιμετώπιση κοινών προβλημάτων όπως λείπουν γραμματοσειρές ή χρονικά όρια δικτύου. + +### Προαπαιτούμενα + +- .NET 6.0 ή νεότερο (το API λειτουργεί και με .NET Framework, αλλά προτείνεται .NET 6+). +- Αναφορά στο πακέτο NuGet **Aspose.HTML for .NET** (`Aspose.Html`). +- Βασική εξοικείωση με C# και async/await (προαιρετικό αλλά χρήσιμο). + +Αν έχετε ήδη αυτά, είστε έτοιμοι να ξεκινήσετε τη μετατροπή HTML σε εικόνα αμέσως. + +## Βήμα 1: Φόρτωση της Ιστοσελίδας – Η Βάση για τη Μετατροπή HTML σε Εικόνα + +Πριν μπορέσει να γίνει οποιαδήποτε απόδοση, χρειάζεστε ένα αντικείμενο `HTMLDocument` που να αντιπροσωπεύει τη σελίδα που θέλετε να καταγράψετε. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Γιατί είναι σημαντικό:* Το `HTMLDocument` αναλύει το HTML, επιλύει το CSS και δημιουργεί το DOM. Αν το έγγραφο δεν φορτωθεί (π.χ. πρόβλημα δικτύου), η επόμενη απόδοση θα παράγει κενή εικόνα. Επαληθεύστε πάντα ότι το URL είναι προσβάσιμο πριν προχωρήσετε. + +## Βήμα 2: Ρύθμιση Μεγέθους Εικόνας – Έλεγχος Πλάτους, Ύψους και Ποιότητας + +Το Aspose.HTML σας επιτρέπει να ρυθμίσετε ακριβώς τις διαστάσεις εξόδου με το `ImageRenderingOptions`. Εδώ **ρυθμίζετε το μέγεθος εικόνας κατά την απόδοση** ώστε να ταιριάζει με το επιθυμητό layout. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Συμβουλή:* Αν παραλείψετε τα `Width` και `Height`, το Aspose.HTML θα χρησιμοποιήσει το ενδογενές μέγεθος της σελίδας, το οποίο μπορεί να είναι απρόβλεπτο για responsive σχεδιασμούς. Ορίζοντας ρητές διαστάσεις εξασφαλίζετε ότι το **save HTML as PNG** θα εμφανίζεται ακριβώς όπως το θέλετε. + +## Βήμα 3: Γραφή Εικόνας σε Αρχείο – Αποθήκευση του Rendered PNG + +Τώρα που το έγγραφο είναι έτοιμο και οι επιλογές απόδοσης έχουν οριστεί, μπορείτε τελικά να **γράψετε εικόνα σε αρχείο**. Η χρήση ενός `FileStream` εγγυάται ότι το αρχείο δημιουργείται με ασφάλεια, ακόμη και αν ο φάκελος δεν υπάρχει ακόμη. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +Αφού εκτελεστεί αυτό το τμήμα, θα βρείτε το `page.png` στην τοποθεσία που καθορίσατε. Μόλις **αποδώσετε ιστοσελίδα σε PNG** και την αποθηκεύσατε στον δίσκο με μια απλή, άμεση λειτουργία. + +### Αναμενόμενο Αποτέλεσμα + +Ανοίξτε το `C:\Temp\page.png` με οποιονδήποτε προβολέα εικόνων. Θα πρέπει να δείτε μια πιστή λήψη του `https://example.com`, αποδομένη σε 1024 × 768 pixels με ομαλές άκρες χάρη στο antialiasing. Αν η σελίδα περιέχει δυναμικό περιεχόμενο (π.χ. στοιχεία που δημιουργούνται με JavaScript), θα καταγραφούν εφόσον το DOM είναι πλήρως φορτωμένο πριν την απόδοση. + +## Βήμα 4: Διαχείριση Ακραίων Περιπτώσεων – Γραμματοσειρές, Αυθεντικοποίηση και Μεγάλες Σελίδες + +Ενώ η βασική ροή λειτουργεί για τις περισσότερες δημόσιες ιστοσελίδες, οι πραγματικές συνθήκες συχνά φέρνουν απρόοπτα: + +| Situation | What to Do | +|-----------|------------| +| **Custom fonts not loading** | Ενσωματώστε τα αρχεία γραμματοσειράς τοπικά και ορίστε `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Pages behind authentication** | Χρησιμοποιήστε την υπερφόρτωση του `HTMLDocument` που δέχεται `HttpWebRequest` με cookies ή tokens. | +| **Very tall pages** | Αυξήστε το `Height` ή ενεργοποιήστε το `PageScaling` στο `ImageRenderingOptions` για να αποφύγετε την αποκοπή. | +| **Memory usage spikes** | Κάντε απόδοση σε τμήματα χρησιμοποιώντας την υπερφόρτωση `RenderToImage` που δέχεται περιοχή `Rectangle`. | + +Αντιμετωπίζοντας αυτές τις λεπτομέρειες της *write image to file* εξασφαλίζετε ότι η **convert html to image** διαδικασία σας παραμένει αξιόπιστη σε παραγωγικό περιβάλλον. + +## Βήμα 5: Πλήρες Παράδειγμα – Έτοιμο για Αντιγραφή‑Επικόλληση + +Παρακάτω βρίσκεται ολόκληρο το πρόγραμμα, έτοιμο για μεταγλώττιση. Περιλαμβάνει όλα τα βήματα, τον χειρισμό σφαλμάτων και σχόλια που χρειάζεστε. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Τρέξτε αυτό το πρόγραμμα και θα δείτε το μήνυμα επιβεβαίωσης στην κονσόλα. Το αρχείο PNG θα είναι ακριβώς ό,τι θα περιμένατε αν **αποδώσετε ιστοσελίδα σε PNG** χειροκίνητα σε έναν περιηγητή και τραβήξετε screenshot — μόνο πιο γρήγορα και πλήρως αυτοματοποιημένα. + +## Συχνές Ερωτήσεις + +**Q: Μπορώ να μετατρέψω ένα τοπικό αρχείο HTML αντί για URL;** +Απολύτως. Απλώς αντικαταστήστε το URL με διαδρομή αρχείου: `new HTMLDocument(@"C:\myPage.html")`. + +**Q: Χρειάζομαι άδεια για το Aspose.HTML;** +Μια δωρεάν άδεια αξιολόγησης λειτουργεί για ανάπτυξη και δοκιμές. Για παραγωγή, αγοράστε άδεια ώστε να αφαιρεθεί το υδατογράφημα αξιολόγησης. + +**Q: Τι γίνεται αν η σελίδα χρησιμοποιεί JavaScript για φόρτωση περιεχομένου μετά το αρχικό φορτίο;** +Το Aspose.HTML εκτελεί JavaScript συγχρονισμένα κατά την ανάλυση, αλλά σενάρια που τρέχουν πολύ χρόνο μπορεί να χρειάζονται καθυστέρηση. Μπορείτε να χρησιμοποιήσετε `HTMLDocument.WaitForReadyState` πριν από την απόδοση. + +## Συμπέρασμα + +Τώρα έχετε μια ολοκληρωμένη, άκρη‑σε‑άκρη λύση για **convert HTML to image** σε C#. Ακολουθώντας τα παραπάνω βήματα μπορείτε να **save HTML as PNG**, να **set image size rendering** με ακρίβεια, και να **write image to file** με σιγουριά σε οποιοδήποτε περιβάλλον Windows ή Linux. + +Από απλές λήψεις οθόνης μέχρι αυτοματοποιημένη δημιουργία αναφορών, αυτή η τεχνική κλιμακώνεται άψογα. Στη συνέχεια, δοκιμάστε άλλες μορφές εξόδου όπως JPEG ή BMP, ή ενσωματώστε τον κώδικα σε ένα ASP.NET Core API που επιστρέφει το PNG απευθείας στους καλούντες. Οι δυνατότητες είναι πρακτικά απεριόριστες. + +Καλή προγραμματιστική, και οι αποδομένες εικόνες σας να είναι πάντα pixel‑perfect! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/greek/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..c9eb83c4b --- /dev/null +++ b/html/greek/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-03-21 +description: Δημιουργήστε PDF από HTML γρήγορα χρησιμοποιώντας το Aspose HTML. Μάθετε + πώς να αποδίδετε HTML σε PDF, να μετατρέπετε HTML σε PDF και πώς να χρησιμοποιείτε + το Aspose σε ένα σύντομο οδηγό. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: el +og_description: Δημιουργήστε PDF από HTML με το Aspose σε C#. Αυτός ο οδηγός δείχνει + πώς να αποδίδετε HTML σε PDF, να μετατρέπετε HTML σε PDF και πώς να χρησιμοποιείτε + το Aspose αποτελεσματικά. +og_title: Δημιουργία PDF από HTML – Πλήρης οδηγός Aspose C# +tags: +- Aspose +- C# +- PDF generation +title: Δημιουργία PDF από HTML με το Aspose – Οδηγός C# βήμα‑βήμα +url: /el/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία PDF από HTML με Aspose – Οδηγός Βήμα‑βήμα C# Guide + +Έχετε χρειαστεί ποτέ να **create PDF from HTML** αλλά δεν ήσασταν σίγουροι ποια βιβλιοθήκη θα σας δώσει αποτελέσματα pixel‑perfect; Δεν είστε μόνοι. Πολλοί προγραμματιστές συναντούν δυσκολίες όταν προσπαθούν να μετατρέψουν ένα κομμάτι web σε εκτυπώσιμο έγγραφο, μόνο για να καταλήξουν με θολό κείμενο ή σπασμένες διατάξεις. + +Τα καλά νέα είναι ότι το Aspose HTML κάνει όλη τη διαδικασία χωρίς κόπο. Σε αυτό το tutorial θα περάσουμε από τον ακριβή κώδικα που χρειάζεστε για **render HTML to PDF**, θα εξετάσουμε γιατί κάθε ρύθμιση είναι σημαντική, και θα σας δείξουμε πώς να **convert HTML to PDF** χωρίς κρυφά κόλπα. Στο τέλος, θα ξέρετε **how to use Aspose** για αξιόπιστη δημιουργία PDF σε οποιοδήποτε έργο .NET. + +## Προαπαιτούμενα – Τι Θα Χρειαστείτε Πριν Ξεκινήσετε + +- **.NET 6.0 ή νεότερο** (το παράδειγμα λειτουργεί επίσης σε .NET Framework 4.7+) +- **Visual Studio 2022** ή οποιοδήποτε IDE που υποστηρίζει C# +- **Aspose.HTML for .NET** πακέτο NuGet (δωρεάν δοκιμή ή έκδοση με άδεια) +- Βασική κατανόηση της σύνταξης C# (δεν απαιτείται βαθιά γνώση PDF) + +Αν έχετε αυτά, είστε έτοιμοι να ξεκινήσετε. Διαφορετικά, κατεβάστε το τελευταίο .NET SDK και εγκαταστήστε το πακέτο NuGet με: + +```bash +dotnet add package Aspose.HTML +``` + +Αυτή η μοναδική γραμμή φέρνει όλα όσα χρειάζεστε για τη μετατροπή **aspose html to pdf**. + +## Βήμα 1: Ρυθμίστε το Έργο σας για Δημιουργία PDF από HTML + +Το πρώτο που κάνετε είναι να δημιουργήσετε μια νέα εφαρμογή κονσόλας (ή να ενσωματώσετε τον κώδικα σε υπάρχουσα υπηρεσία). Εδώ είναι ένα ελάχιστο σκελετό `Program.cs`: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** Αν δείτε `Aspise.Html.Rendering.Text` σε παλαιότερα δείγματα, αντικαταστήστε το με `Aspose.Html.Rendering.Text`. Το τυπογραφικό λάθος θα προκαλέσει σφάλμα μεταγλώττισης. + +Η σωστή χρήση των namespaces εξασφαλίζει ότι ο μεταγλωττιστής μπορεί να εντοπίσει την κλάση **TextOptions** που θα χρειαστούμε αργότερα. + +## Βήμα 2: Δημιουργία του Εγγράφου HTML (Render HTML to PDF) + +Τώρα δημιουργούμε το πηγαίο HTML. Το Aspose σας επιτρέπει να περάσετε μια ακατέργαστη συμβολοσειρά, μια διαδρομή αρχείου ή ακόμη και ένα URL. Για αυτή τη demo θα το κρατήσουμε απλό: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Γιατί να περάσετε μια συμβολοσειρά; Αποφεύγει την I/O του συστήματος αρχείων, επιταχύνει τη μετατροπή και εγγυάται ότι το HTML που βλέπετε στον κώδικα είναι ακριβώς αυτό που θα αποδοθεί. Αν προτιμάτε τη φόρτωση από αρχείο, απλώς αντικαταστήστε το όρισμα του κατασκευαστή με ένα URI αρχείου. + +## Βήμα 3: Λεπτομερής Ρύθμιση Απόδοσης Κειμένου (Convert HTML to PDF with Better Quality) + +Η απόδοση του κειμένου συχνά καθορίζει αν το PDF σας φαίνεται καθαρό ή θολό. Το Aspose προσφέρει την κλάση `TextOptions` που σας επιτρέπει να ενεργοποιήσετε το sub‑pixel hinting—απαραίτητο για έξοδο υψηλής DPI. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Η ενεργοποίηση του `UseHinting` είναι ιδιαίτερα χρήσιμη όταν το πηγαίο HTML περιέχει προσαρμοσμένες γραμματοσειρές ή μικρά μεγέθη γραμματοσειράς. Χωρίς αυτό, μπορεί να παρατηρήσετε σκαλιστές άκρες στο τελικό PDF. + +## Βήμα 4: Συγκόλληση των Ρυθμίσεων Κειμένου στη Διαμόρφωση Απόδοσης PDF (How to Use Aspose) + +Στη συνέχεια, συνδέουμε αυτές τις ρυθμίσεις κειμένου με τον PDF renderer. Εδώ είναι που το **aspose html to pdf** ξεχωρίζει—όλα από το μέγεθος σελίδας έως τη συμπίεση μπορούν να ρυθμιστούν. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Μπορείτε να παραλείψετε το `PageSetup` αν σας αρκεί το προεπιλεγμένο μέγεθος A4. Το βασικό συμπέρασμα είναι ότι το αντικείμενο `TextOptions` βρίσκεται μέσα στο `PdfRenderingOptions`, και έτσι λέτε στο Aspose *πώς* να αποδώσει το κείμενο. + +## Βήμα 5: Απόδοση του HTML και Αποθήκευση του PDF (Convert HTML to PDF) + +Τέλος, μεταφέρουμε την έξοδο σε αρχείο. Η χρήση ενός μπλοκ `using` εγγυάται ότι το χειριστήριο του αρχείου κλείνει σωστά, ακόμη και αν προκύψει εξαίρεση. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Όταν εκτελέσετε το πρόγραμμα, θα βρείτε το `output.pdf` δίπλα στο εκτελέσιμο. Ανοίξτε το και θα δείτε έναν καθαρό τίτλο και παράγραφο—ακριβώς όπως ορίζονται στη συμβολοσειρά HTML. + +### Αναμενόμενο Αποτέλεσμα + +![δημιουργία pdf από html παράδειγμα εξόδου](https://example.com/images/pdf-output.png "δημιουργία pdf από html παράδειγμα εξόδου") + +*Το στιγμιότυπο δείχνει το παραγόμενο PDF με τον τίτλο “Hello, Aspose!” αποδομένο οξυρά χάρη στο text hinting.* + +## Συχνές Ερωτήσεις & Ακραίες Περιπτώσεις + +### 1. Τι γίνεται αν το HTML μου αναφέρεται σε εξωτερικούς πόρους (εικόνες, CSS); + +Το Aspose επιλύει σχετικές URL βάσει του base URI του εγγράφου. Αν τροφοδοτείτε μια ακατέργαστη συμβολοσειρά, ορίστε το base URI χειροκίνητα: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Τώρα οποιοδήποτε `` θα αναζητηθεί σχετικά με το `C:/MyProject/`. + +### 2. Πώς να ενσωματώσω γραμματοσειρές που δεν είναι εγκατεστημένες στον διακομιστή; + +Προσθέστε ένα μπλοκ ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Βήμα 4: Διαμόρφωση Επιλογών Αποθήκευσης για Χρήση της Προσαρμοσμένης Αποθήκευσης + +`HtmlSaveOptions` μας επιτρέπει να πούμε στο Aspose να πακετάρει τα πάντα σε ένα αρχείο ZIP. Η ιδιότητα `OutputStorage` (παραδοσιακή) λαμβάνει το παράδειγμά μας `MyStorage`. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Σημείωση:** Στο Aspose HTML 23.9+ η ιδιότητα ονομάζεται `OutputStorage` αλλά είναι σημειωμένη ως παρωχημένη. Η σύγχρονη εναλλακτική είναι `ZipOutputStorage`. Ο παρακάτω κώδικας λειτουργεί και με τις δύο επειδή η διεπαφή είναι η ίδια. + +### Βήμα 5: Αποθήκευση του Εγγράφου ως Αρχείο ZIP + +Επιλέξτε έναν φάκελο προορισμού (ή stream) και αφήστε το Aspose να κάνει τη βαριά δουλειά. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Όταν το πρόγραμμα ολοκληρωθεί, θα βρείτε το `output.zip` που περιέχει: + +* `index.html` – το κύριο έγγραφο. +* Οποιεσδήποτε ενσωματωμένες εικόνες, αρχεία CSS ή scripts (αν το HTML σας τα ανέφερε). + +Μπορείτε να ανοίξετε το ZIP με οποιονδήποτε διαχειριστή αρχείων για να επαληθεύσετε τη δομή. + +--- + +## Επαλήθευση του Αποτελέσματος (Προαιρετικό) + +Αν θέλετε να ελέγξετε προγραμματιστικά το αρχείο χωρίς να το εξάγετε στο δίσκο: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Τυπική έξοδος: + +``` +- index.html (452 bytes) +``` + +## Συχνές Ερωτήσεις & Ακραίες Περιπτώσεις + +| Ερώτηση | Απάντηση | +|----------|--------| +| **Τι γίνεται αν χρειαστεί να γράψω το ZIP απευθείας σε ροή απόκρισης;** | Επιστρέψτε το `MemoryStream` που λαμβάνετε από το `MyStorage` μετά το `document.Save`. Μετατρέψτε το σε `byte[]` και γράψτε το στο `HttpResponse.Body`. | +| **Το HTML μου αναφέρει εξωτερικά URLs—θα ληφθούν;** | Όχι. Το Aspose πακετάρει μόνο πόρους που είναι *ενσωματωμένοι* (π.χ., `` ή τοπικά αρχεία). Για απομακρυσμένα στοιχεία πρέπει πρώτα να τα κατεβάσετε και να προσαρμόσετε το markup. | +| **Η ιδιότητα `OutputStorage` είναι σημειωμένη ως παρωχημένη—να την αγνοήσω;** | Λειτουργεί ακόμα, αλλά η νεότερη `ZipOutputStorage` προσφέρει το ίδιο API με διαφορετικό όνομα. Αντικαταστήστε το `OutputStorage` με `ZipOutputStorage` αν θέλετε μια κατασκευή χωρίς προειδοποιήσεις. | +| **Μπορώ να κρυπτογραφήσω το ZIP;** | Ναι. Μετά την αποθήκευση, ανοίξτε το αρχείο με `System.IO.Compression.ZipArchive` και ορίστε κωδικό πρόσβασης χρησιμοποιώντας βιβλιοθήκες τρίτων όπως το `SharpZipLib`. Το ίδιο το Aspose δεν παρέχει κρυπτογράφηση. | + +## Πλήρες Παράδειγμα Εργασίας (Αντιγραφή‑Επικόλληση) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Τρέξτε το πρόγραμμα, ανοίξτε το `output.zip`, και θα δείτε ένα μόνο αρχείο `index.html` που εμφανίζει την επικεφαλίδα “Hello from ZIP!” όταν ανοίγεται σε πρόγραμμα περιήγησης. + +## Συμπέρασμα + +Τώρα ξέρετε **πώς να αποθηκεύετε HTML ως ZIP** σε C# χρησιμοποιώντας μια **προσαρμοσμένη κλάση αποθήκευσης**, πώς να **εξάγετε HTML σε ZIP**, και πώς να **δημιουργήσετε ένα HTML zip αρχείο** έτοιμο για διανομή. Το μοτίβο είναι ευέλικτο — αντικαταστήστε το `MemoryStream` με ένα cloud stream, προσθέστε κρυπτογράφηση ή ενσωματώστε το σε ένα web API που επιστρέφει το ZIP κατόπιν ζήτησης. Ο ουρανός είναι το όριο όταν συνδυάζετε τις δυνατότητες ZIP του Aspose.HTML με τη δική σας λογική αποθήκευσης. + +Έτοιμοι για το επόμενο βήμα; Δοκιμάστε να τροφοδοτήσετε μια πλήρη ιστοσελίδα με εικόνες και στυλ, ή συνδέστε την αποθήκευση με το Azure Blob Storage για να παρακάμψετε εντελώς το τοπικό σύστημα αρχείων. Ο ουρανός είναι το όριο όταν συνδυάζετε τις δυνατότητες ZIP του Aspose.HTML με τη δική σας λογική αποθήκευσης. + +Καλό προγραμματισμό, και να είναι πάντα τα αρχεία σας τακτοποιημένα! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hindi/net/generate-jpg-and-png-images/_index.md b/html/hindi/net/generate-jpg-and-png-images/_index.md index b35cbb62e..71573cf12 100644 --- a/html/hindi/net/generate-jpg-and-png-images/_index.md +++ b/html/hindi/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ HTML दस्तावेज़ों में हेरफेर करने DOCX फ़ाइलों को PNG या JPG में परिवर्तित करते समय एंटीएलियासिंग को सक्षम करने के चरणों को जानें। ### [DOCX को PNG में परिवर्तित करें – ZIP आर्काइव बनाएं C# ट्यूटोरियल](./convert-docx-to-png-create-zip-archive-c-tutorial/) C# में DOCX फ़ाइलों को PNG छवियों में बदलें और उन्हें ZIP आर्काइव में संकलित करना सीखें। चरण-दर-चरण मार्गदर्शिका। +### [HTML को PNG में परिवर्तित करें – ZIP निर्यात के साथ पूर्ण C# गाइड](./convert-html-to-png-full-c-guide-with-zip-export/) +C# में HTML को PNG में बदलें और परिणाम को ZIP फ़ाइल में निर्यात करना सीखें। चरण-दर-चरण मार्गदर्शिका। ## निष्कर्ष diff --git a/html/hindi/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/hindi/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..43b9bba58 --- /dev/null +++ b/html/hindi/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: HTML को PNG में बदलें और HTML को छवि के रूप में रेंडर करें जबकि HTML + को ZIP में सहेजें। कुछ ही चरणों में फ़ॉन्ट स्टाइल लागू करना और p तत्वों में बोल्ड + जोड़ना सीखें। +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: hi +og_description: HTML को जल्दी से PNG में बदलें। यह गाइड दिखाता है कि HTML को छवि के + रूप में कैसे रेंडर करें, HTML को ZIP में कैसे सहेजें, HTML पर फ़ॉन्ट स्टाइल कैसे + लागू करें और p तत्वों में बोल्ड कैसे जोड़ें। +og_title: HTML को PNG में बदलें – पूर्ण C# ट्यूटोरियल +tags: +- Aspose +- C# +title: HTML को PNG में बदलें – ZIP निर्यात के साथ पूर्ण C# गाइड +url: /hi/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convert HTML to PNG – Full C# Guide with ZIP Export + +क्या आपको कभी **HTML को PNG में बदलने** की ज़रूरत पड़ी है लेकिन यह नहीं पता था कि कौन‑सा लाइब्रेरी हेडलेस ब्राउज़र के बिना यह कर सके? आप अकेले नहीं हैं। कई प्रोजेक्ट्स—ईमेल थंबनेल, डॉक्यूमेंटेशन प्रीव्यू, या क्विक‑लुक इमेज—में वेब पेज को स्थिर चित्र में बदलना एक वास्तविक आवश्यकता है। + +अच्छी खबर? Aspose.HTML के साथ आप **HTML को इमेज के रूप में रेंडर** कर सकते हैं, मार्कअप को ऑन‑द‑फ़्लाई बदल सकते हैं, और यहाँ तक कि **HTML को ZIP में सेव** भी कर सकते हैं बाद में वितरण के लिए। इस ट्यूटोरियल में हम एक पूर्ण, चलाने योग्य उदाहरण से गुजरेंगे जो **फ़ॉन्ट स्टाइल HTML लागू करता है**, विशेष रूप से **p** एलिमेंट्स को **बोल्ड** बनाता है, और फिर PNG फ़ाइल बनाता है। अंत में आपके पास एक ही C# क्लास होगी जो पेज लोड करने से लेकर उसके रिसोर्सेज़ को आर्काइव करने तक सब कुछ करती है। + +## What You’ll Need + +- .NET 6.0 या बाद का संस्करण (API .NET Core पर भी काम करता है) +- Aspose.HTML for .NET 6+ (NuGet पैकेज `Aspose.Html`) +- C# सिंटैक्स की बुनियादी समझ (कोई उन्नत कॉन्सेप्ट नहीं चाहिए) + +बस इतना ही। कोई बाहरी ब्राउज़र नहीं, कोई phantomjs नहीं, सिर्फ शुद्ध मैनेज्ड कोड। + +## Step 1 – Load the HTML Document + +पहले हम स्रोत फ़ाइल (या URL) को `HTMLDocument` ऑब्जेक्ट में लाते हैं। यह स्टेप **render html as image** और **save html to zip** दोनों के लिए आधार बनता है। + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*क्यों महत्वपूर्ण है:* `HTMLDocument` क्लास मार्कअप को पार्स करता है, DOM बनाता है, और लिंक्ड रिसोर्सेज़ (CSS, इमेज, फ़ॉन्ट) को रेज़ॉल्व करता है। उचित डॉक्यूमेंट ऑब्जेक्ट के बिना आप स्टाइल्स को नहीं बदल सकते या कुछ रेंडर नहीं कर पाएंगे। + +## Step 2 – Apply Font Style HTML (Add Bold to p) + +अब हम **फ़ॉन्ट स्टाइल HTML** लागू करेंगे, हर `

` एलिमेंट को इटररेट करके उसका `font-weight` बोल्ड सेट करेंगे। यह प्रोग्रामेटिक तरीका है **p** टैग्स को **बोल्ड** करने का, बिना मूल फ़ाइल को छुए। + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*प्रो टिप:* अगर आपको केवल कुछ हिस्सों को ही बोल्ड करना है, तो सिलेक्टर को अधिक विशिष्ट बनाएं, जैसे `"p.intro"`। + +## Step 3 – Render HTML as Image (Convert HTML to PNG) + +DOM तैयार होने के बाद, हम `ImageRenderingOptions` को कॉन्फ़िगर करते हैं और `RenderToImage` को कॉल करते हैं। यहीं पर **convert html to png** का जादू चलता है। + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*ऑप्शन्स क्यों महत्वपूर्ण हैं:* फिक्स्ड चौड़ाई/ऊँचाई सेट करने से आउटपुट बहुत बड़ा नहीं होता, जबकि एंटीएलियासिंग से विज़ुअल रिज़ल्ट स्मूद रहता है। अगर आप छोटा फ़ाइल साइज चाहते हैं तो `options` को `ImageFormat.Jpeg` में बदल सकते हैं। + +## Step 4 – Save HTML to ZIP (Bundle Resources) + +अक्सर आपको मूल HTML को उसके CSS, इमेज और फ़ॉन्ट्स के साथ शिप करना पड़ता है। Aspose.HTML का `ZipArchiveSaveOptions` यही काम करता है। हम एक कस्टम `ResourceHandler` भी जोड़ते हैं ताकि सभी एक्सटर्नल एसेट्स उसी फ़ोल्डर में लिखे जाएँ जहाँ आर्काइव है। + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*एज केस:* अगर आपका HTML रिमोट इमेजेज़ रेफ़र करता है जिनके लिए ऑथेंटिकेशन चाहिए, तो डिफ़ॉल्ट हैंडलर फेल हो जाएगा। ऐसे में आप `MyResourceHandler` को एक्सटेंड करके HTTP हेडर्स इन्जेक्ट कर सकते हैं। + +## Step 5 – Wire Everything Up in a Single Converter Class + +नीचे पूरा, तैयार‑चलाने‑योग्य क्लास है जो पिछले सभी स्टेप्स को जोड़ता है। आप इसे कॉन्सोल ऐप में कॉपी‑पेस्ट कर सकते हैं, `Convert` को कॉल करें, और फ़ाइलें बनते देख सकते हैं। + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Expected Output + +ऊपर दिया गया स्निपेट चलाने के बाद आपको `outputDirectory` में दो फ़ाइलें मिलेंगी: + +| File | Description | +|------|-------------| +| `page.png` | स्रोत HTML का 1200 × 800 PNG रेंडरिंग, जहाँ हर पैराग्राफ **बोल्ड** दिखेगा। | +| `archive.zip` | एक ZIP बंडल जिसमें मूल `input.html`, उसका CSS, इमेजेज़, और वेब‑फ़ॉन्ट्स शामिल हैं – ऑफ़लाइन वितरण के लिए परफ़ेक्ट। | + +आप `page.png` को किसी भी इमेज व्यूअर में खोलकर देख सकते हैं कि बोल्ड स्टाइल लागू हुआ है या नहीं, और `archive.zip` को एक्सट्रैक्ट करके अनटच्ड HTML को उसके एसेट्स के साथ देख सकते हैं। + +## Common Questions & Gotchas + +- **अगर HTML में JavaScript हो तो?** + Aspose.HTML रेंडरिंग के दौरान स्क्रिप्ट नहीं चलाता, इसलिए डायनामिक कंटेंट नहीं दिखेगा। पूरी तरह रेंडर किए गए पेज के लिए आपको हेडलेस ब्राउज़र चाहिए, लेकिन स्टैटिक टेम्पलेट्स के लिए यह तरीका तेज़ और हल्का है। + +- **क्या आउटपुट फ़ॉर्मेट JPEG या BMP में बदल सकते हैं?** + हाँ—`ImageRenderingOptions` की `ImageFormat` प्रॉपर्टी को बदलें, जैसे `options.ImageFormat = ImageFormat.Jpeg;`। + +- **क्या `HTMLDocument` को मैन्युअली डिस्पोज़ करना पड़ेगा?** + यह क्लास `IDisposable` इम्प्लीमेंट करती है। लम्बी‑चलने वाली सर्विस में इसे `using` ब्लॉक में रखें या काम ख़त्म होने पर `document.Dispose()` कॉल करें। + +- **कस्टम `MyResourceHandler` कैसे काम करता है?** + यह प्रत्येक एक्सटर्नल रिसोर्स (CSS, इमेज, फ़ॉन्ट) को लेता है और उसे आप द्वारा निर्दिष्ट फ़ोल्डर में लिखता है। इससे ZIP में HTML द्वारा रेफ़र किए गए सभी एसेट्स की सटीक कॉपी शामिल रहती है। + +## Conclusion + +अब आपके पास एक कॉम्पैक्ट, प्रोडक्शन‑रेडी समाधान है जो **convert html to png**, **render html as image**, **save html to zip**, **apply font style html**, और **add bold to p**—सभी कुछ C# की कुछ लाइनों में। कोड सेल्फ‑कंटेन्ड है, .NET 6+ के साथ काम करता है, और किसी भी बैकएंड सर्विस में डाला जा सकता है जो वेब कंटेंट के त्वरित विज़ुअल स्नैपशॉट की ज़रूरत रखती है। + +अगला कदम? रेंडरिंग साइज बदलें, अन्य CSS प्रॉपर्टीज़ (जैसे `font-family` या `color`) के साथ प्रयोग करें, या इस कन्वर्टर को एक ASP.NET Core एंडपॉइंट में इंटीग्रेट करें जो ऑन‑डिमांड PNG रिटर्न करे। संभावनाएँ अनंत हैं, और Aspose.HTML के साथ आप भारी‑भाड़ वाले ब्राउज़र डिपेंडेंसी से बचते हैं। + +अगर आपको कोई समस्या आई या एक्सटेंशन के आइडिया हैं, तो नीचे कमेंट करें। Happy coding! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/hindi/net/html-document-manipulation/_index.md index 8f5af5f85..751fef390 100644 --- a/html/hindi/net/html-document-manipulation/_index.md +++ b/html/hindi/net/html-document-manipulation/_index.md @@ -72,6 +72,9 @@ HTML दस्तावेज़ों के साथ काम करने ### [C# में स्ट्रिंग से HTML बनाएं – कस्टम रिसोर्स हैंडलर गाइड](./create-html-from-string-in-c-custom-resource-handler-guide/) C# में स्ट्रिंग से HTML उत्पन्न करने और कस्टम रिसोर्स हैंडलर का उपयोग करके इसे लोड करने की प्रक्रिया सीखें। +### [C# में HTML दस्तावेज़ बनाएं – चरण‑दर‑चरण गाइड](./create-html-document-c-step-by-step-guide/) +C# में स्ट्रिंग से HTML दस्तावेज़ बनाना और कस्टम रिसोर्स हैंडलर का उपयोग करके लोड करना सीखें। + ## निष्कर्ष अंत में, यदि आप Aspose.HTML for .NET का उपयोग करके HTML दस्तावेज़ हेरफेर में महारत हासिल करना चाहते हैं, तो आप सही जगह पर हैं। हमारे ट्यूटोरियल आपकी सफलता के लिए रोडमैप हैं। संभावनाओं का पता लगाने, अपनी रचनात्मकता को अनलॉक करने और अपने .NET विकास को सुव्यवस्थित करने के लिए तैयार हो जाइए। आज ही अपनी यात्रा शुरू करें, और अपने HTML दस्तावेज़ों को अपनी आँखों के सामने बदलते हुए देखें। चाहे आप डेवलपर हों या उत्साही, Aspose.HTML for .NET में आपके लिए कुछ अविश्वसनीय है। तो, आप किसका इंतज़ार कर रहे हैं? आइए इस रोमांचक साहसिक कार्य को एक साथ शुरू करें! diff --git a/html/hindi/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/hindi/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..26c5ec850 --- /dev/null +++ b/html/hindi/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: C# में HTML दस्तावेज़ बनाएं और Aspose.Html का उपयोग करके ID द्वारा तत्व + प्राप्त करना, ID द्वारा तत्व को खोजना, HTML तत्व की शैली बदलना और बोल्ड इटैलिक जोड़ना + सीखें। +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: hi +og_description: C# में HTML दस्तावेज़ बनाएं और तुरंत सीखें कि ID द्वारा तत्व प्राप्त + करें, ID द्वारा तत्व खोजें, HTML तत्व की शैली बदलें और स्पष्ट कोड उदाहरणों के साथ + बोल्ड इटैलिक जोड़ें। +og_title: HTML दस्तावेज़ बनाएं C# – पूर्ण प्रोग्रामिंग गाइड +tags: +- Aspose.Html +- C# +- DOM manipulation +title: HTML दस्तावेज़ C# बनाना – चरण‑दर‑चरण मार्गदर्शिका +url: /hi/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML दस्तावेज़ C# बनाना – चरण‑दर‑चरण गाइड + +क्या आपको कभी **create HTML document C#** को शून्य से बनाना पड़ा और फिर एक पैराग्राफ की दिखावट को बदलना पड़ा? आप अकेले नहीं हैं। कई वेब‑ऑटोमेशन प्रोजेक्ट्स में आप एक HTML फ़ाइल बनाते हैं, उसके ID से टैग खोजते हैं, और फिर कुछ स्टाइल लागू करते हैं—आमतौर पर बोल्ड + इटैलिक—बिना ब्राउज़र को छुए। + +इस ट्यूटोरियल में हम ठीक वही करेंगे: हम C# में एक HTML दस्तावेज़ बनाएँगे, **get element by id**, **locate element by id**, **change HTML element style**, और अंत में Aspose.Html लाइब्रेरी का उपयोग करके **add bold italic** करेंगे। अंत तक आपके पास एक पूरी तरह चलने योग्य स्निपेट होगा जिसे आप किसी भी .NET प्रोजेक्ट में डाल सकते हैं। + +## आपको क्या चाहिए + +- .NET 6 या बाद का (कोड .NET Framework 4.7+ पर भी काम करता है) +- Visual Studio 2022 (या कोई भी एडिटर जो आप पसंद करें) +- **Aspose.Html** NuGet पैकेज (`Install-Package Aspose.Html`) + +बस इतना ही—कोई अतिरिक्त HTML फ़ाइलें नहीं, कोई वेब सर्वर नहीं, सिर्फ कुछ ही पंक्तियों का C#। + +## HTML दस्तावेज़ C# बनाना – दस्तावेज़ को इनिशियलाइज़ करना + +सबसे पहले: आपको एक लाइव `HTMLDocument` ऑब्जेक्ट चाहिए जिसे Aspose.Html इंजन उपयोग कर सके। इसे ऐसे समझें जैसे आप एक नई नोटबुक खोल रहे हैं जहाँ आप अपना मार्कअप लिखेंगे। + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Why this matters:** `HTMLDocument` को कच्ची स्ट्रिंग पास करके, आप फ़ाइल I/O से बचते हैं और सब कुछ मेमोरी में रखते हैं—यूनिट टेस्ट या ऑन‑द‑फ़्लाई जेनरेशन के लिए परफ़ेक्ट। + +## Get Element by ID – पैराग्राफ ढूँढ़ना + +अब जब दस्तावेज़ मौजूद है, हमें **get element by id** चाहिए। DOM API हमें `GetElementById` देता है, जो एक `IElement` रेफ़रेंस या `null` लौटाता है यदि ID मौजूद नहीं है। + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Pro tip:** भले ही हमारा मार्कअप छोटा है, एक null‑check जोड़ने से बड़े, डायनेमिक पेजों पर वही लॉजिक पुन: उपयोग करने पर परेशानी से बचा जा सकता है। + +## Locate Element by ID – एक वैकल्पिक तरीका + +कभी‑कभी आपके पास दस्तावेज़ की रूट का रेफ़रेंस पहले से ही हो सकता है और आप क्वेरी‑स्टाइल खोज पसंद करेंगे। CSS सिलेक्टर्स (`QuerySelector`) का उपयोग करके **locate element by id** का एक और तरीका है: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **When to use which?** `GetElementById` थोड़ा तेज़ है क्योंकि यह एक डायरेक्ट हैश लुकअप है। `QuerySelector` तब चमकता है जब आपको जटिल सिलेक्टर्स चाहिए (जैसे, `div > p.highlight`)। + +## Change HTML Element Style – बोल्ड इटैलिक जोड़ना + +एलीमेंट हाथ में होने पर, अगला कदम **change HTML element style** है। Aspose.Html एक `Style` ऑब्जेक्ट प्रदान करता है जहाँ आप CSS प्रॉपर्टीज़ समायोजित कर सकते हैं या एक साथ कई फ़ॉन्ट गुण लागू करने के लिए सुविधाजनक `WebFontStyle` एनेमरेशन का उपयोग कर सकते हैं। + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +वह एकल पंक्ति एलीमेंट के `font-weight` को `bold` और `font-style` को `italic` सेट करती है। अंदरूनी रूप से Aspose.Html एनेम को उपयुक्त CSS स्ट्रिंग में बदल देता है। + +### पूर्ण कार्यशील उदाहरण + +सभी हिस्सों को मिलाकर एक कॉम्पैक्ट, स्व-निहित प्रोग्राम बनता है जिसे आप तुरंत कंपाइल और रन कर सकते हैं: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**अपेक्षित आउटपुट** + +``` +Rendered HTML: +

Hello world

+``` + +`

` टैग अब एक इनलाइन `style` एट्रिब्यूट रखता है जो टेक्स्ट को दोनों बोल्ड और इटैलिक बनाता है—बिल्कुल वही जो हम चाहते थे। + +## किनारे के मामलों और सामान्य जाल + +| स्थिति | क्या देखना है | कैसे संभालें | +|-----------|-------------------|---------------| +| **ID मौजूद नहीं है** | `GetElementById` `null` लौटाता है। | एक एक्सेप्शन थ्रो करें या डिफ़ॉल्ट एलीमेंट पर फॉलबैक करें। | +| **कई एलीमेंट्स एक ही ID साझा करते हैं** | HTML स्पेसिफिकेशन कहता है कि IDs यूनिक होनी चाहिए, लेकिन वास्तविक पेज़ कभी‑कभी इस नियम को तोड़ते हैं। | `GetElementById` पहला मैच लौटाता है; यदि आपको डुप्लिकेट्स संभालने हैं तो `QuerySelectorAll` उपयोग करने पर विचार करें। | +| **स्टाइलिंग टकराव** | मौजूदा इनलाइन स्टाइल्स ओवरराइट हो सकते हैं। | पूरे `style` स्ट्रिंग को सेट करने के बजाय `Style` ऑब्जेक्ट में जोड़ें: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **ब्राउज़र में रेंडरिंग** | कुछ ब्राउज़र `WebFontStyle` को नजरअंदाज कर देते हैं यदि एलीमेंट के पास पहले से ही अधिक विशिष्टता वाला CSS क्लास है। | यदि आवश्यक हो तो `paragraph.Style.SetProperty("font-weight", "bold", "important");` के माध्यम से `!important` उपयोग करें। | + +## वास्तविक‑दुनिया प्रोजेक्ट्स के लिए प्रो टिप्स + +- **Cache the document** यदि आप कई एलीमेंट्स प्रोसेस कर रहे हैं; हर छोटे स्निपेट के लिए नया `HTMLDocument` बनाना प्रदर्शन को नुकसान पहुँचा सकता है। +- एक ही `Style` ट्रांज़ैक्शन में **style changes** को मिलाएँ ताकि कई DOM रीफ़्लो से बचा जा सके। +- अंतिम दस्तावेज़ को PDF या इमेज के रूप में एक्सपोर्ट करने के लिए **Aspose.Html’s rendering engine** का उपयोग करें—रिपोर्टिंग टूल्स के लिए शानदार। + +## विज़ुअल पुष्टि (वैकल्पिक) + +यदि आप परिणाम को ब्राउज़र में देखना पसंद करते हैं, तो आप रेंडर की गई स्ट्रिंग को `.html` फ़ाइल में सेव कर सकते हैं: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +`output.html` खोलें और आप **Hello world** को बोल्ड + इटैलिक में प्रदर्शित देखेंगे। + +![Create HTML Document C# उदाहरण जिसमें बोल्ड इटैलिक पैराग्राफ दिखाया गया है](/images/create-html-document-csharp.png "Create HTML Document C# – रेंडर किया गया आउटपुट") + +*Alt text: Create HTML Document C# उदाहरण जिसमें बोल्ड इटैलिक पैराग्राफ दिखाया गया है.* + +## निष्कर्ष + +हमने अभी **created an HTML document C#**, **got element by id**, **located element by id**, **changed HTML element style**, और अंत में **added bold italic** किया—सभी Aspose.Html का उपयोग करके कुछ ही पंक्तियों में। यह तरीका सीधा है, किसी भी .NET वातावरण में काम करता है, और बड़े DOM मैनिपुलेशन तक स्केल करता है। + +अगले कदम के लिए तैयार हैं? `WebFontStyle` को `Underline` जैसे अन्य एनेम से बदलने या कई स्टाइल्स को मैन्युअली मिलाने की कोशिश करें। या बाहरी HTML फ़ाइल लोड करके उसी तकनीक को सैकड़ों एलीमेंट्स पर लागू करने का प्रयोग करें। संभावनाएँ असीम हैं, और अब आपके पास निर्माण के लिए एक ठोस आधार है। + +कोडिंग का आनंद लें! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hindi/net/html-extensions-and-conversions/_index.md b/html/hindi/net/html-extensions-and-conversions/_index.md index 45408d5a1..62d674ae8 100644 --- a/html/hindi/net/html-extensions-and-conversions/_index.md +++ b/html/hindi/net/html-extensions-and-conversions/_index.md @@ -30,7 +30,7 @@ HTML एक्सटेंशन डेवलपर्स के लिए ए ## Aspose.HTML के साथ आरंभ करें -क्या आप शुरू करने के लिए तैयार हैं? .NET के लिए Aspose.HTML ट्यूटोरियल शुरुआती और अनुभवी डेवलपर्स दोनों के लिए हैं। चाहे आप HTML एक्सटेंशन और रूपांतरणों के लिए नए हों या उन्नत युक्तियों की तलाश कर रहे हों, हमारे चरण-दर-चरण मार्गदर्शिकाएँ आपकी आवश्यकताओं के अनुरूप डिज़ाइन की गई हैं। +क्या आप शुरू करने के लिए तैयार हैं? .NET के लिए Aspose.HTML ट्यूटोरियल शुरुआती और अनुभवी डेवलपर्स दोनों के लिए हैं। चाहे आप HTML एक्सटेंशन और रूपांतरणों के लिए नए हों या उन्नत युक्तियों की तलाश कर रहे हों, हमारे चरण-दर-स्टेप मार्गदर्शिकाएँ आपकी आवश्यकताओं के अनुरूप डिज़ाइन की गई हैं। ## .NET के लिए Aspose.HTML क्यों? @@ -40,6 +40,9 @@ Aspose.HTML for .NET सिर्फ़ एक लाइब्रेरी न ### [Aspose.HTML के साथ .NET में HTML को PDF में बदलें](./convert-html-to-pdf/) .NET के लिए Aspose.HTML के साथ HTML को PDF में आसानी से बदलें। हमारे चरण-दर-चरण गाइड का पालन करें और HTML-से-PDF रूपांतरण की शक्ति को प्राप्त करें। +### [Aspose के साथ HTML से PDF बनाएं – चरण‑दर‑चरण C# गाइड](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +C# में Aspose.HTML का उपयोग करके HTML को PDF में बदलने की पूरी चरण‑दर‑चरण गाइड। + ### [HTML से PDF बनाएं – C# चरण‑दर‑चरण गाइड](./create-pdf-from-html-c-step-by-step-guide/) C# में Aspose.HTML का उपयोग करके HTML को PDF में बदलने का चरण‑दर‑चरण मार्गदर्शन। @@ -56,7 +59,7 @@ C# में Aspose.HTML का उपयोग करके HTML को PDF म .NET के लिए Aspose.HTML का उपयोग करके .NET में HTML को BMP में कैसे बदलें, यह जानें। .NET के लिए Aspose.HTML का लाभ उठाने के लिए वेब डेवलपर्स के लिए व्यापक गाइड। ### [Aspose.HTML के साथ .NET में HTML को DOC और DOCX में बदलें](./convert-html-to-doc-docx/) -इस चरण-दर-चरण मार्गदर्शिका में .NET के लिए Aspose.HTML की शक्ति का उपयोग करना सीखें। HTML को DOCX में आसानी से बदलें और अपने .NET प्रोजेक्ट को बेहतर बनाएँ। आज ही शुरू करें! +इस चरण-दर-स्टेप मार्गदर्शिका में .NET के लिए Aspose.HTML की शक्ति का उपयोग करना सीखें। HTML को DOCX में आसानी से बदलें और अपने .NET प्रोजेक्ट को बेहतर बनाएँ। आज ही शुरू करें! ### [Aspose.HTML के साथ .NET में HTML को GIF में बदलें](./convert-html-to-gif/) .NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को GIF में बदलने के लिए चरण-दर-चरण मार्गदर्शिका। पूर्वापेक्षाएँ, कोड उदाहरण, FAQ, और बहुत कुछ! Aspose.HTML के साथ अपने HTML हेरफेर को अनुकूलित करें। @@ -71,25 +74,34 @@ C# में Aspose.HTML का उपयोग करके HTML को PDF म Aspose.HTML के साथ .NET में HTML को MHTML में बदलें - कुशल वेब सामग्री संग्रह के लिए चरण-दर-चरण मार्गदर्शिका। MHTML संग्रह बनाने के लिए .NET के लिए Aspose.HTML का उपयोग करना सीखें। ### [Aspose.HTML के साथ .NET में HTML को PNG में बदलें](./convert-html-to-png/) -जानें कि HTML दस्तावेज़ों में हेरफेर करने और उन्हें परिवर्तित करने के लिए .NET के लिए Aspose.HTML का उपयोग कैसे करें। प्रभावी .NET विकास के लिए चरण-दर-चरण मार्गदर्शिका। +जानें कि HTML दस्तावेज़ों में हेरफेर करने और उन्हें परिवर्तित करने के लिए .NET के लिए Aspose.HTML का उपयोग कैसे करें। प्रभावी .NET विकास के लिए चरण-दर-स्टेप मार्गदर्शिका। ### [Aspose.HTML के साथ .NET में HTML को TIFF में बदलें](./convert-html-to-tiff/) -.NET के लिए Aspose.HTML के साथ HTML को TIFF में कैसे बदलें, यह जानें। कुशल वेब सामग्री अनुकूलन के लिए हमारे चरण-दर-चरण मार्गदर्शिका का पालन करें। +.NET के लिए Aspose.HTML के साथ HTML को TIFF में कैसे बदलें, यह जानें। कुशल वेब सामग्री अनुकूलन के लिए हमारे चरण-दर-स्टेप मार्गदर्शिका का पालन करें। + +### [Aspose.HTML के साथ .NET में HTML को इमेज में बदलें – पूर्ण गाइड](./convert-html-to-image-in-c-complete-guide/) +C# में Aspose.HTML का उपयोग करके HTML को इमेज में बदलने की पूरी गाइड। चरण‑दर‑स्टेप कोड उदाहरण और विकल्प। ### [Aspose.HTML के साथ .NET में HTML को XPS में बदलें](./convert-html-to-xps/) -.NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को XPS में आसानी से बदलें। पूर्वापेक्षाएँ, चरण-दर-चरण मार्गदर्शिका और FAQ शामिल हैं। +.NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को XPS में आसानी से बदलें। पूर्वापेक्षाएँ, चरण-दर-स्टेप मार्गदर्शिका और FAQ शामिल हैं। ### [HTML को ZIP के रूप में सहेजें – पूर्ण C# ट्यूटोरियल](./save-html-as-zip-complete-c-tutorial/) -HTML को ZIP फ़ाइल में सहेजने के चरण-दर-चरण मार्गदर्शन, C# कोड उदाहरण और अनुकूलन विकल्प। +HTML को ZIP फ़ाइल में सहेजने के चरण-दर-स्टेप मार्गदर्शन, C# कोड उदाहरण और अनुकूलन विकल्प। ### [C# में HTML को ज़िप कैसे करें – HTML को ज़िप में सहेजें](./how-to-zip-html-in-c-save-html-to-zip/) .NET के लिए Aspose.HTML का उपयोग करके C# में HTML को ज़िप फ़ाइल में सहेजने का तरीका सीखें। +### [Aspose.HTML के साथ HTML को ज़िप करने का पूर्ण गाइड](./how-to-zip-html-with-aspose-html-complete-guide/) +Aspose.HTML का उपयोग करके HTML को ZIP फ़ाइल में सहेजने का पूर्ण चरण‑दर‑स्टेप गाइड। + ### [स्टाइल्ड टेक्स्ट के साथ HTML दस्तावेज़ बनाएं और PDF में निर्यात करें – पूर्ण गाइड](./create-html-document-with-styled-text-and-export-to-pdf-full/) Aspose.HTML for .NET का उपयोग करके स्टाइल्ड टेक्ट वाले HTML दस्तावेज़ को बनाएं और उसे PDF में निर्यात करने की पूरी गाइड। .NET के लिए Aspose.HTML की शक्ति का पता लगाएं: HTML को XPS में आसानी से बदलें। पूर्वापेक्षाएँ, चरण-दर-स्टेप मार्गदर्शिका और FAQ शामिल हैं। ### [C# में HTML को ZIP में सहेजें – पूर्ण इन‑मेमोरी उदाहरण](./save-html-to-zip-in-c-complete-in-memory-example/) C# में इन‑मेमोरी में HTML को ZIP फ़ाइल में सहेजने का पूरा उदाहरण देखें। +### [C# में HTML को ZIP के रूप में सहेजें – कस्टम स्टोरेज के साथ पूर्ण गाइड](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +C# में कस्टम स्टोरेज विकल्पों के साथ HTML को ZIP फ़ाइल में सहेजने की पूरी प्रक्रिया सीखें। + ## निष्कर्ष निष्कर्ष में, HTML एक्सटेंशन और रूपांतरण आधुनिक वेब विकास के आवश्यक तत्व हैं। .NET के लिए Aspose.HTML प्रक्रिया को सरल बनाता है और इसे सभी स्तरों के डेवलपर्स के लिए सुलभ बनाता है। हमारे ट्यूटोरियल का पालन करके, आप एक व्यापक कौशल सेट के साथ एक कुशल वेब डेवलपर बनने के अपने रास्ते पर अच्छी तरह से आगे बढ़ेंगे। diff --git a/html/hindi/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/hindi/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..a0878507a --- /dev/null +++ b/html/hindi/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Aspose.HTML का उपयोग करके C# में HTML को इमेज में बदलें। सीखें कि कैसे + HTML को PNG के रूप में सहेजें, इमेज का आकार सेट करें, और कुछ ही चरणों में इमेज को + फ़ाइल में लिखें। +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: hi +og_description: HTML को जल्दी से इमेज में बदलें। यह गाइड दिखाता है कि HTML को PNG + के रूप में कैसे सहेजें, इमेज आकार रेंडरिंग सेट करें, और Aspose.HTML के साथ इमेज + को फ़ाइल में लिखें। +og_title: C# में HTML को इमेज में बदलें – चरण‑दर‑चरण गाइड +tags: +- Aspose.HTML +- C# +- Image Rendering +title: C# में HTML को इमेज में परिवर्तित करें – पूर्ण गाइड +url: /hi/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML को इमेज में बदलें C# – पूर्ण गाइड + +क्या आपको कभी डैशबोर्ड थंबनेल, ईमेल प्रीव्यू, या PDF रिपोर्ट के लिए **HTML को इमेज में बदलने** की जरूरत पड़ी है? यह एक ऐसा परिदृश्य है जो आपसे अपेक्षा से अधिक बार सामने आता है, विशेष रूप से जब आप डायनामिक वेब कंटेंट के साथ काम कर रहे हों जिसे कहीं और एम्बेड करना हो। + +अच्छी खबर? Aspose.HTML के साथ आप सिर्फ कुछ लाइनों में **HTML को इमेज में बदल** सकते हैं, और आप सीखेंगे कि *HTML को PNG के रूप में सहेजें*, आउटपुट डाइमेंशन को नियंत्रित करें, और *इमेज को फाइल में लिखें* बिना किसी परेशानी के। + +इस ट्यूटोरियल में हम सब कुछ बताएँगे जो आपको जानना आवश्यक है: रिमोट पेज लोड करने से लेकर रेंडरिंग साइज को ट्यून करने तक, और अंत में परिणाम को डिस्क पर PNG फाइल के रूप में सहेजना। कोई बाहरी टूल नहीं, कोई जटिल कमांड‑लाइन ट्रिक्स नहीं—सिर्फ शुद्ध C# कोड जिसे आप किसी भी .NET प्रोजेक्ट में डाल सकते हैं। + +## आप क्या सीखेंगे + +- Aspose.HTML के `HTMLDocument` क्लास का उपयोग करके **वेबपेज को PNG में रेंडर** करने का तरीका। +- आउटपुट को आपके लेआउट आवश्यकताओं के अनुसार मिलाने के लिए **इमेज साइज रेंडरिंग सेट** करने के सटीक कदम। +- **इमेज को फाइल में लिखें** सुरक्षित रूप से, स्ट्रीम और फाइल पाथ को संभालते हुए। +- मिसिंग फ़ॉन्ट्स या नेटवर्क टाइमआउट जैसी सामान्य समस्याओं को हल करने के टिप्स। + +### आवश्यकताएँ + +- .NET 6.0 या बाद का संस्करण (API .NET Framework के साथ भी काम करता है, लेकिन .NET 6+ की सलाह दी जाती है)। +- Aspose.HTML for .NET NuGet पैकेज (`Aspose.Html`) का रेफ़रेंस। +- C# और async/await की बुनियादी जानकारी (वैकल्पिक लेकिन उपयोगी)। + +यदि आपके पास ये सब हैं, तो आप तुरंत HTML को इमेज में बदलना शुरू करने के लिए तैयार हैं। + +## चरण 1: वेब पेज लोड करें – HTML को इमेज में बदलने की नींव + +किसी भी रेंडरिंग से पहले, आपको एक `HTMLDocument` इंस्टेंस चाहिए जो उस पेज का प्रतिनिधित्व करता है जिसे आप कैप्चर करना चाहते हैं। + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*क्यों यह महत्वपूर्ण है:* `HTMLDocument` HTML को पार्स करता है, CSS को रिजॉल्व करता है, और DOM बनाता है। यदि दस्तावेज़ लोड नहीं हो पाता (जैसे नेटवर्क समस्या), तो अगली रेंडरिंग एक खाली इमेज उत्पन्न करेगी। आगे बढ़ने से पहले हमेशा सुनिश्चित करें कि URL पहुँच योग्य है। + +## चरण 2: इमेज साइज रेंडरिंग सेट करें – चौड़ाई, ऊँचाई, और क्वालिटी को नियंत्रित करना + +Aspose.HTML आपको `ImageRenderingOptions` के साथ आउटपुट डाइमेंशन को फाइन‑ट्यून करने देता है। यहाँ आप **इमेज साइज रेंडरिंग सेट** करते हैं ताकि यह आपके लक्ष्य लेआउट से मेल खाए। + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*प्रो टिप:* यदि आप `Width` और `Height` को छोड़ देते हैं, तो Aspose.HTML पेज के अंतर्निहित आकार का उपयोग करेगा, जो रिस्पॉन्सिव डिज़ाइनों के लिए अप्रत्याशित हो सकता है। स्पष्ट डाइमेंशन निर्दिष्ट करने से आपका **HTML को PNG के रूप में सहेजें** आउटपुट बिल्कुल वही दिखेगा जैसा आप उम्मीद करते हैं। + +## चरण 3: इमेज को फाइल में लिखें – रेंडर की गई PNG को स्थायी बनाना + +अब जब दस्तावेज़ तैयार है और रेंडरिंग विकल्प सेट हैं, आप अंततः **इमेज को फाइल में लिख सकते** हैं। `FileStream` का उपयोग करने से फाइल सुरक्षित रूप से बनती है, भले ही फ़ोल्डर अभी तक मौजूद न हो। + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +इस ब्लॉक के चलने के बाद, आपको निर्दिष्ट स्थान पर `page.png` मिलेगा। आपने अभी **वेबपेज को PNG में रेंडर** किया है और इसे डिस्क पर एक ही सरल ऑपरेशन में लिखा है। + +### अपेक्षित परिणाम + +`C:\Temp\page.png` को किसी भी इमेज व्यूअर में खोलें। आपको `https://example.com` का एक सटीक स्नैपशॉट दिखना चाहिए, जो 1024 × 768 पिक्सेल पर एंटीएलियासिंग के कारण स्मूद एजेस के साथ रेंडर हुआ है। यदि पेज में डायनामिक कंटेंट (जैसे JavaScript‑जनित एलिमेंट) है, तो वे तब कैप्चर हो जाएंगे जब तक DOM रेंडरिंग से पहले पूरी तरह लोड न हो जाए। + +## चरण 4: एज केस को संभालना – फ़ॉन्ट्स, ऑथेंटिकेशन, और बड़े पेज + +जबकि बेसिक फ्लो अधिकांश सार्वजनिक साइटों के लिए काम करता है, वास्तविक दुनिया के परिदृश्य अक्सर अप्रत्याशित समस्याएँ लाते हैं: + +| स्थिति | क्या करें | +|-----------|------------| +| **कस्टम फ़ॉन्ट्स लोड नहीं हो रहे** | फ़ॉन्ट फ़ाइलों को लोकली एम्बेड करें और `htmlDoc.Fonts.Add("path/to/font.ttf")` सेट करें। | +| **ऑथेंटिकेशन के पीछे पेजेज** | `HTMLDocument` ओवरलोड का उपयोग करें जो `HttpWebRequest` को कुकीज़ या टोकन के साथ स्वीकार करता है। | +| **बहुत लंबी पेजेज** | `Height` बढ़ाएँ या `ImageRenderingOptions` में `PageScaling` सक्षम करें ताकि ट्रंकेशन न हो। | +| **मेमोरी उपयोग में स्पाइक** | `RenderToImage` ओवरलोड का उपयोग करके चंक्स में रेंडर करें जो `Rectangle` रीजन को स्वीकार करता है। | + +इन *इमेज को फाइल में लिखें* बारीकियों को संबोधित करने से आपका `convert html to image` पाइपलाइन प्रोडक्शन में मजबूत बना रहता है। + +## चरण 5: पूर्ण कार्यशील उदाहरण – कॉपी‑पेस्ट तैयार + +नीचे पूरा प्रोग्राम दिया गया है, जिसे कंपाइल करने के लिए तैयार है। इसमें सभी चरण, एरर हैंडलिंग, और आवश्यक कमेंट्स शामिल हैं। + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +इस प्रोग्राम को चलाएँ, और आपको कंसोल में पुष्टि संदेश दिखाई देगा। PNG फाइल बिल्कुल वही होगी जो आप ब्राउज़र में मैन्युअली **वेबपेज को PNG में रेंडर** करके स्क्रीनशॉट लेते समय उम्मीद करेंगे—सिर्फ तेज़ और पूरी तरह स्वचालित। + +## अक्सर पूछे जाने वाले प्रश्न + +**प्रश्न: क्या मैं URL के बजाय स्थानीय HTML फ़ाइल को बदल सकता हूँ?** +बिल्कुल। बस URL को फ़ाइल पाथ से बदल दें: `new HTMLDocument(@"C:\myPage.html")`। + +**प्रश्न: क्या मुझे Aspose.HTML के लिए लाइसेंस चाहिए?** +एक मुफ्त इवैल्यूएशन लाइसेंस विकास और परीक्षण के लिए काम करता है। प्रोडक्शन के लिए, इवैल्यूएशन वाटरमार्क हटाने हेतु लाइसेंस खरीदें। + +**प्रश्न: यदि पेज प्रारंभिक लोड के बाद कंटेंट लोड करने के लिए JavaScript का उपयोग करता है तो क्या करें?** +Aspose.HTML पार्सिंग के दौरान JavaScript को सिंक्रोनस रूप से चलाता है, लेकिन लंबे चलने वाले स्क्रिप्ट्स को मैन्युअल डिले की आवश्यकता हो सकती है। आप रेंडरिंग से पहले `HTMLDocument.WaitForReadyState` का उपयोग कर सकते हैं। + +## निष्कर्ष + +अब आपके पास C# में **HTML को इमेज में बदलने** के लिए एक ठोस, एंड‑टू‑एंड समाधान है। ऊपर बताए गए चरणों का पालन करके आप **HTML को PNG के रूप में सहेज** सकते हैं, सटीक रूप से **इमेज साइज रेंडरिंग सेट** कर सकते हैं, और किसी भी Windows या Linux वातावरण में आत्मविश्वास से **इमेज को फाइल में लिख** सकते हैं। + +सरल स्क्रीनशॉट से लेकर ऑटोमेटेड रिपोर्ट जेनरेशन तक, यह तकनीक अच्छी तरह स्केल करती है। अगला, JPEG या BMP जैसे अन्य आउटपुट फ़ॉर्मेट्स के साथ प्रयोग करें, या कोड को ASP.NET Core API में इंटीग्रेट करें जो PNG को सीधे कॉलर को रिटर्न करता है। संभावनाएँ लगभग अनंत हैं। + +कोडिंग का आनंद लें, और आपकी रेंडर की गई इमेजेस हमेशा पिक्सेल‑परफेक्ट दिखें! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hindi/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/hindi/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..800e8e33b --- /dev/null +++ b/html/hindi/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-03-21 +description: Aspose HTML का उपयोग करके HTML से तेज़ी से PDF बनाएं। HTML को PDF में + रेंडर करना, HTML को PDF में बदलना और संक्षिप्त ट्यूटोरियल में Aspose का उपयोग कैसे + करें, सीखें। +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: hi +og_description: C# में Aspose के साथ HTML से PDF बनाएं। यह गाइड दिखाता है कि HTML + को PDF में कैसे रेंडर करें, HTML को PDF में कैसे बदलें, और Aspose का प्रभावी उपयोग + कैसे करें। +og_title: HTML से PDF बनाएं – पूर्ण Aspose C# ट्यूटोरियल +tags: +- Aspose +- C# +- PDF generation +title: Aspose के साथ HTML से PDF बनाएं – चरण‑दर‑चरण C# गाइड +url: /hi/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose के साथ HTML से PDF बनाना – चरण‑दर‑चरण C# गाइड + +क्या आपको कभी **HTML से PDF बनाना** पड़ा है लेकिन आप सुनिश्चित नहीं थे कि कौन‑सी लाइब्रेरी आपको पिक्सेल‑परफेक्ट परिणाम देगी? आप अकेले नहीं हैं। कई डेवलपर्स को समस्या होती है जब वे वेब स्निपेट को प्रिंटेबल दस्तावेज़ में बदलने की कोशिश करते हैं, और अंत में धुंधला टेक्स्ट या टूटे‑फ़ुटे लेआउट मिलते हैं। + +अच्छी खबर यह है कि Aspose HTML पूरी प्रक्रिया को आसान बना देता है। इस ट्यूटोरियल में हम वह सटीक कोड देखेंगे जो आपको **HTML को PDF में रेंडर** करने के लिए चाहिए, प्रत्येक सेटिंग क्यों महत्वपूर्ण है इसे समझेंगे, और आपको दिखाएंगे कि **HTML को PDF में कैसे बदलें** बिना किसी छिपे हुए ट्रिक के। अंत तक, आप **Aspose का उपयोग कैसे करें** यह जान जाएंगे, जिससे किसी भी .NET प्रोजेक्ट में भरोसेमंद PDF जेनरेशन संभव हो सके। + +## Prerequisites – What You’ll Need Before You Start + +- **.NET 6.0 या बाद का** (उदाहरण .NET Framework 4.7+ पर भी काम करता है) +- **Visual Studio 2022** या कोई भी IDE जो C# को सपोर्ट करता हो +- **Aspose.HTML for .NET** NuGet पैकेज (फ्री ट्रायल या लाइसेंस्ड वर्ज़न) +- C# सिंटैक्स की बुनियादी समझ (गहरी PDF जानकारी की आवश्यकता नहीं) + +यदि आपके पास ये सब है, तो आप तैयार हैं। अन्यथा, नवीनतम .NET SDK डाउनलोड करें और NuGet पैकेज को इस कमांड से इंस्टॉल करें: + +```bash +dotnet add package Aspose.HTML +``` + +यह एकल लाइन **aspose html to pdf** कन्वर्ज़न के लिए आवश्यक सभी चीज़ें लाती है। + +--- + +## Step 1: Set Up Your Project to Create PDF from HTML + +सबसे पहले आपको एक नया कंसोल ऐप बनाना है (या कोड को मौजूदा सर्विस में इंटीग्रेट करना है)। यहाँ एक न्यूनतम `Program.cs` स्केलेटन है: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** यदि आप पुराने सैंपल में `Aspise.Html.Rendering.Text` देखते हैं, तो इसे `Aspose.Html.Rendering.Text` से बदलें। टाइपो के कारण कंपाइल एरर आएगा। + +सही नेमस्पेसेस का उपयोग करने से कंपाइलर को **TextOptions** क्लास मिल पाती है, जिसकी हमें बाद में जरूरत पड़ेगी। + +## Step 2: Build the HTML Document (Render HTML to PDF) + +अब हम स्रोत HTML बनाते हैं। Aspose आपको रॉ स्ट्रिंग, फ़ाइल पाथ या यहाँ तक कि URL पास करने की सुविधा देता है। इस डेमो के लिए हम इसे सरल रखेंगे: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +स्ट्रिंग पास क्यों करें? इससे फ़ाइल सिस्टम I/O से बचा जाता है, कन्वर्ज़न तेज़ होता है, और यह सुनिश्चित होता है कि कोड में जो HTML दिख रहा है वही रेंडर हो रहा है। यदि आप फ़ाइल से लोड करना चाहते हैं, तो कंस्ट्रक्टर आर्ग्यूमेंट को फ़ाइल URI से बदल दें। + +## Step 3: Fine‑Tune Text Rendering (Convert HTML to PDF with Better Quality) + +टेक्स्ट रेंडरिंग अक्सर यह तय करती है कि आपका PDF साफ़ दिखेगा या धुंधला। Aspose एक `TextOptions` क्लास प्रदान करता है जो आपको सब‑पिक्सेल हिन्टिंग एनेबल करने देता है—उच्च‑DPI आउटपुट के लिए आवश्यक। + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +`UseHinting` को एनेबल करना विशेष रूप से तब उपयोगी होता है जब आपके स्रोत HTML में कस्टम फ़ॉन्ट या छोटे फ़ॉन्ट साइज हों। बिना इस विकल्प के अंतिम PDF में किनारे जगरज हो सकते हैं। + +## Step 4: Attach Text Options to PDF Rendering Configuration (How to Use Aspose) + +अब हम इन टेक्स्ट ऑप्शन्स को PDF रेंडरर से बाइंड करते हैं। यही वह जगह है जहाँ **aspose html to pdf** वास्तव में चमकता है—पेज साइज से लेकर कम्प्रेशन तक सब कुछ ट्यून किया जा सकता है। + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +यदि आप डिफ़ॉल्ट A4 साइज से संतुष्ट हैं तो `PageSetup` को छोड़ सकते हैं। मुख्य बात यह है कि `TextOptions` ऑब्जेक्ट `PdfRenderingOptions` के अंदर रहता है, और इसी से आप Aspose को बताते हैं कि टेक्स्ट कैसे रेंडर करना है। + +## Step 5: Render the HTML and Save the PDF (Convert HTML to PDF) + +अंत में, हम आउटपुट को फ़ाइल में स्ट्रीम करते हैं। `using` ब्लॉक का उपयोग करने से फ़ाइल हैंडल सही ढंग से बंद हो जाता है, चाहे कोई एक्सेप्शन आए या न आए। + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +प्रोग्राम चलाने पर आपको `output.pdf` एक्सिक्यूटेबल के बगल में मिलेगा। इसे खोलें, और आपको एक साफ़ हेडिंग और पैराग्राफ़ दिखेगा—बिल्कुल वही जो HTML स्ट्रिंग में परिभाषित किया गया था। + +### Expected Output + +![HTML से PDF बनाने का उदाहरण आउटपुट](https://example.com/images/pdf-output.png "HTML से PDF बनाने का उदाहरण आउटपुट") + +*स्क्रीनशॉट में जनरेट किया गया PDF दिखाया गया है, जिसमें “Hello, Aspose!” हेडिंग टेक्स्ट हिन्टिंग के कारण तेज़ी से रेंडर हुई है।* + +--- + +## Common Questions & Edge Cases + +### 1. What if my HTML references external resources (images, CSS)? + +Aspose डॉक्यूमेंट के बेस URI के आधार पर रिलेटिव URL को रिजॉल्व करता है। यदि आप रॉ स्ट्रिंग पास कर रहे हैं, तो बेस URI को मैन्युअली सेट करें: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +अब कोई भी `` `C:/MyProject/` के रिलेटिव रूप में खोजा जाएगा। + +### 2. How do I embed fonts that aren’t installed on the server? + +एक ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### चरण 4: कस्टम स्टोरेज के साथ सेव ऑप्शन कॉन्फ़िगर करें + +`HtmlSaveOptions` हमें Aspose को सब कुछ ZIP फ़ाइल में पैक करने का निर्देश देता है। `OutputStorage` प्रॉपर्टी (लेगेसी) हमारे `MyStorage` इंस्टेंस को प्राप्त करती है। + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **नोट:** Aspose HTML 23.9+ में प्रॉपर्टी का नाम `OutputStorage` है लेकिन इसे डिप्रिकेटेड चिह्नित किया गया है। आधुनिक विकल्प `ZipOutputStorage` है। नीचे दिया गया कोड दोनों के साथ काम करता है क्योंकि इंटरफ़ेस समान है। + +### चरण 5: डॉक्यूमेंट को ZIP आर्काइव के रूप में सेव करें + +एक टार्गेट फ़ोल्डर (या स्ट्रीम) चुनें और Aspose को भारी काम करने दें। + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +प्रोग्राम समाप्त होने पर आपको `output.zip` मिलेगा जिसमें: + +* `index.html` – मुख्य डॉक्यूमेंट। +* कोई भी एम्बेडेड इमेज, CSS फ़ाइलें, या स्क्रिप्ट्स (यदि आपके HTML ने उनका रेफ़रेंस दिया हो)। + +आप किसी भी आर्काइव मैनेजर से ZIP खोलकर संरचना की जाँच कर सकते हैं। + +--- + +## परिणाम की जाँच (वैकल्पिक) + +यदि आप डिस्क पर एक्सट्रैक्ट किए बिना प्रोग्रामेटिकली आर्काइव की जाँच करना चाहते हैं: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +सामान्य आउटपुट: + +``` +- index.html (452 bytes) +``` + +यदि आपके पास इमेज या CSS थे, तो वे अतिरिक्त एंट्रीज़ के रूप में दिखेंगे। यह त्वरित जाँच पुष्टि करती है कि **create html zip archive** अपेक्षित रूप से काम किया। + +--- + +## सामान्य प्रश्न एवं किनारे के मामलों + +| प्रश्न | उत्तर | +|----------|--------| +| **यदि मुझे ZIP को सीधे रिस्पॉन्स स्ट्रीम में लिखना हो तो क्या करें?** | `document.Save` के बाद `MyStorage` से प्राप्त `MemoryStream` को रिटर्न करें। इसे `byte[]` में कास्ट करके `HttpResponse.Body` में लिखें। | +| **मेरे HTML में बाहरी URLs रेफ़रेंस हैं—क्या वे डाउनलोड हो जाएंगे?** | नहीं। Aspose केवल उन रिसोर्सेज़ को पैक करता है जो *एम्बेडेड* हैं (जैसे `` या लोकल फ़ाइलें)। रिमोट एसेट्स को पहले डाउनलोड करके मार्कअप में अपडेट करना होगा। | +| **`OutputStorage` प्रॉपर्टी डिप्रिकेटेड है—क्या इसे अनदेखा करें?** | यह अभी भी काम करता है, लेकिन नया `ZipOutputStorage` समान API के साथ अलग नाम प्रदान करता है। यदि आप वॉर्निंग‑फ्री बिल्ड चाहते हैं तो `OutputStorage` को `ZipOutputStorage` से बदल दें। | +| **क्या मैं ZIP को एन्क्रिप्ट कर सकता हूँ?** | हाँ। सेव करने के बाद `System.IO.Compression.ZipArchive` से फ़ाइल खोलें और `SharpZipLib` जैसी थर्ड‑पार्टी लाइब्रेरी से पासवर्ड सेट करें। Aspose स्वयं एन्क्रिप्शन प्रदान नहीं करता। | + +--- + +## पूर्ण कार्यशील उदाहरण (कॉपी‑पेस्ट) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +प्रोग्राम चलाएँ, `output.zip` खोलें, और आप एकल `index.html` फ़ाइल देखेंगे जो ब्राउज़र में खोलने पर “Hello from ZIP!” हेडिंग रेंडर करता है। + +--- + +## निष्कर्ष + +अब आप **C# में HTML को ZIP के रूप में सहेजना** जानते हैं, एक **कस्टम स्टोरेज** क्लास का उपयोग करके, **HTML को ZIP में एक्सपोर्ट** करना, और एक **HTML zip archive** बनाना जो वितरण के लिए तैयार है। यह पैटर्न लचीला है—`MemoryStream` को क्लाउड स्ट्रीम से बदलें, एन्क्रिप्शन जोड़ें, या इसे वेब API में इंटीग्रेट करें जो ज़रूरत पड़ने पर ZIP रिटर्न करता है। + +अगला कदम तैयार है? पूरी‑तरह की वेब पेज को इमेज और स्टाइल्स के साथ फीड करें, या स्टोरेज को Azure Blob Storage से कनेक्ट करें ताकि स्थानीय फ़ाइल सिस्टम को पूरी तरह बायपास किया जा सके। Aspose.HTML की ZIP क्षमताओं को आपके अपने स्टोरेज लॉजिक के साथ मिलाकर संभावनाएँ असीमित हैं। + +कोडिंग का आनंद लें, और आपके आर्काइव हमेशा व्यवस्थित रहें! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hongkong/net/generate-jpg-and-png-images/_index.md b/html/hongkong/net/generate-jpg-and-png-images/_index.md index 33103bd04..dcc5d5a87 100644 --- a/html/hongkong/net/generate-jpg-and-png-images/_index.md +++ b/html/hongkong/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET 提供了一種將 HTML 轉換為映像的簡單方法。 了解如何在使用 Aspose.HTML for .NET 將 DOCX 轉換為 PNG 或 JPG 時啟用抗鋸齒,以提升圖像品質。 ### [使用 Aspose.HTML 在 .NET 中將 docx 轉換為 png 並建立 zip 壓縮檔 C# 教學](./convert-docx-to-png-create-zip-archive-c-tutorial/) 學習如何使用 Aspose.HTML for .NET 將 docx 轉換為 png,並將圖像打包成 zip 壓縮檔的完整步驟。 +### [使用 Aspose.HTML 在 .NET 中將 HTML 轉換為 PNG – 完整 C# 教學與 ZIP 匯出](./convert-html-to-png-full-c-guide-with-zip-export/) +完整示範如何使用 Aspose.HTML for .NET 將 HTML 轉換為 PNG,並將結果打包為 ZIP 檔案。 ## 結論 diff --git a/html/hongkong/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/hongkong/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..69533d11c --- /dev/null +++ b/html/hongkong/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-03-21 +description: 將 HTML 轉換為 PNG,並在將 HTML 儲存為 ZIP 的同時渲染 HTML 為圖像。學習如何套用字型樣式於 HTML,並在幾個步驟內為 + p 元素加粗。 +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: zh-hant +og_description: 快速將 HTML 轉換為 PNG。本指南說明如何將 HTML 渲染為圖像、將 HTML 儲存為 ZIP、套用字體樣式於 HTML,並為 + p 元素加粗。 +og_title: 將 HTML 轉換為 PNG – 完整 C# 教學 +tags: +- Aspose +- C# +title: 將 HTML 轉換為 PNG – 完整 C# 指南與 ZIP 匯出 +url: /zh-hant/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 將 HTML 轉換為 PNG – 完整 C# 指南與 ZIP 匯出 + +是否曾需要 **將 HTML 轉換為 PNG**,卻不確定哪個函式庫能在不使用無頭瀏覽器的情況下完成?你並不孤單。無論是電子郵件縮圖、文件預覽,或是快速檢視圖像,將網頁轉成靜態圖片都是實務需求。 + +好消息是,使用 Aspose.HTML 你可以 **將 HTML 渲染為圖像**、即時調整標記,甚至 **將 HTML 儲存為 ZIP** 以便日後分發。本教學將示範一個完整、可直接執行的範例,**套用字體樣式 HTML**(即 **為 p 元素加粗**),最後產生 PNG 檔案。完成後,你將擁有一個單一的 C# 類別,負責從載入頁面到封存資源的全部工作。 + +## 需要的環境 + +- .NET 6.0 或更新版本(API 亦支援 .NET Core) +- Aspose.HTML for .NET 6+(NuGet 套件 `Aspose.Html`) +- 基本的 C# 語法概念(不需要進階知識) + +就這麼簡單。無需外部瀏覽器、無需 phantomjs,純粹使用受管理的程式碼。 + +## 第一步 – 載入 HTML 文件 + +首先將來源檔案(或 URL)載入 `HTMLDocument` 物件。此步驟是之後 **將 HTML 渲染為圖像** 與 **將 HTML 儲存為 ZIP** 的基礎。 + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*為什麼重要:* `HTMLDocument` 類別會解析標記、建立 DOM,並解析連結的資源(CSS、圖片、字型)。若沒有正確的文件物件,就無法操作樣式或進行渲染。 + +## 第二步 – 套用字體樣式 HTML(為 p 加粗) + +接下來,我們會 **套用字體樣式 HTML**,遍歷所有 `

` 元素,將其 `font-weight` 設為 bold。這是以程式方式 **為 p 標籤加粗**,而不必直接修改原始檔案。 + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*小技巧:* 若只想加粗特定子集,可將選擇器改為更具體的,例如 `"p.intro"`。 + +## 第三步 – 將 HTML 渲染為圖像(將 HTML 轉換為 PNG) + +DOM 準備好後,設定 `ImageRenderingOptions` 並呼叫 `RenderToImage`。這就是 **將 HTML 轉換為 PNG** 的魔法所在。 + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*為什麼選項重要:* 設定固定寬高可避免輸出過大,抗鋸齒則提供更平滑的視覺效果。若想要較小的檔案,也可以將 `options` 的 `ImageFormat` 改為 `ImageFormat.Jpeg`。 + +## 第四步 – 將 HTML 儲存為 ZIP(打包資源) + +通常需要將原始 HTML 與其 CSS、圖片、字型一起發佈。Aspose.HTML 的 `ZipArchiveSaveOptions` 正好提供此功能。我們同時加入自訂的 `ResourceHandler`,讓所有外部資產寫入與壓縮檔同一資料夾。 + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*邊緣情況:* 若 HTML 參照需要驗證的遠端圖片,預設處理器會失敗。此時可擴充 `MyResourceHandler` 以注入 HTTP 標頭。 + +## 第五步 – 在單一 Converter 類別中串接全部流程 + +以下是完整、可直接執行的類別,將前面的步驟全部整合。只要複製貼上到 Console 應用程式,呼叫 `Convert`,即可看到產生的檔案。 + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### 預期輸出 + +執行上述程式碼後,`outputDirectory` 內會出現兩個檔案: + +| 檔案 | 說明 | +|------|------| +| `page.png` | 1200 × 800 的 PNG,呈現來源 HTML,且所有段落皆 **加粗**。 | +| `archive.zip` | 包含原始 `input.html`、其 CSS、圖片與任何 Web‑fonts 的 ZIP 壓縮檔,適合離線分發。 | + +你可以使用任何圖像檢視器開啟 `page.png`,驗證加粗樣式是否正確;解壓 `archive.zip` 後,即可看到未經修改的 HTML 及其資源。 + +## 常見問題與注意事項 + +- **如果 HTML 包含 JavaScript 會怎樣?** + Aspose.HTML 在渲染時 **不會執行腳本**,因此動態內容不會出現在圖像中。若需要完整渲染的頁面,仍須使用無頭瀏覽器;但對於靜態模板,此方式更快且更輕量。 + +- **可以改成 JPEG 或 BMP 格式嗎?** + 可以——只要將 `ImageRenderingOptions` 的 `ImageFormat` 屬性改為 `ImageFormat.Jpeg`(或 `ImageFormat.Bmp`)即可。 + +- **需要手動釋放 `HTMLDocument` 嗎?** + 此類別實作 `IDisposable`。在長時間執行的服務中,建議使用 `using` 區塊或在使用完畢後呼叫 `document.Dispose()`。 + +- **自訂的 `MyResourceHandler` 如何運作?** + 它會接收每一個外部資源(CSS、圖片、字型),並寫入你指定的資料夾,確保 ZIP 中完整保留 HTML 所引用的所有檔案。 + +## 結論 + +現在你已擁有一套精簡、可投入生產環境的解決方案,能 **將 HTML 轉換為 PNG**、**將 HTML 渲染為圖像**、**將 HTML 儲存為 ZIP**、**套用字體樣式 HTML**,以及 **為 p 加粗**——全部只需少量 C# 程式碼。此程式碼自包含、相容 .NET 6+,可直接嵌入任何需要快速取得網頁視覺快照的後端服務。 + +想更進一步嗎?嘗試調整渲染尺寸、實驗其他 CSS 屬性(如 `font-family` 或 `color`),或將此轉換器整合到 ASP.NET Core 端點,讓它即時回傳 PNG。可能性無限,而使用 Aspose.HTML 讓你免除沉重的瀏覽器相依。 + +如果在實作過程中遇到問題或有擴充想法,歡迎在下方留言。祝編程愉快! + +![將 HTML 轉換為 PNG 範例](example.png "將 HTML 轉換為 PNG 範例") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hongkong/net/html-document-manipulation/_index.md b/html/hongkong/net/html-document-manipulation/_index.md index 3cbe22369..9dbb868c8 100644 --- a/html/hongkong/net/html-document-manipulation/_index.md +++ b/html/hongkong/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aspose.HTML for .NET 因其簡單性和強大功能而脫穎而出。它使您 使用 Aspose.HTML for .NET 釋放 Web 開發的潛力。輕鬆建立、轉換和操作 HTML 文件。 ### [在 C# 中從字串建立 HTML – 自訂資源處理程式指南](./create-html-from-string-in-c-custom-resource-handler-guide/) 了解如何使用 Aspose.HTML for .NET 從字串建立 HTML,並透過自訂資源處理程式進行管理。 +### [在 C# 中建立 HTML 文件 – 步驟指南](./create-html-document-c-step-by-step-guide/) +了解如何在 C# 中使用 Aspose.HTML 建立 HTML 文件,提供完整步驟與範例說明。 ## 結論 diff --git a/html/hongkong/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/hongkong/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..135b6dc72 --- /dev/null +++ b/html/hongkong/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,186 @@ +--- +category: general +date: 2026-03-21 +description: 使用 C# 建立 HTML 文件,學習如何透過 id 取得元素、定位元素、變更 HTML 元素樣式,並使用 Aspose.Html 加粗與斜體。 +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: zh-hant +og_description: 使用 C# 建立 HTML 文件,即時學會透過 ID 取得元素、定位元素、變更 HTML 元素樣式,並加入粗體與斜體,提供清晰的程式碼範例。 +og_title: 使用 C# 建立 HTML 文件 – 完整程式設計指南 +tags: +- Aspose.Html +- C# +- DOM manipulation +title: 建立 HTML 文件(C#)– 步驟指南 +url: /zh-hant/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 建立 HTML 文件 C# – 步驟指南 + +曾經需要從頭 **create HTML document C#** 並且調整單一段落的外觀嗎?你並不孤單。在許多網頁自動化專案中,你會產生一個 HTML 檔案,依 ID 找到標籤,然後套用一些樣式——通常是粗體 + 斜體——而不需要開啟瀏覽器。 + +在本教學中,我們將一步步示範:在 C# 中建立 HTML 文件,**get element by id**,**locate element by id**,**change HTML element style**,最後使用 Aspose.Html 函式庫 **add bold italic**。完成後,你將擁有一段可直接放入任何 .NET 專案的完整可執行程式碼片段。 + +## 需要的條件 + +- .NET 6 或更新版本(此程式碼亦可於 .NET Framework 4.7+ 執行) +- Visual Studio 2022(或任何你喜歡的編輯器) +- **Aspose.Html** NuGet 套件(`Install-Package Aspose.Html`) + +就這樣——不需要額外的 HTML 檔案,也不需要網頁伺服器,只要幾行 C# 程式碼。 + +## 建立 HTML 文件 C# – 初始化文件 + +首先,你需要一個可供 Aspose.Html 引擎使用的 `HTMLDocument` 物件。可以把它想像成打開一本全新的筆記本,讓你在上面撰寫標記。 + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **為什麼這很重要:** 將原始字串傳遞給 `HTMLDocument`,即可避免檔案 I/O,所有內容都保留在記憶體中——非常適合單元測試或即時產生。 + +## 取得元素(Get Element by ID) – 找到段落 + +現在文件已存在,我們需要 **get element by id**。DOM API 提供 `GetElementById`,若找到對應 ID,會回傳 `IElement` 參考,否則回傳 `null`。 + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **專業提示:** 即使我們的標記很小,加入 null 檢查也能在相同邏輯被重複用於較大、動態的頁面時避免麻煩。 + +## 依 ID 定位元素 – 替代方法 + +有時你可能已經取得文件根節點的參考,並且偏好以查詢方式搜尋。使用 CSS 選擇器(`QuerySelector`)是另一種 **locate element by id** 的方法: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **何時使用哪個?** `GetElementById` 稍快,因為它直接以雜湊查找。當需要複雜選擇器(例如 `div > p.highlight`)時,`QuerySelector` 更有優勢。 + +## 變更 HTML 元素樣式 – 加入粗斜體 + +取得元素後,下一步是 **change HTML element style**。Aspose.Html 提供 `Style` 物件,可調整 CSS 屬性,或使用方便的 `WebFontStyle` 列舉一次套用多種字體樣式。 + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +那一行程式碼會將元素的 `font-weight` 設為 `bold`、`font-style` 設為 `italic`。在底層,Aspose.Html 會將列舉轉換成相應的 CSS 字串。 + +### 完整範例 + +將所有部件組合起來,即可得到一個緊湊且自包含的程式,你可以立即編譯並執行: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**預期輸出** + +``` +Rendered HTML: +

Hello world

+``` + +`

` 標籤現在帶有內聯 `style` 屬性,使文字同時呈現粗體與斜體——正是我們想要的效果。 + +## 邊緣情況與常見陷阱 + +| Situation | What to Watch For | How to Handle | +|-----------|-------------------|---------------| +| **ID 不存在** | `GetElementById` 回傳 `null`。 | 拋出例外或回退至預設元素。 | +| **多個元素共用相同 ID** | HTML 規範要求 ID 必須唯一,但實務頁面有時會違反此規則。 | `GetElementById` 會回傳第一個匹配項;若需處理重複項,請考慮使用 `QuerySelectorAll`。 | +| **樣式衝突** | 現有的內聯樣式可能會被覆寫。 | 改為向 `Style` 物件追加,而非設定整個 `style` 字串:`paragraph.Style.FontWeight = \"bold\"; paragraph.Style.FontStyle = \"italic\";` | +| **在瀏覽器中的渲染** | 若元素已具備更高特異性的 CSS 類別,部分瀏覽器會忽略 `WebFontStyle`。 | 必要時可透過 `paragraph.Style.SetProperty(\"font-weight\", \"bold\", \"important\");` 加上 `!important`。 | + +## 真實專案的專業提示 + +- **快取文件**:如果你要處理大量元素,為每個小片段建立新的 `HTMLDocument` 會影響效能。 +- **合併樣式變更**:在單一 `Style` 交易中完成,以避免多次 DOM 重新排版。 +- **利用 Aspose.Html 的渲染引擎**,將最終文件匯出為 PDF 或影像——非常適合報表工具。 + +## 視覺確認(可選) + +如果你想在瀏覽器中查看結果,可以將渲染後的字串儲存為 `.html` 檔案: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +開啟 `output.html`,即可看到 **Hello world** 以粗體 + 斜體顯示。 + +![Create HTML Document C# 範例,顯示粗斜體段落](/images/create-html-document-csharp.png "Create HTML Document C# – 渲染輸出") + +*Alt text: Create HTML Document C# – 渲染輸出,包含粗斜體文字。* + +## 結論 + +我們剛剛 **created an HTML document C#**、**got element by id**、**located element by id**、**changed HTML element style**,最後 **added bold italic**——全部只用了幾行程式碼,藉由 Aspose.Html 完成。此方法簡單直接,適用於任何 .NET 環境,且可擴展至更大的 DOM 操作。 + +準備好進一步了嗎?試著將 `WebFontStyle` 換成其他列舉,例如 `Underline`,或手動結合多種樣式。亦可嘗試載入外部 HTML 檔案,對數百個元素套用相同技巧。沒有上限,現在你已擁有堅實的基礎可供發揮。 + +祝編程愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hongkong/net/html-extensions-and-conversions/_index.md b/html/hongkong/net/html-extensions-and-conversions/_index.md index 3d146ada2..8af280da6 100644 --- a/html/hongkong/net/html-extensions-and-conversions/_index.md +++ b/html/hongkong/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML for .NET 不只是一個函式庫;它還是一個函式庫。它 ## HTML 擴充功能與轉換教學課程 ### [使用 Aspose.HTML 將 .NET 中的 HTML 轉換為 PDF](./convert-html-to-pdf/) 使用 Aspose.HTML for .NET 輕鬆將 HTML 轉換為 PDF。遵循我們的逐步指南,釋放 HTML 到 PDF 轉換的強大功能。 +### [使用 Aspose.HTML 從 HTML 建立 PDF – C# 步驟指南](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +使用 Aspose.HTML for .NET 於 C# 中將 HTML 轉換為 PDF,提供完整的逐步說明與範例程式碼。 ### [使用 C# 從 HTML 建立 PDF – 完整步驟指南](./create-pdf-from-html-c-step-by-step-guide/) 使用 Aspose.HTML for .NET,透過 C# 將 HTML 轉換為 PDF 的完整步驟說明與範例。 ### [使用 Aspose.HTML 將 EPUB 轉換為 .NET 中的映像](./convert-epub-to-image/) @@ -61,6 +63,8 @@ Aspose.HTML for .NET 不只是一個函式庫;它還是一個函式庫。它 使用 Aspose.HTML 將 .NET 中的 HTML 轉換為 MHTML - 高效 Web 內容歸檔的逐步指南。了解如何使用 Aspose.HTML for .NET 建立 MHTML 檔案。 ### [使用 Aspose.HTML 將 .NET 中的 HTML 轉換為 PNG](./convert-html-to-png/) 了解如何使用 Aspose.HTML for .NET 來操作和轉換 HTML 文件。有效 .NET 開發的逐步指南。 +### [使用 Aspose.HTML 將 .NET 中的 HTML 轉換為圖像](./convert-html-to-image-in-c-complete-guide/) +了解如何使用 Aspose.HTML for .NET 在 C# 中將 HTML 轉換為圖像。提供程式碼範例與完整步驟說明。 ### [使用 Aspose.HTML 將 .NET 中的 HTML 轉換為 TIFF](./convert-html-to-tiff/) 了解如何使用 Aspose.HTML for .NET 將 HTML 轉換為 TIFF。請依照我們的逐步指南進行高效率的網路內容優化。 ### [使用 Aspose.HTML 將 .NET 中的 HTML 轉換為 XPS](./convert-html-to-xps/) @@ -70,9 +74,13 @@ Aspose.HTML for .NET 不只是一個函式庫;它還是一個函式庫。它 ### [建立具樣式文字的 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# 範例與步驟說明。 +使用 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-as-zip-in-c-complete-guide-with-custom-storage/) +說明如何在 C# 中使用 Aspose.HTML 將 HTML 壓縮為 ZIP,並自訂儲存位置與方式。 +### [使用 Aspose.HTML 將 HTML 壓縮為 ZIP – 完整指南](./how-to-zip-html-with-aspose-html-complete-guide/) +使用 Aspose.HTML for .NET 在 C# 中將 HTML 壓縮為 ZIP,提供完整步驟與範例說明。 ## 結論 diff --git a/html/hongkong/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/hongkong/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..d1408088a --- /dev/null +++ b/html/hongkong/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,185 @@ +--- +category: general +date: 2026-03-21 +description: 使用 Aspose.HTML 在 C# 中將 HTML 轉換為圖片。了解如何將 HTML 儲存為 PNG、設定圖片尺寸渲染,並在幾個步驟內將圖片寫入檔案。 +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: zh-hant +og_description: 快速將 HTML 轉換為圖像。此指南說明如何將 HTML 儲存為 PNG、設定圖像尺寸渲染,並使用 Aspose.HTML 將圖像寫入檔案。 +og_title: 在 C# 中將 HTML 轉換為圖片 – 逐步指南 +tags: +- Aspose.HTML +- C# +- Image Rendering +title: 在 C# 中將 HTML 轉換為圖片 – 完整指南 +url: /zh-hant/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中將 HTML 轉換為圖像 – 完整指南 + +是否曾需要將 **HTML 轉換為圖像** 以作為儀表板縮圖、電郵預覽或 PDF 報告?這種情況比你想像的更常出現,尤其是當你需要嵌入動態網頁內容時。 + +好消息是?使用 Aspose.HTML,你只需幾行程式碼即可 **convert HTML to image**,同時還會學習如何 *save HTML as PNG*、控制輸出尺寸,以及 *write image to file*,輕鬆完成。 + +在本教學中,我們將逐步說明所有必須了解的內容:從載入遠端頁面、調整渲染尺寸,到最終將結果保存為磁碟上的 PNG 檔案。無需外部工具或繁雜的命令列技巧——只需純 C# 程式碼,即可直接嵌入任何 .NET 專案。 + +## 您將學到的內容 + +- 如何使用 Aspose.HTML 的 `HTMLDocument` 類別 **render webpage to PNG**。 +- 逐步說明 **set image size rendering**,使輸出符合版面需求。 +- 安全地 **write image to file**,處理串流與檔案路徑的方法。 +- 排除常見問題的技巧,例如缺少字型或網路逾時。 + +### 前置條件 + +- .NET 6.0 或更新版本(API 亦支援 .NET Framework,但建議使用 .NET 6 以上)。 +- 參考 Aspose.HTML for .NET 的 NuGet 套件 (`Aspose.Html`)。 +- 具備基本的 C# 及 async/await 知識(非必須,但有助於理解)。 + +如果你已具備上述條件,即可立即開始將 HTML 轉換為圖像。 + +## 第一步:載入網頁 – HTML 轉換為圖像的基礎 + +在任何渲染發生之前,你需要一個代表欲擷取頁面的 `HTMLDocument` 實例。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*為什麼這很重要:* `HTMLDocument` 會解析 HTML、解析 CSS 並建立 DOM。若文件無法載入(例如網路問題),後續渲染將產生空白圖像。請務必先確認 URL 可連線再繼續。 + +## 第二步:設定圖像尺寸渲染 – 控制寬度、高度與品質 + +Aspose.HTML 讓你使用 `ImageRenderingOptions` 精細調整輸出尺寸。在此你可以 **set image size rendering** 以符合目標版面。 + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*專業提示:* 若省略 `Width` 與 `Height`,Aspose.HTML 會使用頁面的內在尺寸,對於響應式設計可能不穩定。明確指定尺寸可確保你的 **save HTML as PNG** 輸出如預期般呈現。 + +## 第三步:寫入圖像檔案 – 保存渲染後的 PNG + +現在文件已就緒且渲染選項已設定,你終於可以 **write image to file**。使用 `FileStream` 可確保檔案安全建立,即使資料夾尚未存在亦不例外。 + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +此程式碼執行完畢後,你會在指定位置看到 `page.png`。你已成功 **rendered webpage to PNG**,並以簡單的方式寫入磁碟。 + +### 預期結果 + +使用任何圖像檢視器開啟 `C:\Temp\page.png`。你應該會看到 `https://example.com` 的完整快照,解析度為 1024 × 768 像素,且因抗鋸齒而邊緣平滑。若頁面包含動態內容(例如 JavaScript 產生的元素),只要在渲染前 DOM 已完整載入,即會被捕捉。 + +## 第四步:處理例外情況 – 字型、驗證與大型頁面 + +雖然基本流程適用於大多數公開網站,但實務情境常會出現挑戰: + +| 情況 | 處理方式 | +|-----------|------------| +| **Custom fonts not loading** | 將字型檔案本地嵌入,並使用 `htmlDoc.Fonts.Add("path/to/font.ttf")`。 | +| **Pages behind authentication** | 使用接受 `HttpWebRequest`(含 Cookie 或 Token)的 `HTMLDocument` 重載。 | +| **Very tall pages** | 增加 `Height` 或在 `ImageRenderingOptions` 中啟用 `PageScaling` 以避免截斷。 | +| **Memory usage spikes** | 使用接受 `Rectangle` 區域的 `RenderToImage` 重載,分段渲染。 | + +處理上述 *write image to file* 的細節,可確保你的 `convert html to image` 流程在生產環境中保持穩定。 + +## 第五步:完整範例 – 可直接複製貼上 + +以下為完整程式碼,已可直接編譯。它包含所有步驟、錯誤處理與必要註解。 + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +執行此程式後,你會在主控台看到確認訊息。PNG 檔案將與你在瀏覽器手動 **render webpage to PNG** 並截圖時的結果完全相同,只是更快且全自動化。 + +## 常見問題 + +**Q: 我可以轉換本機 HTML 檔案而非 URL 嗎?** +當然可以。只要將 URL 改為檔案路徑:`new HTMLDocument(@"C:\myPage.html")`。 + +**Q: 使用 Aspose.HTML 是否需要授權?** +免費評估授權可用於開發與測試。正式上線時,請購買授權以移除評估浮水印。 + +**Q: 若頁面在初始載入後仍透過 JavaScript 動態載入內容,該怎麼辦?** +Aspose.HTML 會在解析期間同步執行 JavaScript,但長時間執行的腳本可能需要手動延遲。你可以在渲染前使用 `HTMLDocument.WaitForReadyState`。 + +## 結論 + +現在你已擁有完整、端對端的 **convert HTML to image** 解決方案於 C#。依照上述步驟,你可以 **save HTML as PNG**、精確 **set image size rendering**,並在任何 Windows 或 Linux 環境中自信地 **write image to file**。 + +從簡單的螢幕截圖到自動化報告產生,此技術皆能良好擴展。接下來,可嘗試其他輸出格式如 JPEG 或 BMP,或將程式碼整合至 ASP.NET Core API,直接回傳 PNG 給呼叫端。可能性幾乎無限。 + +祝程式開發順利,願你的渲染圖像永遠保持像素完美! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hongkong/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/hongkong/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..fa836e3c6 --- /dev/null +++ b/html/hongkong/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-03-21 +description: 使用 Aspose HTML 快速將 HTML 轉換為 PDF。學習如何將 HTML 渲染成 PDF、將 HTML 轉為 PDF,以及在簡潔教學中如何使用 + Aspose。 +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: zh-hant +og_description: 使用 Aspose 在 C# 中從 HTML 建立 PDF。本指南說明如何將 HTML 轉換為 PDF、如何渲染 HTML 為 PDF,以及如何有效使用 + Aspose。 +og_title: 從 HTML 建立 PDF – 完整 Aspose C# 教程 +tags: +- Aspose +- C# +- PDF generation +title: 使用 Aspose 從 HTML 產生 PDF – C# 一步一步教學 +url: /zh-hant/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose 從 HTML 建立 PDF – 步驟說明 C# 教學 + +曾經需要**從 HTML 建立 PDF**,但不確定哪個函式庫能提供像素完美的結果嗎?你並不孤單。許多開發者在嘗試將網頁片段轉換為可列印文件時,常會遇到文字模糊或版面錯亂的問題。 + +好消息是 Aspose HTML 讓整個流程變得毫不費力。在本教學中,我們將逐步說明 **render HTML to PDF** 所需的完整程式碼,探討每個設定為何重要,並示範如何 **convert HTML to PDF** 而不需要任何隱藏的技巧。完成後,你將了解 **how to use Aspose**,在任何 .NET 專案中都能可靠產生 PDF。 + +## 前置條件 – 開始之前需要準備什麼 + +- **.NET 6.0 或更新版本**(此範例亦可在 .NET Framework 4.7+ 上執行) +- **Visual Studio 2022** 或任何支援 C# 的 IDE +- **Aspose.HTML for .NET** NuGet 套件(免費試用版或正式授權版) +- 基本的 C# 語法概念(不需要深入的 PDF 知識) + +如果你已具備上述條件,就可以直接開始。若尚未安裝,請先取得最新的 .NET SDK,然後使用以下指令安裝 NuGet 套件: + +```bash +dotnet add package Aspose.HTML +``` + +這一行指令會把 **aspose html to pdf** 轉換所需的所有元件全部拉下來。 + +--- + +## Step 1: 設定專案以建立 PDF from HTML + +首先建立一個新的 Console 應用程式(或將程式碼整合到現有服務中)。以下是一個最小的 `Program.cs` 骨架: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** 若在舊範例中看到 `Aspise.Html.Rendering.Text`,請改成 `Aspose.Html.Rendering.Text`。拼寫錯誤會導致編譯錯誤。 + +使用正確的命名空間可確保編譯器能找到稍後會用到的 **TextOptions** 類別。 + +## Step 2: 建立 HTML 文件(Render HTML to PDF) + +現在建立來源 HTML。Aspose 支援傳入原始字串、檔案路徑,甚至是 URL。此示範採用最簡單的方式: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +為什麼要傳入字串?這樣可以避免檔案系統 I/O、加快轉換速度,且能保證程式碼中看到的 HTML 與實際渲染的內容完全一致。若想從檔案載入,只需將建構子參數換成檔案 URI 即可。 + +## Step 3: 精細調校文字渲染(Convert HTML to PDF with Better Quality) + +文字渲染往往決定 PDF 是清晰還是模糊。Aspose 提供 `TextOptions` 類別,可啟用子像素提示(sub‑pixel hinting)——對高 DPI 輸出至關重要。 + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +啟用 `UseHinting` 尤其適用於來源 HTML 包含自訂字型或字體尺寸較小的情況。若未啟用,最終 PDF 可能會出現鋸齒狀邊緣。 + +## Step 4: 將文字選項附加至 PDF 渲染設定(How to Use Aspose) + +接著,我們把文字選項綁定到 PDF 渲染器。這正是 **aspose html to pdf** 發揮威力的地方——從頁面大小到壓縮方式皆可自行調整。 + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +若你對預設的 A4 大小沒意見,可以省略 `PageSetup`。重點是 `TextOptions` 物件位於 `PdfRenderingOptions` 之中,這樣才能告訴 Aspose *如何* 渲染文字。 + +## Step 5: 渲染 HTML 並儲存 PDF(Convert HTML to PDF) + +最後,我們將輸出串流寫入檔案。使用 `using` 區塊可確保即使發生例外,檔案句柄也會正確關閉。 + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +執行程式後,你會在執行檔旁看到 `output.pdf`。開啟它,你應該會看到乾淨的標題與段落——完全與 HTML 字串中定義的內容相符。 + +### 預期輸出 + +![create pdf from html example output](https://example.com/images/pdf-output.png "create pdf from html example output") + +*此截圖顯示產生的 PDF,標題「Hello, Aspose!」因文字提示而呈現銳利。* + +--- + +## 常見問題與邊緣案例 + +### 1. 如果我的 HTML 參照了外部資源(圖片、CSS)? + +Aspose 會根據文件的基礎 URI 解析相對 URL。若你傳入的是原始字串,需手動設定基礎 URI: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +如此一來,任何 `` 都會以 `C:/MyProject/` 為基準去尋找。 + +### 2. 如何嵌入伺服器上未安裝的字型? + +在 ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### 步驟 4:設定儲存選項以使用自訂儲存 + +`HtmlSaveOptions` 讓我們告訴 Aspose 將所有內容打包成 ZIP 檔。`OutputStorage` 屬性(舊版)會接收我們的 `MyStorage` 實例。 + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **注意:** 在 Aspose HTML 23.9+ 中,此屬性仍名為 `OutputStorage`,但已標記為過時。較新的替代方案是 `ZipOutputStorage`。以下程式碼同時支援兩者,因為介面相同。 + +### 步驟 5:將文件儲存為 ZIP 壓縮檔 + +選擇目標資料夾(或串流),讓 Aspose 完成繁重的工作。 + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +程式執行完畢後,你會在 `output.zip` 中看到: + +* `index.html` – 主要文件。 +* 任何嵌入的圖片、CSS 檔或腳本(若你的 HTML 有引用)。 + +你可以使用任何壓縮檔管理工具開啟 ZIP,以驗證其結構。 + +--- + +## 驗證結果(可選) + +若想以程式方式檢查壓縮檔而不將其解壓至磁碟: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +典型輸出: + +``` +- index.html (452 bytes) +``` + +如果有圖片或 CSS,會顯示為額外的條目。此快速檢查確認 **create html zip archive** 如預期運作。 + +--- + +## 常見問題與邊緣情況 + +| 問題 | 答案 | +|----------|--------| +| **如果需要將 ZIP 直接寫入回應串流該怎麼辦?** | 在 `document.Save` 後,從 `MyStorage` 取得的 `MemoryStream` 回傳。將其轉型為 `byte[]`,再寫入 `HttpResponse.Body`。 | +| **我的 HTML 參考外部 URL——會被下載嗎?** | 不會。Aspose 只會打包 *嵌入式* 資源(例如 `` 或本機檔案)。若為遠端資產,必須先下載並調整標記。 | +| **`OutputStorage` 屬性已標記為過時——我可以忽略嗎?** | 它仍可使用,但較新的 `ZipOutputStorage` 以不同名稱提供相同 API。若希望編譯時無警告,請將 `OutputStorage` 改為 `ZipOutputStorage`。 | +| **我可以加密 ZIP 嗎?** | 可以。儲存後,使用 `System.IO.Compression.ZipArchive` 開啟檔案,並透過第三方函式庫(如 `SharpZipLib`)設定密碼。Aspose 本身不提供加密功能。 | + +--- + +## 完整可執行範例(複製貼上) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +執行程式,開啟 `output.zip`,你會看到唯一的 `index.html` 檔案,於瀏覽器開啟時會顯示 “Hello from ZIP!” 標題。 + +--- + +## 結論 + +現在你已了解如何在 C# 中使用 **自訂儲存** 類別 **將 HTML 儲存為 ZIP**,以及如何 **將 HTML 匯出為 ZIP**,並建立可供發佈的 **HTML zip archive**。此模式相當彈性——可將 `MemoryStream` 換成雲端串流、加入加密,或整合至 Web API,按需回傳 ZIP。 + +準備好進一步了嗎?試著輸入包含圖片與樣式的完整網頁,或將儲存連接至 Azure Blob Storage,徹底避免本機檔案系統。結合 Aspose.HTML 的 ZIP 功能與自訂儲存邏輯,無所不能。 + +祝程式開發順利,願你的壓縮檔永遠整潔! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hungarian/net/generate-jpg-and-png-images/_index.md b/html/hungarian/net/generate-jpg-and-png-images/_index.md index dc2c2b0ac..d0af56e6c 100644 --- a/html/hungarian/net/generate-jpg-and-png-images/_index.md +++ b/html/hungarian/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Tanulja meg az Aspose.HTML for .NET használatát HTML-dokumentumok kezeléséhe Ismerje meg, hogyan állíthatja be az antialiasingot a DOCX dokumentumok PNG vagy JPG képekké konvertálásakor az Aspose.HTML for .NET használatával. ### [docx konvertálása png-re – zip archívum létrehozása C# oktatóanyag](./convert-docx-to-png-create-zip-archive-c-tutorial/) Ismerje meg, hogyan konvertálhat docx fájlokat png képekké, majd csomagolhatja őket zip archívumba C#-ban az Aspose.HTML segítségével. +### [HTML konvertálása PNG-re – Teljes C# útmutató ZIP exporttal](./convert-html-to-png-full-c-guide-with-zip-export/) +Ismerje meg, hogyan konvertálhat HTML-t PNG-re C#-ban, és exportálhatja a képeket ZIP archívumba az Aspose.HTML for .NET segítségével. ## Következtetés diff --git a/html/hungarian/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/hungarian/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..82291ce63 --- /dev/null +++ b/html/hungarian/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Konvertálja a HTML-t PNG-re, és renderelje a HTML-t képként, miközben + a HTML-t ZIP-be menti. Tanulja meg, hogyan alkalmazzon betűstílust a HTML-ben, és + adjon félkövér formázást a p elemekhez néhány lépésben. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: hu +og_description: Konvertálja a HTML-t gyorsan PNG formátumba. Ez az útmutató bemutatja, + hogyan lehet a HTML-t képként megjeleníteni, a HTML-t ZIP-be menteni, betűstílust + alkalmazni a HTML-re, és félkövérrel kiemelni a p elemeket. +og_title: HTML konvertálása PNG-re – Teljes C# oktatóanyag +tags: +- Aspose +- C# +title: HTML konvertálása PNG-re – Teljes C# útmutató ZIP exporttal +url: /hu/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML konvertálása PNG‑re – Teljes C# útmutató ZIP exporttal + +Valaha szükséged volt **HTML konvertálásra PNG‑re**, de nem tudtad, melyik könyvtár tudja ezt megtenni fej nélküli böngésző használata nélkül? Nem vagy egyedül. Sok projektben—e‑mail bélyegképek, dokumentáció előnézetek vagy gyors‑nézet képek—egy weboldal statikus képpé alakítása valós igény. + +A jó hír? Az Aspose.HTML‑del **renderelheted a HTML‑t képként**, módosíthatod a markupot menet közben, sőt **mentheted a HTML‑t ZIP‑be** későbbi terjesztéshez. Ebben az útmutatóban egy teljes, futtatható példán keresztül mutatjuk be, hogyan **alkalmazzunk betűstílus HTML‑t**, konkrétan **félkövérre állítjuk a p** elemeket, mielőtt PNG fájlt generálnánk. A végére egyetlen C# osztályod lesz, amely mindent elvégez a lap betöltésétől a források archiválásáig. + +## Amire szükséged lesz + +- .NET 6.0 vagy újabb (az API .NET Core‑on is működik) +- Aspose.HTML for .NET 6+ (NuGet csomag `Aspose.Html`) +- Alapvető C# szintaxis ismeret (nincs szükség haladó koncepciókra) + +Ennyi. Nincs külső böngésző, nincs phantomjs, csak tiszta managed kód. + +## 1. lépés – HTML dokumentum betöltése + +Először betöltjük a forrásfájlt (vagy URL‑t) egy `HTMLDocument` objektumba. Ez a lépés a **render html as image** és a **save html to zip** későbbi műveletek alapja. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Miért fontos:* A `HTMLDocument` osztály elemzi a markupot, felépíti a DOM‑ot, és feloldja a hivatkozott erőforrásokat (CSS, képek, betűkészletek). Megfelelő dokumentumobjektum nélkül nem tudsz stílusokat módosítani vagy semmit renderelni. + +## 2. lépés – Betűstílus HTML alkalmazása (p elemek félkövérré tétele) + +Most **betűstílus HTML-t alkalmazunk** úgy, hogy végigiterálunk minden `

` elemen, és beállítjuk a `font-weight` értékét **bold**-ra. Ez a programozott módja annak, hogy **p** címkéket **félkövérre** tegyünk anélkül, hogy az eredeti fájlt módosítanánk. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Pro tipp:* Ha csak egy részhalmazt szeretnél félkövérré tenni, módosítsd a szelektort konkrétabbra, pl. `"p.intro"`. + +## 3. lépés – HTML renderelése képként (HTML konvertálása PNG‑re) + +A DOM készen áll, konfiguráljuk a `ImageRenderingOptions`‑t és meghívjuk a `RenderToImage`‑t. Itt történik a **convert html to png** varázslat. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Miért fontosak a beállítások:* A fix szélesség/magasság megakadályozza, hogy a kimenet túl nagy legyen, míg az antialiasing simább vizuális eredményt ad. Ha kisebb fájlméretet szeretnél, átállíthatod a `options`‑t `ImageFormat.Jpeg`‑re. + +## 4. lépés – HTML mentése ZIP‑be (Erőforrások csomagolása) + +Gyakran szükség van az eredeti HTML szállítására a CSS‑ével, képeivel és betűkészleteivel együtt. Az Aspose.HTML `ZipArchiveSaveOptions` pontosan ezt teszi. Emellett egy egyedi `ResourceHandler`‑t csatolunk, hogy minden külső erőforrás ugyanabba a mappába kerüljön, mint a archívum. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Különleges eset:* Ha a HTML távoli képekre hivatkozik, amelyek hitelesítést igényelnek, az alapértelmezett kezelő hibázik. Ebben az esetben kiterjesztheted a `MyResourceHandler`‑t HTTP fejlécek beszúrására. + +## 5. lépés – Minden összekapcsolása egyetlen konverter osztályban + +Az alábbiakban a teljes, azonnal futtatható osztály látható, amely összekapcsolja az előző lépéseket. Másold be egy konzolos alkalmazásba, hívd meg a `Convert` metódust, és figyeld, ahogy a fájlok megjelennek. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Várható kimenet + +A fenti kódrészlet futtatása után két fájlt találsz a `outputDirectory`‑ben: + +| File | Description | +|------|-------------| +| `page.png` | A 1200 × 800 PNG renderelése a forrás HTML‑ről, minden bekezdés **félkövér** megjelenítéssel. | +| `archive.zip` | Egy ZIP csomag, amely tartalmazza az eredeti `input.html`‑t, annak CSS‑ét, képeit és minden web‑betűkészletet – tökéletes offline terjesztéshez. | + +Megnyithatod a `page.png`‑t bármely képnézőben, hogy ellenőrizd a félkövér stílus alkalmazását, és kicsomagolhatod a `archive.zip`‑t, hogy lásd a változatlan HTML‑t a hozzá tartozó erőforrásokkal. + +## Gyakori kérdések és buktatók + +- **Mi van, ha a HTML JavaScript‑et tartalmaz?** + Az Aspose.HTML **nem** hajt végre szkripteket a renderelés során, így a dinamikus tartalom nem jelenik meg. Teljesen renderelt oldalakhoz fej nélküli böngészőre lenne szükség, de statikus sablonok esetén ez a megközelítés gyorsabb és könnyebb. + +- **Meg tudom változtatni a kimeneti formátumot JPEG‑re vagy BMP‑re?** + Igen—cseréld le az `ImageRenderingOptions` `ImageFormat` tulajdonságát, pl. `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Kell manuálisan felszabadítani a `HTMLDocument`‑et?** + Az osztály implementálja az `IDisposable`‑t. Hosszú‑távú szolgáltatásban csomagold `using` blokkba, vagy hívd a `document.Dispose()`‑t a használat után. + +- **Hogyan működik az egyedi `MyResourceHandler`?** + Minden külső erőforrást (CSS, képek, betűkészletek) megkap, és a megadott mappába írja. Ez biztosítja, hogy a ZIP hűen tartalmazza a HTML által hivatkozott összes elemet. + +## Összegzés + +Most már van egy kompakt, termelés‑kész megoldásod, amely **convert html to png**, **render html as image**, **save html to zip**, **apply font style html**, és **add bold to p**—mindegyik néhány C# sorban. A kód önálló, .NET 6+ környezetben működik, és beilleszthető bármely háttérrendszerbe, amely gyors vizuális pillanatképeket igényel a webes tartalomról. + +Készen állsz a következő lépésre? Próbáld megváltoztatni a renderelés méretét, kísérletezz más CSS tulajdonságokkal (pl. `font-family` vagy `color`), vagy integráld ezt a konvertert egy ASP.NET Core végpontra, amely igény szerint visszaadja a PNG‑t. A lehetőségek végtelenek, és az Aspose.HTML‑del elkerülheted a nehéz böngésző‑függőségeket. + +Ha problémába ütköztél vagy van ötleted a bővítésre, írj egy megjegyzést alább. Boldog kódolást! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/hungarian/net/html-document-manipulation/_index.md index 4f88cba20..e5733264d 100644 --- a/html/hungarian/net/html-document-manipulation/_index.md +++ b/html/hungarian/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Tanulja meg az Aspose.HTML használatát .NET-hez. Importáljon névteret, egyes Használja ki a webfejlesztésben rejlő lehetőségeket az Aspose.HTML for .NET segítségével. Könnyen hozhat létre, konvertálhat és kezelhet HTML dokumentumokat. ### [HTML létrehozása karakterláncból C#-ban – Egyéni erőforráskezelő útmutató](./create-html-from-string-in-c-custom-resource-handler-guide/) Ismerje meg, hogyan hozhat létre HTML-t karakterláncból C#-ban egy egyéni erőforráskezelő segítségével. +### [HTML dokumentum létrehozása C#‑ban – Lépésről‑lépésre útmutató](./create-html-document-c-step-by-step-guide/) +Ismerje meg, hogyan hozhat létre HTML dokumentumot C#‑ban részletes, lépésről‑lépésre útmutatóval. ## Következtetés diff --git a/html/hungarian/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/hungarian/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..3ab835289 --- /dev/null +++ b/html/hungarian/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: HTML dokumentum létrehozása C#-ban, és megtanulni, hogyan lehet elemet + lekérni azonosító alapján, elemet megtalálni azonosítóval, megváltoztatni a HTML + elem stílusát, valamint félkövér és dőlt formázást hozzáadni az Aspose.Html használatával. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: hu +og_description: HTML dokumentum létrehozása C#-ban, és azonnal megtanulod, hogyan + kell elemet lekérni ID alapján, elemet megtalálni ID alapján, a HTML elem stílusát + módosítani, valamint félkövér és dőlt formázást hozzáadni, világos kódrészletekkel. +og_title: HTML dokumentum létrehozása C#‑ban – Teljes programozási útmutató +tags: +- Aspose.Html +- C# +- DOM manipulation +title: HTML dokumentum létrehozása C#‑ban – Lépésről lépésre útmutató +url: /hu/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML dokumentum létrehozása C#‑ban – Lépés‑ről‑lépésre útmutató + +Valaha szükséged volt már **HTML dokumentum C#‑ban** létrehozására a semmiből, majd egyetlen bekezdés megjelenésének módosítására? Nem vagy egyedül. Sok web‑automatizálási projektben létrehozol egy HTML fájlt, megtalálod a kívánt elemet az ID‑ja alapján, és alkalmazol némi stílust – gyakran félkövér + dőlt – anélkül, hogy bármilyen böngészőt megnyitnál. + +Ebben az útmutatóban pontosan ezt fogjuk végigjárni: létrehozunk egy HTML dokumentumot C#‑ban, **get element by id**, **locate element by id**, **change HTML element style**, és végül **add bold italic** a Aspose.Html könyvtár segítségével. A végére egy teljesen futtatható kódrészletet kapsz, amelyet bármely .NET projektbe beilleszthetsz. + +## Amire szükséged lesz + +- .NET 6 vagy újabb (a kód .NET Framework 4.7+‑on is működik) +- Visual Studio 2022 (vagy bármely kedvenc szerkesztő) +- Az **Aspose.Html** NuGet csomag (`Install-Package Aspose.Html`) + +Ennyi—nincs extra HTML fájl, nincs webszerver, csak néhány sor C#‑ban. + +## HTML dokumentum létrehozása C#‑ban – A dokumentum inicializálása + +Először is: szükséged van egy élő `HTMLDocument` objektumra, amelyet az Aspose.Html motor használhat. Gondolj rá úgy, mint egy új jegyzetre, ahol a jelölőnyelvedet írod. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Miért fontos:** A nyers karakterlánc átadása a `HTMLDocument`‑nek elkerüli a fájl‑I/O‑t, és mindent memóriában tart—tökéletes egységtesztekhez vagy futás‑közbeni generáláshoz. + +## Get Element by ID – A bekezdés megtalálása + +Miután a dokumentum létezik, szükségünk van a **get element by id** műveletre. A DOM API biztosítja a `GetElementById`‑t, amely egy `IElement` referenciát ad vissza, vagy `null`‑t, ha az ID nem létezik. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Pro tipp:** Bár a jelölőnyelvünk apró, a null‑ellenőrzés elkerüli a fejfájást, amikor ugyanazt a logikát nagyobb, dinamikus oldalakon használod újra. + +## Locate Element by ID – Alternatív megközelítés + +Néha már lehet egy hivatkozásod a dokumentum gyökerére, és egy lekérdezés‑stílusú keresést részesítesz előnyben. A CSS szelektorok (`QuerySelector`) használata egy másik módja a **locate element by id** műveletnek: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **Mikor melyiket használjuk?** A `GetElementById` valamivel gyorsabb, mivel közvetlen hash‑keresés. A `QuerySelector` akkor jön jól, ha összetett szelektorokra van szükség (pl. `div > p.highlight`). + +## Change HTML Element Style – Félkövér dőlt hozzáadása + +Miután megvan az elem, a következő lépés a **change HTML element style**. Az Aspose.Html egy `Style` objektumot biztosít, ahol CSS tulajdonságokat állíthatsz be, vagy a kényelmes `WebFontStyle` felsorolást használhatod több betűstílus egyszerre alkalmazásához. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Ez az egyetlen sor beállítja az elem `font-weight` tulajdonságát `bold`‑ra és a `font-style`‑t `italic`‑ra. A háttérben az Aspose.Html a felsorolást a megfelelő CSS karakterláncra fordítja. + +### Teljes működő példa + +Az összes részlet összerakása egy kompakt, önálló programot eredményez, amelyet azonnal lefordíthatsz és futtathatsz: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Várt kimenet** + +``` +Rendered HTML: +

Hello world

+``` + +A `

` tag most már egy beágyazott `style` attribútummal rendelkezik, amely a szöveget egyszerre félkövér és dőlt teszi – pontosan, ahogy szerettük. + +## Szélsőséges esetek és gyakori buktatók + +| Helyzet | Mire figyeljünk | Hogyan kezeljük | +|-----------|-------------------|---------------| +| **Az ID nem létezik** | `GetElementById` `null`‑t ad vissza. | Dobj kivételt vagy térj vissza egy alapértelmezett elemhez. | +| **Több elem osztja ugyanazt az ID‑t** | A HTML specifikáció szerint az ID‑knek egyedinek kell lenniük, de a valós oldalak néha megszegik ezt a szabályt. | `GetElementById` az első egyezést adja vissza; fontold meg a `QuerySelectorAll` használatát, ha a duplikátumokat kell kezelni. | +| **Stílusütközések** | A meglévő beágyazott stílusok felülíródhatnak. | Fűzd hozzá a `Style` objektumhoz a teljes `style` karakterlánc helyett: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Megjelenítés böngészőben** | Néhány böngésző figyelmen kívül hagyja a `WebFontStyle`‑t, ha az elem már rendelkezik magasabb specifikusságú CSS osztállyal. | Használj `!important`-ot a `paragraph.Style.SetProperty("font-weight", "bold", "important");` segítségével, ha szükséges. | + +## Pro tippek valós projektekhez + +- **Cache-eld a dokumentumot**, ha sok elemet dolgozol fel; minden apró kódrészlethez új `HTMLDocument` létrehozása rontja a teljesítményt. +- **Kombináld a stílusváltoztatásokat** egyetlen `Style` tranzakcióban, hogy elkerüld a többszörös DOM újrarajzolást. +- **Használd ki az Aspose.Html renderelő motorját** a végső dokumentum PDF‑ként vagy képként történő exportálásához – nagyszerű jelentéskészítő eszközöknek. + +## Vizuális ellenőrzés (opcionális) + +Ha inkább a böngészőben szeretnéd látni az eredményt, elmentheted a renderelt karakterláncot egy `.html` fájlba: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Nyisd meg a `output.html`‑t, és látni fogod, hogy a **Hello world** félkövér + dőlt formában jelenik meg. + +![HTML dokumentum C# példa, amely félkövér dőlt bekezdést mutat](/images/create-html-document-csharp.png "HTML dokumentum C# – renderelt kimenet") + +*Alt szöveg: HTML dokumentum C# – renderelt kimenet félkövér dőlt szöveggel.* + +## Összegzés + +Most **HTML dokumentumot C#‑ban** hoztunk létre, **got element by id**, **located element by id**, **changed HTML element style**, és végül **added bold italic**—mindegyik csak néhány sorban az Aspose.Html használatával. A megközelítés egyszerű, bármely .NET környezetben működik, és skálázható nagyobb DOM manipulációkhoz. + +Készen állsz a következő lépésre? Próbáld ki a `WebFontStyle` helyett más felsorolásokat, például `Underline`, vagy kombináld manuálisan több stílust. Vagy kísérletezz egy külső HTML fájl betöltésével és ugyanazzal a technikával több száz elemre. A lehetőségek végtelenek, és most már szilárd alapod van a további fejlesztéshez. + +Boldog kódolást! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/hungarian/net/html-extensions-and-conversions/_index.md b/html/hungarian/net/html-extensions-and-conversions/_index.md index 53dd8b575..63fd961da 100644 --- a/html/hungarian/net/html-extensions-and-conversions/_index.md +++ b/html/hungarian/net/html-extensions-and-conversions/_index.md @@ -48,15 +48,26 @@ Az Aspose.HTML for .NET nem csak egy könyvtár; ez egy változás a webfejleszt ### [Konvertálja a HTML-t Markdown-ra .NET-ben az Aspose.HTML-lel](./convert-html-to-markdown/) ### [Konvertálja a HTML-t MHTML-re .NET-ben az Aspose.HTML-lel](./convert-html-to-mhtml/) ### [Konvertálja a HTML-t PNG-re .NET-ben az Aspose.HTML-lel](./convert-html-to-png/) +### [HTML konvertálása képre C#‑ban – Teljes útmutató](./convert-html-to-image-in-c-complete-guide/) +Ismerje meg, hogyan konvertálhatja a HTML-t különböző képformátumokba C#‑ban az Aspose.HTML for .NET segítségével. ### [Konvertálja a HTML-t TIFF-re .NET-ben az Aspose.HTML-lel](./convert-html-to-tiff/) ### [Konvertálja a HTML-t XPS-re .NET-ben az Aspose.HTML-lel](./convert-html-to-xps/) Fedezze fel az Aspose.HTML erejét .NET-hez: A HTML-t könnyedén konvertálja XPS-re. Előfeltételek, lépésenkénti útmutató és GYIK mellékelve. ### [HTML zip-elése C#-ban – HTML mentése zip-be](./how-to-zip-html-in-c-save-html-to-zip/) Ismerje meg, hogyan csomagolhatja be a HTML-fájlokat zip-archívumba C#-ban az Aspose.HTML for .NET segítségével. +### [HTML zip-elése Aspose.HTML‑el – Teljes útmutató](./how-to-zip-html-with-aspose-html-complete-guide/) +Részletes útmutató az HTML fájlok zip‑archívumba csomagolásához Aspose.HTML for .NET használatá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/) +Mentje a HTML-t közvetlenül memóriában ZIP-archívumba az Aspose.HTML for .NET C#‑ban. +### [HTML mentése ZIP-be C#‑ban – Teljes útmutató egyedi tárolóval](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Ismerje meg, hogyan mentheti a HTML-t ZIP-archívumba C#‑ban egyedi tárolási megoldással, lépésről‑lépésre útmutatóval. ### [HTML-dokumentum létrehozása formázott szöveggel és exportálása PDF-be – Teljes útmutató](./create-html-document-with-styled-text-and-export-to-pdf-full/) Hozzon létre HTML-dokumentumot formázott szöveggel, majd exportálja PDF-be az Aspose.HTML for .NET segítségével. Lépésről lépésre útmutató. ### [PDF létrehozása HTML-ből – C# lépésről‑lépésre útmutató](./create-pdf-from-html-c-step-by-step-guide/) Ismerje meg, hogyan hozhat létre PDF-et HTML-ből C#‑ban az Aspose.HTML for .NET segítségével, részletes lépésről‑lépésre útmutatóval. +### [PDF létrehozása HTML-ből Aspose‑szal – Lépésről‑lépésre C# útmutató](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Ismerje meg, hogyan hozhat létre PDF-et HTML-ből C#‑ban az Aspose.HTML for .NET segítségével, részletes lépésről‑lépésre útmutatóval. ### [HTML mentése ZIP-ként – Teljes C# oktatóanyag](./save-html-as-zip-complete-c-tutorial/) ### [HTML mentése ZIP-be C#‑ban – Teljes memória‑beli példa](./save-html-to-zip-in-c-complete-in-memory-example/) Mentse a HTML-t közvetlenül memóriában ZIP-archívumba az Aspose.HTML for .NET C#‑ban. diff --git a/html/hungarian/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/hungarian/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..fa6240df6 --- /dev/null +++ b/html/hungarian/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: HTML konvertálása képpé az Aspose.HTML használatával C#-ban. Tanulja + meg, hogyan menthet HTML-t PNG formátumban, állíthatja be a kép méretét a renderelés + során, és írhatja a képet fájlba néhány lépésben. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: hu +og_description: HTML gyors átalakítása képpé. Ez az útmutató bemutatja, hogyan mentheted + el az HTML-t PNG formátumban, hogyan állíthatod be a képméret renderelését, és hogyan + írhatod a képet fájlba az Aspose.HTML segítségével. +og_title: HTML konvertálása képpé C#‑ban – Lépésről‑lépésre útmutató +tags: +- Aspose.HTML +- C# +- Image Rendering +title: HTML konvertálása képpé C#-ban – Teljes útmutató +url: /hu/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML konvertálása képpé C#-ban – Teljes útmutató + +Valaha is szükséged volt **convert HTML to image** műveletre egy irányítópult előnézetéhez, egy e‑mail előnézethez vagy egy PDF‑jelentéshez? Ez a szituáció gyakrabban merül fel, mint gondolnád, különösen, ha dinamikus webtartalommal dolgozol, amelyet máshová kell beágyazni. + +A jó hír? Az Aspose.HTML segítségével **convert HTML to image** néhány sor kóddal megoldható, és megtanulod, hogyan *save HTML as PNG*, hogyan szabályozhatod a kimeneti méreteket, valamint hogyan *write image to file* anélkül, hogy izzadnál. + +Ebben a tutorialban mindent végigvázolunk, amit tudnod kell: a távoli oldal betöltésétől a renderelési méret finomhangolásáig, egészen a PNG fájl lemezre mentéséig. Nincs szükség külső eszközökre, nincs bonyolult parancssori trükk – csak tiszta C# kód, amit bármely .NET projektbe beilleszthetsz. + +## Mit fogsz megtanulni + +- Hogyan **render webpage to PNG** az Aspose.HTML `HTMLDocument` osztályával. +- A pontos lépések a **set image size rendering** beállításához, hogy a kimenet megfeleljen a layout követelményeidnek. +- Módszerek a **write image to file** biztonságos végrehajtására, stream‑ek és fájlutak kezelése. +- Tippek a gyakori hibák, például hiányzó betűtípusok vagy hálózati időtúllépések hibaelhárításához. + +### Előfeltételek + +- .NET 6.0 vagy újabb (az API működik .NET Framework‑kel is, de a .NET 6+ ajánlott). +- Hivatkozás az Aspose.HTML for .NET NuGet csomagra (`Aspose.Html`). +- Alapvető ismeretek a C#‑ról és az async/await‑ról (opcionális, de hasznos). + +Ha már megvannak ezek, készen állsz arra, hogy azonnal elkezdj **convert HTML to image** műveletet végezni. + +## 1. lépés: Weboldal betöltése – A HTML képpé konvertálás alapja + +Mielőtt bármilyen renderelés megtörténne, szükséged van egy `HTMLDocument` példányra, amely a rögzíteni kívánt oldalt képviseli. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Miért fontos:* A `HTMLDocument` elemzi a HTML‑t, feloldja a CSS‑t, és felépíti a DOM‑ot. Ha a dokumentum nem tud betöltődni (pl. hálózati hiba), a későbbi renderelés üres képet eredményez. Mindig ellenőrizd, hogy az URL elérhető‑e, mielőtt továbbmennél. + +## 2. lépés: Kép méretének beállítása – Szélesség, magasság és minőség szabályozása + +Az Aspose.HTML lehetővé teszi a kimeneti méretek finomhangolását az `ImageRenderingOptions` segítségével. Itt állítod be a **set image size rendering**‑t, hogy megfeleljen a cél layoutnak. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Pro tipp:* Ha kihagyod a `Width` és `Height` beállításokat, az Aspose.HTML a lap belső méretét használja, ami a reszponzív tervezésnél kiszámíthatatlan lehet. Az explicit méretek megadása biztosítja, hogy a **save HTML as PNG** kimenet pontosan úgy nézzen ki, ahogy elvárod. + +## 3. lépés: Kép írása fájlba – A renderelt PNG mentése + +Most, hogy a dokumentum készen áll és a renderelési beállítások megvannak, végre **write image to file**. A `FileStream` használata garantálja, hogy a fájl biztonságosan létrejön, még akkor is, ha a mappa még nem létezik. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +Ez a blokk lefutása után megtalálod a `page.png`‑t a megadott helyen. Épp **rendered webpage to PNG** és leírtad a lemezre egy egyszerű, egyértelmű műveletben. + +### Várható eredmény + +Nyisd meg a `C:\Temp\page.png` fájlt bármely képnéző programmal. Egy hűséges pillanatképet kell látnod a `https://example.com` oldalról, 1024 × 768 pixel méretben, antialiasingnak köszönhetően sima élekkel. Ha az oldal dinamikus tartalmat (pl. JavaScript‑tel generált elemeket) tartalmaz, azok is rögzítésre kerülnek, amennyiben a DOM teljesen betöltődött a renderelés előtt. + +## 4. lépés: Szélsőséges esetek kezelése – Betűtípusok, hitelesítés és nagy oldalak + +Miközben az alapfolyamat a legtöbb nyilvános oldalnál működik, a valós világ gyakran dob kihívásokat: + +| Szituáció | Mit kell tenni | +|-----------|----------------| +| **Custom fonts not loading** | Ágyazd be a betűtípus fájlokat helyileg, és állítsd be a `htmlDoc.Fonts.Add("path/to/font.ttf")`‑t. | +| **Pages behind authentication** | Használd a `HTMLDocument` túlterhelést, amely `HttpWebRequest`‑et fogad cookie‑kkal vagy tokenekkel. | +| **Very tall pages** | Növeld a `Height` értékét vagy engedélyezd a `PageScaling`‑et az `ImageRenderingOptions`‑ban, hogy elkerüld a levágást. | +| **Memory usage spikes** | Renderelj darabokban a `RenderToImage` olyan túlterhelésével, amely `Rectangle` régiót fogad. | + +Ezeknek a *write image to file* finomságainak a kezelése biztosítja, hogy a `convert html to image` folyamatod robusztus maradjon a produkcióban. + +## 5. lépés: Teljes működő példa – Másolás-beillesztés kész + +Az alábbiakban a teljes program látható, amely készen áll a fordításra. Tartalmazza az összes lépést, a hibakezelést és a szükséges kommentárokat. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Futtasd a programot, és a konzolon megjelenik a megerősítő üzenet. A PNG fájl pontosan olyan lesz, mint amikor manuálisan **rendered webpage to PNG** a böngészőben, és képernyőképet készítesz – csak gyorsabb és teljesen automatizált. + +## Gyakran Ismételt Kérdések + +**Q: Átalakíthatok-e egy helyi HTML fájlt URL helyett?** +Természetesen. Csak cseréld le az URL‑t egy fájlútra: `new HTMLDocument(@"C:\myPage.html")`. + +**Q: Szükségem van licencre az Aspose.HTML‑hez?** +Egy ingyenes értékelő licenc működik fejlesztés és tesztelés során. Produkcióban vásárolj licencet, hogy eltávolítsd az értékelő vízjelet. + +**Q: Mi van, ha az oldal JavaScript‑tel tölt be tartalmat az első betöltés után?** +Az Aspose.HTML szinkron módon hajtja végre a JavaScript‑et a parsing során, de a hosszú futású szkriptekhez manuális késleltetésre lehet szükség. Használhatod a `HTMLDocument.WaitForReadyState`‑t a renderelés előtt. + +## Összegzés + +Most már egy szilárd, vég‑től‑végig megoldással rendelkezel a **convert HTML to image** feladatra C#‑ban. A fenti lépéseket követve **save HTML as PNG**, pontosan **set image size rendering**, és magabiztosan **write image to file** tudsz végrehajtani bármely Windows vagy Linux környezetben. + +Az egyszerű képernyőképektől az automatizált jelentéskészítésig ez a technika könnyen skálázható. Következő lépésként kísérletezz más kimeneti formátumokkal, például JPEG‑el vagy BMP‑vel, vagy integráld a kódot egy ASP.NET Core API‑ba, amely közvetlenül visszaadja a PNG‑t a hívóknak. A lehetőségek gyakorlatilag végtelenek. + +Boldog kódolást, és legyenek a renderelt képeid mindig pixel‑tökéletesek! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/hungarian/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..79f76e440 --- /dev/null +++ b/html/hungarian/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-03-21 +description: Készíts PDF-et HTML-ből gyorsan az Aspose HTML segítségével. Tanulja + meg, hogyan rendereljen HTML-t PDF-be, konvertálja a HTML-t PDF-re, és hogyan használja + az Aspose-t egy tömör útmutatóban. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: hu +og_description: PDF létrehozása HTML‑ből Aspose‑szal C#‑ban. Ez az útmutató bemutatja, + hogyan lehet HTML‑t PDF‑re renderelni, HTML‑t PDF‑re konvertálni, és hogyan lehet + hatékonyan használni az Aspose‑t. +og_title: PDF létrehozása HTML‑ből – Teljes Aspose C# útmutató +tags: +- Aspose +- C# +- PDF generation +title: PDF létrehozása HTML‑ből Aspose‑szal – Lépésről lépésre C# útmutató +url: /hu/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF létrehozása HTML‑ből Aspose‑szal – Lépés‑ről‑lépésre C# útmutató + +Valaha is szükséged volt **PDF létrehozására HTML‑ből**, de nem tudtad, melyik könyvtár adja a pixel‑pontos eredményt? Nem vagy egyedül. Sok fejlesztő elakad, amikor egy webes részletet nyomtatható dokumentummá akar alakítani, és csak elmosódott szöveget vagy összetört elrendezést kap. + +A jó hír, hogy az Aspose HTML a teljes folyamatot fájdalommentessé teszi. Ebben az útmutatóban végigvezetünk a **HTML PDF‑re rendereléséhez** szükséges kódon, megmagyarázzuk, miért fontos minden beállítás, és megmutatjuk, hogyan **konvertálhatod a HTML‑t PDF‑be** rejtett trükkök nélkül. A végére tudni fogod, **hogyan használjuk az Aspose‑t** megbízható PDF‑generáláshoz bármely .NET projektben. + +## Előfeltételek – Amire szükséged lesz a kezdéshez + +- **.NET 6.0 vagy újabb** (a példa .NET Framework 4.7+‑on is működik) +- **Visual Studio 2022** vagy bármely C#‑t támogató IDE +- **Aspose.HTML for .NET** NuGet csomag (ingyenes próba vagy licencelt verzió) +- Alapvető C# szintaxis ismeret (mély PDF‑tudás nem szükséges) + +Ha ezek megvannak, már indulhatsz. Ellenkező esetben töltsd le a legújabb .NET SDK‑t, és telepítsd a NuGet csomagot a következővel: + +```bash +dotnet add package Aspose.HTML +``` + +Ez az egyetlen sor mindent beszerez, ami a **aspose html to pdf** konverzióhoz szükséges. + +--- + +## 1. lépés: Projekt beállítása PDF létrehozásához HTML‑ből + +Az első teendő egy új konzolalkalmazás létrehozása (vagy a kód integrálása egy meglévő szolgáltatásba). Íme egy minimális `Program.cs` vázlat: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tipp:** Ha a régebbi példákban `Aspise.Html.Rendering.Text`‑et látsz, cseréld le `Aspose.Html.Rendering.Text`‑re. A helyesírási hiba fordítási hibát okoz. + +A helyes névterek biztosítják, hogy a fordító megtalálja a később szükséges **TextOptions** osztályt. + +## 2. lépés: HTML dokumentum felépítése (Render HTML to PDF) + +Most létrehozzuk a forrás HTML‑t. Az Aspose elfogad nyers karakterláncot, fájlútvonalat vagy akár URL‑t is. A bemutatóhoz egyszerűen maradjunk a karakterláncnál: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Miért karakterláncot? Elkerüli a fájlrendszer‑I/O‑t, felgyorsítja a konverziót, és garantálja, hogy a kódban látható HTML pontosan az, ami renderelődik. Ha fájlból szeretnéd betölteni, csak cseréld le a konstruktor argumentumát egy fájl‑URI‑ra. + +## 3. lépés: Szöveg renderelés finomhangolása (Convert HTML to PDF with Better Quality) + +A szöveg renderelése gyakran meghatározza, hogy a PDF éles vagy homályos lesz‑e. Az Aspose egy `TextOptions` osztályt kínál, amellyel engedélyezheted az alpixel‑hintinget – elengedhetetlen a magas DPI‑kimenethez. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +A `UseHinting` engedélyezése különösen hasznos, ha a forrás HTML egyedi betűtípusokat vagy kis betűméreteket tartalmaz. Enélkül a végső PDF‑ben szaggatott éleket láthatsz. + +## 4. lépés: Szövegbeállítások csatolása a PDF renderelési konfigurációhoz (How to Use Aspose) + +Ezután a szövegbeállításokat a PDF renderelőhöz kötjük. Itt mutatkozik meg igazán a **aspose html to pdf** ereje – a lapmérettől a tömörítésig mindent testre szabhatunk. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Elhagyhatod a `PageSetup`‑ot, ha az alapértelmezett A4 mérettel vagy elégedett. A lényeg, hogy a `TextOptions` objektum a `PdfRenderingOptions`‑on belül él, és így mondod meg az Aspose‑nak, *hogyan* renderelje a szöveget. + +## 5. lépés: HTML renderelése és PDF mentése (Convert HTML to PDF) + +Végül a kimenetet egy fájlba streameljük. Egy `using` blokk garantálja, hogy a fájlkezelő megfelelően lezárul, még kivétel esetén is. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +A program futtatása után a `output.pdf` a végrehajtható mellé kerül. Nyisd meg, és egy tiszta címsort és bekezdést kell látnod – pontosan úgy, ahogy a HTML karakterlánc definiálja. + +### Várható kimenet + +![PDF‑kimenet példája HTML‑ből létrehozva](https://example.com/images/pdf-output.png "PDF‑kimenet példája HTML‑ből létrehozva") + +*A képernyőkép a generált PDF‑et mutatja a „Hello, Aspose!” címmel, amely a szöveg‑hintingnek köszönhetően élesen jelenik meg.* + +--- + +## Gyakori kérdések és speciális esetek + +### 1. Mi van, ha a HTML külső erőforrásokra (képek, CSS) hivatkozik? + +Az Aspose a relatív URL‑ket a dokumentum alap‑URI‑ja alapján oldja fel. Ha nyers karakterláncot adsz meg, állítsd be manuálisan az alap‑URI‑t: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Ezután bármely `` a `C:/MyProject/` relatív útvonalhoz lesz keresve. + +### 2. Hogyan ágyazhatok be betűtípusokat, amelyek nincsenek telepítve a szerveren? + +Adj hozzá egy ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### 4. lépés: Állítsd be a mentési opciókat, hogy az egyedi tárolót használd + +A `HtmlSaveOptions` lehetővé teszi, hogy az Aspose mindent egy ZIP fájlba csomagoljon. A (legacy) `OutputStorage` tulajdonság kapja meg a `MyStorage` példányunkat. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Megjegyzés:** Az Aspose HTML 23.9+ verzióban a tulajdonság neve `OutputStorage`, de elavultként van jelölve. A modern alternatíva a `ZipOutputStorage`. Az alábbi kód mindkettővel működik, mivel az interfész ugyanaz. + +### 5. lépés: Mentsd a dokumentumot ZIP archívumként + +Válassz egy célmappát (vagy streamet), és hagyd, hogy az Aspose elvégezze a nehéz munkát. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +A program befejezésekor megtalálod az `output.zip` fájlt, amely a következőket tartalmazza: + +* `index.html` — a fő dokumentum. +* Az összes beágyazott kép, CSS fájl vagy script (ha a HTML hivatkozik rájuk). + +A ZIP‑et bármely archívumkezelővel megnyithatod, hogy ellenőrizd a struktúrát. + +--- + +## Az eredmény ellenőrzése (opcionális) + +Ha programból szeretnéd átnézni az archívumot anélkül, hogy kicsomagolnád a lemezre: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Tipikus kimenet: + +``` +- index.html (452 bytes) +``` + +Ha képeket vagy CSS‑t tartalmaz a HTML, azok további bejegyzésekként jelennek meg. Ez a gyors ellenőrzés megerősíti, hogy a **create html zip archive** a várt módon működött. + +--- + +## Gyakori kérdések és speciális esetek + +| Kérdés | Válasz | +|----------|--------| +| **Mi a teendő, ha a ZIP‑et közvetlenül egy válasz stream‑be kell írni?** | A `document.Save` után kapott `MemoryStream`‑et adhatod vissza. Cast-olhatod `byte[]`‑re, és írhatod a `HttpResponse.Body`‑ba. | +| **A HTML‑om külső URL‑kre hivatkozik – letöltődik majd?** | Nem. Az Aspose csak a *beágyazott* erőforrásokat csomagolja (pl. `` vagy helyi fájlok). A távoli asset‑eket előbb le kell tölteni, és a markup‑ot módosítani. | +| **Az `OutputStorage` tulajdonság elavult – figyelmen kívül hagyjam?** | Működik, de az újabb `ZipOutputStorage` ugyanazt az API‑t kínálja más névvel. Cseréld le `OutputStorage`‑t `ZipOutputStorage`‑ra, ha szeretnél figyelmeztetés‑mentes buildet. | +| **Titkosítható a ZIP?** | Igen. Mentés után nyisd meg a fájlt a `System.IO.Compression.ZipArchive`‑val, és használj harmadik‑fél könyvtárakat, például `SharpZipLib`, a jelszó beállításához. Az Aspose önmagában nem biztosít titkosítást. | + +--- + +## Teljes működő példa (másold be) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Futtasd a programot, nyisd meg az `output.zip`‑et, és egyetlen `index.html` fájlt látsz, amely a „Hello from ZIP!” címsort jeleníti meg böngészőben. + +--- + +## Összegzés + +Most már tudod, **hogyan ments HTML‑t ZIP‑ként** C#‑ban egy **egyedi tároló** osztály segítségével, hogyan **exportálj HTML‑t ZIP‑be**, és hogyan **hozz létre egy HTML zip archívumot**, amely készen áll a terjesztésre. A minta rugalmas — cseréld le a `MemoryStream`‑et egy felhő stream‑re, adj hozzá titkosítást, vagy integráld egy web API‑ba, amely kérésre visszaadja a ZIP‑et. + +Készen állsz a következő lépésre? Próbálj meg egy teljes weboldalt betölteni képekkel és stílusokkal, vagy csatlakoztasd a tárolót az Azure Blob Storage‑hoz, hogy teljesen elkerüld a helyi fájlrendszert. A lehetőségek határtalanok, ha az Aspose.HTML ZIP képességeit saját tárolási logikáddal kombinálod. + +Jó kódolást, és legyenek mindig rendezettek az archívumaid! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/indonesian/net/generate-jpg-and-png-images/_index.md b/html/indonesian/net/generate-jpg-and-png-images/_index.md index 4e885ce32..5ad79d04e 100644 --- a/html/indonesian/net/generate-jpg-and-png-images/_index.md +++ b/html/indonesian/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Pelajari cara menggunakan Aspose.HTML untuk .NET guna memanipulasi dokumen HTML, Pelajari cara mengaktifkan antialiasing untuk meningkatkan kualitas gambar PNG atau JPG saat mengonversi dokumen DOCX menggunakan Aspose.HTML. ### [Konversi DOCX ke PNG – Membuat Arsip ZIP dengan C# Tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Pelajari cara mengonversi file DOCX menjadi PNG dan mengemasnya ke dalam arsip ZIP menggunakan C# dengan Aspose.HTML. +### [Konversi HTML ke PNG – Panduan Lengkap C# dengan Ekspor ZIP](./convert-html-to-png-full-c-guide-with-zip-export/) +Pelajari cara mengonversi HTML menjadi PNG secara lengkap menggunakan C# dan mengekspor hasilnya ke arsip ZIP dengan Aspose.HTML. ## Kesimpulan diff --git a/html/indonesian/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/indonesian/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..dfe762f8b --- /dev/null +++ b/html/indonesian/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Konversi HTML ke PNG dan render HTML sebagai gambar sambil menyimpan + HTML ke ZIP. Pelajari cara menerapkan gaya font pada HTML dan menambahkan tebal + pada elemen p dalam beberapa langkah saja. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: id +og_description: Konversi HTML ke PNG dengan cepat. Panduan ini menunjukkan cara merender + HTML menjadi gambar, menyimpan HTML ke ZIP, menerapkan gaya font pada HTML, dan + menambahkan teks tebal pada elemen p. +og_title: Konversi HTML ke PNG – Tutorial C# Lengkap +tags: +- Aspose +- C# +title: Mengonversi HTML ke PNG – Panduan Lengkap C# dengan Ekspor ZIP +url: /id/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konversi HTML ke PNG – Panduan Lengkap C# dengan Ekspor ZIP + +Pernahkah Anda perlu **mengonversi HTML ke PNG** tetapi tidak yakin pustaka mana yang dapat melakukannya tanpa harus menarik browser headless? Anda tidak sendirian. Dalam banyak proyek—thumbnail email, pratinjau dokumentasi, atau gambar quick‑look—mengubah halaman web menjadi gambar statis adalah kebutuhan dunia nyata. + +Kabar baiknya? Dengan Aspose.HTML Anda dapat **merender HTML sebagai gambar**, menyesuaikan markup secara dinamis, dan bahkan **menyimpan HTML ke ZIP** untuk distribusi selanjutnya. Dalam tutorial ini kami akan membahas contoh lengkap yang dapat dijalankan yang **menerapkan font style HTML**, khususnya **menambahkan tebal pada elemen p**, sebelum menghasilkan file PNG. Pada akhir tutorial Anda akan memiliki satu kelas C# yang melakukan semuanya mulai dari memuat halaman hingga mengarsipkan sumber dayanya. + +## Apa yang Anda Butuhkan + +- .NET 6.0 atau lebih baru (API juga berfungsi di .NET Core) +- Aspose.HTML untuk .NET 6+ (paket NuGet `Aspose.Html`) +- Pemahaman dasar tentang sintaks C# (tidak memerlukan konsep lanjutan) + +Itu saja. Tanpa browser eksternal, tanpa phantomjs, hanya kode terkelola murni. + +## Langkah 1 – Muat Dokumen HTML + +Pertama kami membawa file sumber (atau URL) ke dalam objek `HTMLDocument`. Langkah ini menjadi dasar untuk **render html as image** dan **save html to zip** nanti. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Mengapa ini penting:* Kelas `HTMLDocument` mem-parsing markup, membangun DOM, dan menyelesaikan sumber daya yang terhubung (CSS, gambar, font). Tanpa objek dokumen yang tepat Anda tidak dapat memanipulasi gaya atau merender apa pun. + +## Langkah 2 – Terapkan Font Style HTML (Tambah Tebal pada p) + +Sekarang kami akan **menerapkan font style HTML** dengan mengiterasi setiap elemen `

` dan mengatur `font-weight`‑nya menjadi bold. Ini adalah cara programatik untuk **add bold to p** tag tanpa menyentuh file asli. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Tips pro:* Jika Anda hanya perlu menebalkan sebagian, ubah selector menjadi lebih spesifik, misalnya `"p.intro"`. + +## Langkah 3 – Render HTML sebagai Gambar (Konversi HTML ke PNG) + +Setelah DOM siap, kami mengonfigurasi `ImageRenderingOptions` dan memanggil `RenderToImage`. Di sinilah keajaiban **convert html to png** terjadi. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Mengapa opsi ini penting:* Menetapkan lebar/tinggi tetap mencegah output menjadi terlalu besar, sementara antialiasing memberikan hasil visual yang lebih halus. Anda juga dapat mengubah `options` menjadi `ImageFormat.Jpeg` jika menginginkan ukuran file yang lebih kecil. + +## Langkah 4 – Simpan HTML ke ZIP (Bundel Sumber Daya) + +Seringkali Anda perlu mengirimkan HTML asli beserta CSS, gambar, dan fontnya. `ZipArchiveSaveOptions` milik Aspose.HTML melakukan hal itu dengan tepat. Kami juga menambahkan `ResourceHandler` khusus sehingga semua aset eksternal ditulis ke folder yang sama dengan arsip. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Kasus tepi:* Jika HTML Anda merujuk ke gambar remote yang memerlukan otentikasi, handler default akan gagal. Dalam skenario tersebut Anda dapat memperluas `MyResourceHandler` untuk menyuntikkan header HTTP. + +## Langkah 5 – Sambungkan Semua dalam Satu Kelas Konverter + +Berikut adalah kelas lengkap yang siap‑jalan yang menggabungkan semua langkah sebelumnya. Anda dapat menyalin‑tempelnya ke aplikasi console, memanggil `Convert`, dan melihat file‑file muncul. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Output yang Diharapkan + +Setelah menjalankan potongan kode di atas Anda akan menemukan dua file di `outputDirectory`: + +| Berkas | Deskripsi | +|------|-------------| +| `page.png` | Rendering PNG 1200 × 800 dari HTML sumber, dengan setiap paragraf ditampilkan dalam **bold**. | +| `archive.zip` | Bundel ZIP yang berisi `input.html` asli, CSS‑nya, gambar‑gambarnya, dan semua web‑font – sempurna untuk distribusi offline. | + +Anda dapat membuka `page.png` di penampil gambar apa pun untuk memverifikasi bahwa gaya tebal telah diterapkan, dan mengekstrak `archive.zip` untuk melihat HTML yang tidak diubah beserta aset‑asetsnya. + +## Pertanyaan Umum & Hal-hal yang Perlu Diwaspadai + +- **Bagaimana jika HTML mengandung JavaScript?** + Aspose.HTML **tidak** mengeksekusi skrip selama proses rendering, sehingga konten dinamis tidak akan muncul. Untuk halaman yang sepenuhnya dirender Anda memerlukan browser headless, tetapi untuk templat statis pendekatan ini lebih cepat dan ringan. + +- **Bisakah saya mengubah format output menjadi JPEG atau BMP?** + Ya—ganti properti `ImageFormat` pada `ImageRenderingOptions`, misalnya `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Apakah saya perlu membuang (dispose) `HTMLDocument` secara manual?** + Kelas ini mengimplementasikan `IDisposable`. Pada layanan yang berjalan lama, bungkuslah dalam blok `using` atau panggil `document.Dispose()` setelah selesai. + +- **Bagaimana cara kerja `MyResourceHandler` khusus?** + Handler ini menerima setiap sumber daya eksternal (CSS, gambar, font) dan menuliskannya ke folder yang Anda tentukan. Hal ini memastikan ZIP berisi salinan yang setia dari semua yang direferensikan HTML. + +## Kesimpulan + +Sekarang Anda memiliki solusi ringkas dan siap produksi yang **convert html to png**, **render html as image**, **save html to zip**, **apply font style html**, dan **add bold to p**—semua dalam beberapa baris C#. Kode ini berdiri sendiri, bekerja dengan .NET 6+, dan dapat disisipkan ke layanan backend mana pun yang memerlukan snapshot visual cepat dari konten web. + +Siap untuk langkah selanjutnya? Coba ubah ukuran rendering, bereksperimen dengan properti CSS lain (seperti `font-family` atau `color`), atau integrasikan konverter ini ke endpoint ASP.NET Core yang mengembalikan PNG secara on‑demand. Kemungkinannya tak terbatas, dan dengan Aspose.HTML Anda terhindar dari ketergantungan pada browser berat. + +Jika Anda mengalami kendala atau memiliki ide untuk ekstensi, tinggalkan komentar di bawah. Selamat coding! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/indonesian/net/html-document-manipulation/_index.md index 6308bff33..586a613bf 100644 --- a/html/indonesian/net/html-document-manipulation/_index.md +++ b/html/indonesian/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Pelajari cara menggunakan Aspose.HTML untuk .NET. Impor namespace, gabungkan HTM Manfaatkan potensi pengembangan web dengan Aspose.HTML untuk .NET. Buat, ubah, dan manipulasi dokumen HTML dengan mudah. ### [Buat HTML dari String di C# – Panduan Penangan Sumber Daya Kustom](./create-html-from-string-in-c-custom-resource-handler-guide/) Pelajari cara membuat dokumen HTML dari string menggunakan handler sumber daya kustom di C# dengan Aspose.HTML. +### [Buat Dokumen HTML C# – Panduan Langkah demi Langkah](./create-html-document-c-step-by-step-guide/) +Pelajari cara membuat dokumen HTML menggunakan C# dengan panduan langkah demi langkah lengkap. ## Kesimpulan diff --git a/html/indonesian/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/indonesian/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..017dcc8eb --- /dev/null +++ b/html/indonesian/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: Buat dokumen HTML C# dan pelajari cara mendapatkan elemen berdasarkan + ID, menemukan elemen berdasarkan ID, mengubah gaya elemen HTML, serta menambahkan + teks tebal miring menggunakan Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: id +og_description: Buat dokumen HTML dengan C# dan segera pelajari cara mengambil elemen + berdasarkan id, menemukan elemen berdasarkan id, mengubah gaya elemen HTML, serta + menambahkan teks tebal miring dengan contoh kode yang jelas. +og_title: Buat Dokumen HTML C# – Panduan Pemrograman Lengkap +tags: +- Aspose.Html +- C# +- DOM manipulation +title: Membuat Dokumen HTML C# – Panduan Langkah demi Langkah +url: /id/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Membuat Dokumen HTML C# – Panduan Langkah‑ demi‑Langkah + +Pernahkah Anda perlu **membuat dokumen HTML C#** dari awal dan kemudian mengubah tampilan satu paragraf? Anda bukan satu‑satunya. Dalam banyak proyek otomasi web, Anda akan membuat file HTML, mencari tag berdasarkan ID‑nya, dan kemudian menerapkan beberapa gaya—sering kali tebal + miring—tanpa pernah menyentuh browser. + +Dalam tutorial ini kami akan membahas tepat itu: kami akan membuat dokumen HTML di C#, **get element by id**, **locate element by id**, **change HTML element style**, dan akhirnya **add bold italic** menggunakan pustaka Aspose.Html. Pada akhir tutorial Anda akan memiliki potongan kode yang dapat dijalankan sepenuhnya dan dapat ditempatkan ke proyek .NET mana pun. + +## Apa yang Anda Butuhkan + +- .NET 6 atau lebih baru (kode ini juga bekerja pada .NET Framework 4.7+) +- Visual Studio 2022 (atau editor apa pun yang Anda suka) +- Paket NuGet **Aspose.Html** (`Install-Package Aspose.Html`) + +Itu saja—tidak ada file HTML tambahan, tidak ada server web, hanya beberapa baris C#. + +## Membuat Dokumen HTML C# – Menginisialisasi Dokumen + +Hal pertama yang harus dilakukan: Anda memerlukan objek `HTMLDocument` yang aktif sehingga mesin Aspose.Html dapat bekerja dengannya. Anggap ini seperti membuka buku catatan baru tempat Anda akan menulis markup. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Mengapa ini penting:** Dengan memberikan string mentah ke `HTMLDocument`, Anda menghindari penanganan I/O file dan menjaga semuanya di memori—sempurna untuk unit test atau pembuatan on‑the‑fly. + +## Dapatkan Elemen berdasarkan ID – Menemukan Paragraf + +Sekarang dokumen sudah ada, kita perlu **get element by id**. API DOM menyediakan `GetElementById`, yang mengembalikan referensi `IElement` atau `null` jika ID tidak ada. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Tips profesional:** Meskipun markup kami sangat kecil, menambahkan pemeriksaan null menghindarkan Anda dari masalah ketika logika yang sama digunakan kembali pada halaman yang lebih besar dan dinamis. + +## Temukan Elemen berdasarkan ID – Pendekatan Alternatif + +Kadang‑kadang Anda mungkin sudah memiliki referensi ke akar dokumen dan lebih suka pencarian bergaya query. Menggunakan selector CSS (`QuerySelector`) adalah cara lain untuk **locate element by id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **Kapan menggunakan yang mana?** `GetElementById` sedikit lebih cepat karena merupakan pencarian hash langsung. `QuerySelector` unggul ketika Anda membutuhkan selector kompleks (mis., `div > p.highlight`). + +## Ubah Gaya Elemen HTML – Menambahkan Tebal Miring + +Dengan elemen di tangan, langkah selanjutnya adalah **change HTML element style**. Aspose.Html menyediakan objek `Style` dimana Anda dapat menyesuaikan properti CSS atau menggunakan enumerasi `WebFontStyle` yang praktis untuk menerapkan beberapa sifat font sekaligus. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Baris tunggal itu mengatur `font-weight` elemen menjadi `bold` dan `font-style` menjadi `italic`. Di balik layar Aspose.Html menerjemahkan enum tersebut menjadi string CSS yang sesuai. + +### Contoh Lengkap yang Berfungsi + +Menggabungkan semua bagian menghasilkan program ringkas dan mandiri yang dapat Anda kompilasi dan jalankan segera: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Output yang Diharapkan** + +``` +Rendered HTML: +

Hello world

+``` + +Tag `

` kini memiliki atribut `style` inline yang membuat teks menjadi tebal dan miring—tepat seperti yang kami inginkan. + +## Kasus Tepi & Kesalahan Umum + +| Situasi | Hal yang Perlu Diperhatikan | Cara Menangani | +|-----------|-------------------|---------------| +| **ID tidak ada** | `GetElementById` mengembalikan `null`. | Lemparkan pengecualian atau gunakan elemen default sebagai cadangan. | +| **Beberapa elemen berbagi ID yang sama** | Spesifikasi HTML menyatakan ID harus unik, namun halaman dunia nyata kadang melanggar aturan. | `GetElementById` mengembalikan kecocokan pertama; pertimbangkan menggunakan `QuerySelectorAll` jika Anda perlu menangani duplikat. | +| **Konflik styling** | Gaya inline yang ada mungkin ditimpa. | Tambahkan ke objek `Style` alih-alih mengatur seluruh string `style`: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Rendering di browser** | Beberapa browser mengabaikan `WebFontStyle` jika elemen sudah memiliki kelas CSS dengan spesifisitas lebih tinggi. | Gunakan `!important` melalui `paragraph.Style.SetProperty("font-weight", "bold", "important");` bila diperlukan. | + +## Tips Pro untuk Proyek Dunia‑Nyata + +- **Cache dokumen** jika Anda memproses banyak elemen; membuat `HTMLDocument` baru untuk setiap potongan kecil dapat menurunkan kinerja. +- **Gabungkan perubahan gaya** dalam satu transaksi `Style` untuk menghindari beberapa reflow DOM. +- **Manfaatkan mesin rendering Aspose.Html** untuk mengekspor dokumen akhir sebagai PDF atau gambar—bagus untuk alat pelaporan. + +## Konfirmasi Visual (Opsional) + +Jika Anda lebih suka melihat hasilnya di browser, Anda dapat menyimpan string yang dirender ke file `.html`: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Buka `output.html` dan Anda akan melihat **Hello world** ditampilkan dalam tebal + miring. + +![Contoh Membuat Dokumen HTML C# menampilkan paragraf tebal miring](/images/create-html-document-csharp.png "Membuat Dokumen HTML C# – output yang dirender") + +*Teks alternatif: Membuat Dokumen HTML C# – output yang dirender dengan teks tebal miring.* + +## Kesimpulan + +Kami baru saja **membuat dokumen HTML C#**, **mendapatkan elemen berdasarkan id**, **menemukan elemen berdasarkan id**, **mengubah gaya elemen HTML**, dan akhirnya **menambahkan tebal miring**—semua dengan beberapa baris kode menggunakan Aspose.Html. Pendekatan ini sederhana, bekerja di lingkungan .NET apa pun, dan dapat diskalakan untuk manipulasi DOM yang lebih besar. + +Siap untuk langkah selanjutnya? Coba ganti `WebFontStyle` dengan enum lain seperti `Underline` atau gabungkan beberapa gaya secara manual. Atau bereksperimen dengan memuat file HTML eksternal dan menerapkan teknik yang sama pada ratusan elemen. Tidak ada batasan, dan kini Anda memiliki fondasi yang kuat untuk dibangun. + +Selamat coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/indonesian/net/html-extensions-and-conversions/_index.md b/html/indonesian/net/html-extensions-and-conversions/_index.md index 6ac5368ff..63cf60bc5 100644 --- a/html/indonesian/net/html-extensions-and-conversions/_index.md +++ b/html/indonesian/net/html-extensions-and-conversions/_index.md @@ -39,41 +39,70 @@ Aspose.HTML untuk .NET bukan sekadar pustaka; pustaka ini merupakan pengubah per ## Tutorial Ekstensi dan Konversi HTML ### [Konversi HTML ke PDF dalam .NET dengan Aspose.HTML](./convert-html-to-pdf/) Ubah HTML ke PDF dengan mudah menggunakan Aspose.HTML untuk .NET. Ikuti panduan langkah demi langkah kami dan manfaatkan kekuatan konversi HTML ke PDF. + ### [Buat PDF dari HTML – Panduan Langkah‑demi‑Langkah C#](./create-pdf-from-html-c-step-by-step-guide/) Pelajari cara membuat PDF dari HTML menggunakan C# dengan panduan langkah demi langkah menggunakan Aspose.HTML. + +### [Buat PDF dari HTML dengan Aspose – Panduan Langkah‑demi‑Langkah C#](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Pelajari cara membuat PDF dari HTML dengan Aspose menggunakan C# melalui panduan langkah demi langkah yang lengkap. + ### [Konversi EPUB ke Gambar dalam .NET dengan Aspose.HTML](./convert-epub-to-image/) Pelajari cara mengonversi EPUB ke gambar menggunakan Aspose.HTML untuk .NET. Tutorial langkah demi langkah dengan contoh kode dan opsi yang dapat disesuaikan. + ### [Konversi EPUB ke PDF dalam .NET dengan Aspose.HTML](./convert-epub-to-pdf/) Pelajari cara mengonversi EPUB ke PDF menggunakan Aspose.HTML untuk .NET. Panduan langkah demi langkah ini mencakup opsi penyesuaian, FAQ, dan banyak lagi untuk konversi dokumen yang lancar. + ### [Konversi EPUB ke XPS dalam .NET dengan Aspose.HTML](./convert-epub-to-xps/) Pelajari cara mengonversi EPUB ke XPS dalam format .NET menggunakan Aspose.HTML untuk .NET. Ikuti panduan langkah demi langkah kami untuk konversi yang mudah. + ### [Konversi HTML ke BMP di .NET dengan Aspose.HTML](./convert-html-to-bmp/) Pelajari cara mengonversi HTML ke BMP dalam .NET menggunakan Aspose.HTML untuk .NET. Panduan lengkap bagi pengembang web untuk memanfaatkan Aspose.HTML untuk .NET. + ### [Konversi HTML ke DOC dan DOCX dalam .NET dengan Aspose.HTML](./convert-html-to-doc-docx/) Pelajari cara memanfaatkan kekuatan Aspose.HTML untuk .NET dalam panduan langkah demi langkah ini. Ubah HTML menjadi DOCX dengan mudah dan tingkatkan proyek .NET Anda. Mulailah hari ini! + ### [Konversi HTML ke GIF di .NET dengan Aspose.HTML](./convert-html-to-gif/) Temukan kekuatan Aspose.HTML untuk .NET: Panduan langkah demi langkah untuk mengonversi HTML ke GIF. Prasyarat, contoh kode, Tanya Jawab Umum, dan banyak lagi! Optimalkan manipulasi HTML Anda dengan Aspose.HTML. + ### [Konversi HTML ke JPEG dalam .NET dengan Aspose.HTML](./convert-html-to-jpeg/) Pelajari cara mengonversi HTML ke JPEG dalam .NET dengan Aspose.HTML untuk .NET. Panduan langkah demi langkah untuk memanfaatkan kekuatan Aspose.HTML untuk .NET. Optimalkan tugas pengembangan web Anda dengan mudah. + ### [Konversi HTML ke Markdown di .NET dengan Aspose.HTML](./convert-html-to-markdown/) Pelajari cara mengonversi HTML ke Markdown dalam .NET menggunakan Aspose.HTML untuk manipulasi konten yang efisien. Dapatkan panduan langkah demi langkah untuk proses konversi yang lancar. + ### [Konversi HTML ke MHTML di .NET dengan Aspose.HTML](./convert-html-to-mhtml/) Konversi HTML ke MHTML dalam .NET dengan Aspose.HTML - Panduan langkah demi langkah untuk pengarsipan konten web yang efisien. Pelajari cara menggunakan Aspose.HTML untuk .NET guna membuat arsip MHTML. + ### [Konversi HTML ke PNG dalam .NET dengan Aspose.HTML](./convert-html-to-png/) Temukan cara menggunakan Aspose.HTML untuk .NET guna memanipulasi dan mengonversi dokumen HTML. Panduan langkah demi langkah untuk pengembangan .NET yang efektif. + +### [Konversi HTML ke Gambar dalam C# – Panduan Lengkap](./convert-html-to-image-in-c-complete-guide/) +Pelajari cara mengonversi HTML menjadi gambar menggunakan C# dengan panduan lengkap dan contoh kode Aspose.HTML. + ### [Konversi HTML ke TIFF dalam .NET dengan Aspose.HTML](./convert-html-to-tiff/) Pelajari cara mengonversi HTML ke TIFF dengan Aspose.HTML untuk .NET. Ikuti panduan langkah demi langkah kami untuk pengoptimalan konten web yang efisien. + ### [Konversi HTML ke XPS dalam .NET dengan Aspose.HTML](./convert-html-to-xps/) Temukan kekuatan Aspose.HTML untuk .NET: Ubah HTML menjadi XPS dengan mudah. Prasyarat, panduan langkah demi langkah, dan Tanya Jawab Umum disertakan. + ### [Cara Mengompres HTML menjadi Zip di C# – Simpan HTML ke Zip](./how-to-zip-html-in-c-save-html-to-zip/) Pelajari cara mengompres file HTML menjadi arsip ZIP menggunakan C# dan Aspose.HTML. + ### [Buat Dokumen HTML dengan Teks Bergaya dan Ekspor ke PDF – Panduan Lengkap](./create-html-document-with-styled-text-and-export-to-pdf-full/) Pelajari cara membuat dokumen HTML dengan teks berformat dan mengekspornya ke PDF menggunakan Aspose.HTML untuk .NET. + ### [Simpan HTML sebagai ZIP – Tutorial Lengkap C#](./save-html-as-zip-complete-c-tutorial/) 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 sebagai ZIP di C# – Panduan Lengkap dengan Penyimpanan Kustom](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Pelajari cara menyimpan file HTML ke dalam arsip ZIP dengan penyimpanan kustom menggunakan C# dan Aspose.HTML. + +### [Cara Mengompres HTML menjadi Zip dengan Aspose.HTML – Panduan Lengkap](./how-to-zip-html-with-aspose-html-complete-guide/) +Pelajari cara mengompres HTML menjadi arsip ZIP dengan Aspose.HTML dalam panduan lengkap. + ## Kesimpulan Kesimpulannya, ekstensi dan konversi HTML merupakan elemen penting dalam pengembangan web modern. Aspose.HTML untuk .NET menyederhanakan proses dan membuatnya dapat diakses oleh pengembang dari semua tingkatan. Dengan mengikuti tutorial kami, Anda akan berada di jalur yang tepat untuk menjadi pengembang web yang ahli dengan keahlian yang luas. diff --git a/html/indonesian/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/indonesian/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..dc695d4c0 --- /dev/null +++ b/html/indonesian/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Konversi HTML ke gambar menggunakan Aspose.HTML di C#. Pelajari cara + menyimpan HTML sebagai PNG, mengatur ukuran rendering gambar, dan menulis gambar + ke file dalam beberapa langkah saja. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: id +og_description: Konversi HTML ke gambar dengan cepat. Panduan ini menunjukkan cara + menyimpan HTML sebagai PNG, mengatur ukuran rendering gambar, dan menulis gambar + ke file dengan Aspose.HTML. +og_title: Mengonversi HTML ke Gambar di C# – Panduan Langkah demi Langkah +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Mengonversi HTML ke Gambar di C# – Panduan Lengkap +url: /id/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mengonversi HTML ke Gambar di C# – Panduan Lengkap + +Pernahkah Anda perlu **mengonversi HTML ke gambar** untuk thumbnail dasbor, pratinjau email, atau laporan PDF? Ini adalah skenario yang muncul lebih sering daripada yang Anda kira, terutama ketika Anda menangani konten web dinamis yang harus disematkan di tempat lain. + +Kabar baiknya? Dengan Aspose.HTML Anda dapat **mengonversi HTML ke gambar** hanya dengan beberapa baris kode, dan Anda juga akan belajar cara *menyimpan HTML sebagai PNG*, mengontrol dimensi output, serta *menulis gambar ke file* tanpa kesulitan. + +Dalam tutorial ini kami akan membahas semua yang perlu Anda ketahui: mulai dari memuat halaman remote hingga menyesuaikan ukuran rendering, dan akhirnya menyimpan hasilnya sebagai file PNG di disk. Tanpa alat eksternal, tanpa trik baris perintah yang rumit—hanya kode C# murni yang dapat Anda sisipkan ke proyek .NET apa pun. + +## Apa yang Akan Anda Pelajari + +- Cara **render halaman web ke PNG** menggunakan kelas `HTMLDocument` dari Aspose.HTML. +- Langkah tepat untuk **mengatur ukuran rendering gambar** sehingga output sesuai dengan kebutuhan tata letak Anda. +- Cara **menulis gambar ke file** dengan aman, menangani stream dan jalur file. +- Tips untuk memecahkan masalah umum seperti font yang hilang atau timeout jaringan. + +### Prasyarat + +- .NET 6.0 atau yang lebih baru (API ini juga bekerja dengan .NET Framework, tetapi .NET 6+ disarankan). +- Referensi ke paket NuGet Aspose.HTML for .NET (`Aspose.Html`). +- Familiaritas dasar dengan C# dan async/await (opsional tetapi membantu). + +Jika Anda sudah memiliki semua itu, Anda siap mulai mengonversi HTML ke gambar segera. + +## Langkah 1: Muat Halaman Web – Fondasi Mengonversi HTML ke Gambar + +Sebelum rendering apa pun dapat terjadi, Anda memerlukan instance `HTMLDocument` yang mewakili halaman yang ingin Anda tangkap. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Mengapa ini penting:* `HTMLDocument` mem-parsing HTML, menyelesaikan CSS, dan membangun DOM. Jika dokumen tidak dapat dimuat (misalnya, masalah jaringan), rendering berikutnya akan menghasilkan gambar kosong. Selalu pastikan URL dapat diakses sebelum melanjutkan. + +## Langkah 2: Atur Ukuran Rendering Gambar – Mengontrol Lebar, Tinggi, dan Kualitas + +Aspose.HTML memungkinkan Anda menyesuaikan dimensi output dengan `ImageRenderingOptions`. Di sinilah Anda **mengatur ukuran rendering gambar** agar sesuai dengan tata letak target Anda. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Tip profesional:* Jika Anda tidak menyertakan `Width` dan `Height`, Aspose.HTML akan menggunakan ukuran intrinsik halaman, yang dapat tidak dapat diprediksi untuk desain responsif. Menentukan dimensi eksplisit memastikan output **menyimpan HTML sebagai PNG** terlihat persis seperti yang Anda harapkan. + +## Langkah 3: Tulis Gambar ke File – Menyimpan PNG yang Telah Dirender + +Setelah dokumen siap dan opsi rendering sudah diatur, Anda akhirnya dapat **menulis gambar ke file**. Menggunakan `FileStream` menjamin file dibuat dengan aman, bahkan jika folder belum ada. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +Setelah blok ini dijalankan, Anda akan menemukan `page.png` di lokasi yang Anda tentukan. Anda baru saja **merender halaman web ke PNG** dan menulisnya ke disk dalam satu operasi yang sederhana. + +### Hasil yang Diharapkan + +Buka `C:\Temp\page.png` dengan penampil gambar apa pun. Anda akan melihat snapshot akurat dari `https://example.com`, dirender pada 1024 × 768 piksel dengan tepi halus berkat antialiasing. Jika halaman berisi konten dinamis (misalnya, elemen yang dihasilkan JavaScript), mereka akan tertangkap selama DOM sepenuhnya dimuat sebelum rendering. + +## Langkah 4: Menangani Kasus Khusus – Font, Autentikasi, dan Halaman Besar + +Meskipun alur dasar bekerja untuk kebanyakan situs publik, skenario dunia nyata seringkali memberikan tantangan: + +| Situasi | Apa yang Harus Dilakukan | +|-----------|------------| +| **Font khusus tidak dimuat** | Tempatkan file font secara lokal dan set `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Halaman di balik autentikasi** | Gunakan overload `HTMLDocument` yang menerima `HttpWebRequest` dengan cookie atau token. | +| **Halaman sangat tinggi** | Tingkatkan `Height` atau aktifkan `PageScaling` pada `ImageRenderingOptions` untuk menghindari pemotongan. | +| **Lonjakan penggunaan memori** | Render dalam potongan menggunakan overload `RenderToImage` yang menerima wilayah `Rectangle`. | + +Menangani nuansa *menulis gambar ke file* ini memastikan pipeline **mengonversi html ke gambar** Anda tetap kuat dalam produksi. + +## Langkah 5: Contoh Lengkap – Siap Salin‑Tempel + +Berikut adalah seluruh program, siap untuk dikompilasi. Program ini mencakup semua langkah, penanganan error, dan komentar yang Anda perlukan. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Jalankan program ini, dan Anda akan melihat pesan konfirmasi di konsol. File PNG akan persis seperti yang Anda harapkan ketika **merender halaman web ke PNG** secara manual di browser dan mengambil screenshot—hanya lebih cepat dan sepenuhnya otomatis. + +## Pertanyaan yang Sering Diajukan + +**T: Bisakah saya mengonversi file HTML lokal alih-alih URL?** +Tentu saja. Ganti URL dengan jalur file: `new HTMLDocument(@"C:\myPage.html")`. + +**T: Apakah saya memerlukan lisensi untuk Aspose.HTML?** +Lisensi evaluasi gratis cukup untuk pengembangan dan pengujian. Untuk produksi, beli lisensi untuk menghilangkan watermark evaluasi. + +**T: Bagaimana jika halaman menggunakan JavaScript untuk memuat konten setelah pemuatan awal?** +Aspose.HTML mengeksekusi JavaScript secara sinkron selama parsing, tetapi skrip yang berjalan lama mungkin memerlukan penundaan manual. Anda dapat menggunakan `HTMLDocument.WaitForReadyState` sebelum rendering. + +## Kesimpulan + +Anda kini memiliki solusi menyeluruh, ujung‑ke‑ujung, untuk **mengonversi HTML ke gambar** di C#. Dengan mengikuti langkah‑langkah di atas Anda dapat **menyimpan HTML sebagai PNG**, secara tepat **mengatur ukuran rendering gambar**, dan dengan percaya diri **menulis gambar ke file** di lingkungan Windows atau Linux mana pun. + +Dari screenshot sederhana hingga pembuatan laporan otomatis, teknik ini skalabel dengan baik. Selanjutnya, coba bereksperimen dengan format output lain seperti JPEG atau BMP, atau integrasikan kode ke dalam API ASP.NET Core yang mengembalikan PNG langsung ke pemanggil. Kemungkinannya hampir tak terbatas. + +Selamat coding, semoga gambar yang Anda render selalu tampak pixel‑perfect! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/indonesian/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..b4fcf8ccc --- /dev/null +++ b/html/indonesian/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-03-21 +description: Buat PDF dari HTML dengan cepat menggunakan Aspose HTML. Pelajari cara + merender HTML ke PDF, mengonversi HTML ke PDF, dan cara menggunakan Aspose dalam + tutorial singkat. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: id +og_description: Buat PDF dari HTML dengan Aspose di C#. Panduan ini menunjukkan cara + merender HTML ke PDF, mengonversi HTML ke PDF, dan cara menggunakan Aspose secara + efektif. +og_title: Buat PDF dari HTML – Tutorial Lengkap Aspose C# +tags: +- Aspose +- C# +- PDF generation +title: Buat PDF dari HTML dengan Aspose – Panduan C# Langkah demi Langkah +url: /id/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buat PDF dari HTML dengan Aspose – Panduan Langkah‑demi‑Langkah C# + +Pernah perlu **membuat PDF dari HTML** tetapi tidak yakin perpustakaan mana yang akan memberikan hasil pixel‑perfect? Anda tidak sendirian. Banyak pengembang mengalami kesulitan ketika mencoba mengubah cuplikan web menjadi dokumen yang dapat dicetak, hanya untuk berakhir dengan teks yang buram atau tata letak yang rusak. + +Kabar baiknya, Aspose HTML membuat seluruh proses menjadi mudah. Dalam tutorial ini kami akan menelusuri kode tepat yang Anda perlukan untuk **render HTML ke PDF**, menjelaskan mengapa setiap pengaturan penting, dan menunjukkan cara **mengonversi HTML ke PDF** tanpa trik tersembunyi. Pada akhir tutorial, Anda akan tahu **cara menggunakan Aspose** untuk menghasilkan PDF yang dapat diandalkan dalam proyek .NET apa pun. + +## Prasyarat – Apa yang Anda Butuhkan Sebelum Memulai + +- **.NET 6.0 atau lebih baru** (contoh ini juga bekerja pada .NET Framework 4.7+) +- **Visual Studio 2022** atau IDE apa pun yang mendukung C# +- Paket NuGet **Aspose.HTML for .NET** (versi percobaan gratis atau berlisensi) +- Pemahaman dasar tentang sintaks C# (tidak memerlukan pengetahuan PDF yang mendalam) + +Jika Anda sudah memiliki semua itu, Anda siap memulai. Jika belum, unduh .NET SDK terbaru dan instal paket NuGet dengan: + +```bash +dotnet add package Aspose.HTML +``` + +Baris tunggal itu mengimpor semua yang Anda perlukan untuk konversi **aspose html to pdf**. + +--- + +## Langkah 1: Siapkan Proyek Anda untuk Membuat PDF dari HTML + +Hal pertama yang harus Anda lakukan adalah membuat aplikasi konsol baru (atau mengintegrasikan kode ke layanan yang sudah ada). Berikut ini kerangka minimal `Program.cs`: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** Jika Anda melihat `Aspise.Html.Rendering.Text` pada contoh lama, ganti dengan `Aspose.Html.Rendering.Text`. Kesalahan ketik ini akan menyebabkan error kompilasi. + +Memiliki namespace yang tepat memastikan kompiler dapat menemukan kelas **TextOptions** yang akan kita gunakan nanti. + +## Langkah 2: Bangun Dokumen HTML (Render HTML ke PDF) + +Sekarang kita buat HTML sumber. Aspose memungkinkan Anda memberikan string mentah, jalur file, atau bahkan URL. Untuk demo ini kami akan tetap sederhana: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Mengapa menggunakan string? Karena menghindari I/O sistem berkas, mempercepat konversi, dan memastikan HTML yang Anda lihat di kode persis sama dengan yang dirender. Jika Anda lebih suka memuat dari file, cukup ganti argumen konstruktor dengan URI file. + +## Langkah 3: Sesuaikan Rendering Teks (Konversi HTML ke PDF dengan Kualitas Lebih Baik) + +Rendering teks sering menentukan apakah PDF Anda tampak tajam atau kabur. Aspose menyediakan kelas `TextOptions` yang memungkinkan Anda mengaktifkan sub‑pixel hinting—penting untuk output ber‑DPI tinggi. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Mengaktifkan `UseHinting` sangat berguna ketika HTML sumber berisi font khusus atau ukuran font kecil. Tanpanya, Anda mungkin melihat tepi bergerigi pada PDF akhir. + +## Langkah 4: Lampirkan Opsi Teks ke Konfigurasi Rendering PDF (Cara Menggunakan Aspose) + +Selanjutnya, kami mengikat opsi teks tersebut ke renderer PDF. Di sinilah **aspose html to pdf** benar‑benar bersinar—semua mulai dari ukuran halaman hingga kompresi dapat disesuaikan. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Anda dapat menghilangkan `PageSetup` jika ukuran A4 default sudah cukup. Inti pentingnya adalah objek `TextOptions` berada di dalam `PdfRenderingOptions`, dan itulah cara memberi tahu Aspose *bagaimana* merender teks. + +## Langkah 5: Render HTML dan Simpan PDF (Konversi HTML ke PDF) + +Akhirnya, kami menyalurkan output ke file. Menggunakan blok `using` menjamin handle file ditutup dengan benar, bahkan jika terjadi pengecualian. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Saat Anda menjalankan program, Anda akan menemukan `output.pdf` di samping executable. Buka file tersebut, dan Anda akan melihat judul dan paragraf yang bersih—persis seperti yang didefinisikan dalam string HTML. + +### Output yang Diharapkan + +![contoh output pdf dari html](https://example.com/images/pdf-output.png "contoh output pdf dari html") + +*Tangkap layar menunjukkan PDF yang dihasilkan dengan judul “Hello, Aspose!” yang ditampilkan tajam berkat text hinting.* + +--- + +## Pertanyaan Umum & Kasus Tepi + +### 1. Bagaimana jika HTML saya merujuk ke sumber eksternal (gambar, CSS)? + +Aspose menyelesaikan URL relatif berdasarkan base URI dokumen. Jika Anda memberi string mentah, atur base URI secara manual: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Sekarang setiap `` akan dicari relatif terhadap `C:/MyProject/`. + +### 2. Bagaimana cara menyematkan font yang tidak terpasang di server? + +Tambahkan blok ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Langkah 4: Konfigurasikan Opsi Penyimpanan untuk Menggunakan Penyimpanan Kustom + +`HtmlSaveOptions` memungkinkan kami memberi tahu Aspose untuk mengemas semuanya ke dalam file ZIP. Properti `OutputStorage` (legacy) menerima instance `MyStorage` kami. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Catatan:** Pada Aspose HTML 23.9+ properti tersebut bernama `OutputStorage` tetapi ditandai usang. Alternatif modernnya adalah `ZipOutputStorage`. Kode di bawah ini bekerja dengan keduanya karena antarmukanya sama. + +### Langkah 5: Simpan Dokumen sebagai Arsip ZIP + +Pilih folder target (atau stream) dan biarkan Aspose melakukan pekerjaan berat. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Setelah program selesai, Anda akan menemukan `output.zip` yang berisi: + +* `index.html` – dokumen utama. +* Semua gambar, file CSS, atau skrip yang tersemat (jika HTML Anda merujuknya). + +Anda dapat membuka ZIP dengan pengelola arsip apa pun untuk memverifikasi struktur. + +--- + +## Memverifikasi Hasil (Opsional) + +Jika Anda ingin memeriksa arsip secara programatis tanpa mengekstraknya ke disk: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Output tipikal: + +``` +- index.html (452 bytes) +``` + +Jika Anda memiliki gambar atau CSS, mereka akan muncul sebagai entri tambahan. Pemeriksaan cepat ini mengonfirmasi bahwa **create html zip archive** berfungsi seperti yang diharapkan. + +--- + +## Pertanyaan Umum & Kasus Tepi + +| Pertanyaan | Jawaban | +|------------|---------| +| **Bagaimana jika saya perlu menulis ZIP langsung ke stream respons?** | Kembalikan `MemoryStream` yang Anda dapatkan dari `MyStorage` setelah `document.Save`. Cast menjadi `byte[]` dan tulis ke `HttpResponse.Body`. | +| **HTML saya merujuk URL eksternal—apakah mereka akan diunduh?** | Tidak. Aspose hanya mengemas sumber daya yang *tersemat* (misalnya, `` atau file lokal). Untuk aset remote Anda harus mengunduhnya terlebih dahulu dan menyesuaikan markup. | +| **Properti `OutputStorage` ditandai usang—haruskah saya mengabaikannya?** | Masih berfungsi, tetapi `ZipOutputStorage` yang lebih baru menawarkan API yang sama dengan nama yang berbeda. Ganti `OutputStorage` dengan `ZipOutputStorage` jika Anda menginginkan build bebas peringatan. | +| **Bisakah saya mengenkripsi ZIP?** | Ya. Setelah menyimpan, buka file dengan `System.IO.Compression.ZipArchive` dan atur kata sandi menggunakan pustaka pihak ketiga seperti `SharpZipLib`. Aspose sendiri tidak menyediakan enkripsi. | + +## Contoh Lengkap yang Berfungsi (Salin‑Tempel) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Jalankan program, buka `output.zip`, dan Anda akan melihat satu file `index.html` yang menampilkan judul “Hello from ZIP!” saat dibuka di browser. + +## Kesimpulan + +Anda kini tahu **cara menyimpan HTML sebagai ZIP** di C# menggunakan kelas **penyimpanan kustom**, cara **mengekspor HTML ke ZIP**, dan cara **membuat arsip zip HTML** yang siap didistribusikan. Pola ini fleksibel—ganti `MemoryStream` dengan stream cloud, tambahkan enkripsi, atau integrasikan ke dalam API web yang mengembalikan ZIP sesuai permintaan. + +Siap untuk langkah selanjutnya? Cobalah memberikan halaman web lengkap dengan gambar dan gaya, atau hubungkan penyimpanan ke Azure Blob Storage untuk melewati sistem file lokal sepenuhnya. Tidak ada batasan ketika Anda menggabungkan kemampuan ZIP Aspose.HTML dengan logika penyimpanan Anda sendiri. + +Selamat coding, semoga arsip Anda selalu rapi! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/italian/net/generate-jpg-and-png-images/_index.md b/html/italian/net/generate-jpg-and-png-images/_index.md index f6e8b2d8a..655930290 100644 --- a/html/italian/net/generate-jpg-and-png-images/_index.md +++ b/html/italian/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Impara a usare Aspose.HTML per .NET per manipolare documenti HTML, convertire HT Scopri come abilitare l'antialiasing durante la conversione di documenti DOCX in immagini PNG o JPG con Aspose.HTML per .NET. ### [Converti docx in PNG – crea archivio zip C# tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Impara a convertire documenti DOCX in PNG e a comprimerli in un archivio ZIP usando C# e Aspose.HTML. +### [Converti HTML in PNG – Guida completa C# con esportazione ZIP](./convert-html-to-png-full-c-guide-with-zip-export/) +Scopri come convertire HTML in PNG e comprimere le immagini in un archivio ZIP usando C# e Aspose.HTML. ## Conclusione diff --git a/html/italian/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/italian/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..5e488b2d8 --- /dev/null +++ b/html/italian/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Converti HTML in PNG e rendi l'HTML come immagine salvando l'HTML in + ZIP. Impara ad applicare lo stile del font in HTML e ad aggiungere il grassetto + agli elementi p in pochi passaggi. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: it +og_description: Converti HTML in PNG rapidamente. Questa guida mostra come renderizzare + HTML come immagine, salvare HTML in ZIP, applicare lo stile del font HTML e aggiungere + il grassetto agli elementi p. +og_title: Converti HTML in PNG – Tutorial completo C# +tags: +- Aspose +- C# +title: Converti HTML in PNG – Guida completa C# con esportazione ZIP +url: /it/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converti HTML in PNG – Guida completa C# con esportazione ZIP + +Ti è mai capitato di dover **convertire HTML in PNG** senza sapere quale libreria potesse farlo senza ricorrere a un browser headless? Non sei il solo. In molti progetti—miniature di email, anteprime di documentazione o immagini di quick‑look—trasformare una pagina web in un’immagine statica è una necessità reale. + +La buona notizia? Con Aspose.HTML puoi **renderizzare HTML come immagine**, modificare il markup al volo e persino **salvare HTML in ZIP** per una distribuzione successiva. In questo tutorial percorreremo un esempio completo, eseguibile, che **applica lo stile di carattere HTML**, in particolare **aggiunge il grassetto ai paragrafi `

`**, prima di produrre un file PNG. Alla fine avrai una singola classe C# che gestisce tutto, dal caricamento della pagina all’archiviazione delle risorse. + +## Cosa ti serve + +- .NET 6.0 o successivo (l’API funziona anche su .NET Core) +- Aspose.HTML per .NET 6+ (pacchetto NuGet `Aspose.Html`) +- Una conoscenza di base della sintassi C# (non servono concetti avanzati) + +Tutto qui. Nessun browser esterno, nessun phantomjs, solo codice gestito puro. + +## Passo 1 – Carica il documento HTML + +Per prima cosa importiamo il file sorgente (o l’URL) in un oggetto `HTMLDocument`. Questo passaggio è la base sia per **render html as image** sia per **save html to zip** successivamente. + +```csharp +using Aspose.Html; +using System.IO; + +///

+/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Perché è importante:* la classe `HTMLDocument` analizza il markup, costruisce un DOM e risolve le risorse collegate (CSS, immagini, font). Senza un documento corretto non è possibile manipolare gli stili né renderizzare nulla. + +## Passo 2 – Applica lo stile di carattere HTML (Aggiungi grassetto a `

`) + +Ora **applicheremo lo stile di carattere HTML** iterando su ogni elemento `

` e impostando il suo `font-weight` a bold. Questo è il modo programmatico per **add bold to p** senza modificare il file originale. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Consiglio:* se ti serve rendere bold solo un sottoinsieme, cambia il selettore con qualcosa di più specifico, ad esempio `"p.intro"`. + +## Passo 3 – Renderizza HTML come immagine (Converti HTML in PNG) + +Con il DOM pronto, configuriamo `ImageRenderingOptions` e chiamiamo `RenderToImage`. Qui avviene la magia del **convert html to png**. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Perché le opzioni contano:* impostare una larghezza/altezza fissa evita che l’output sia troppo grande, mentre l’antialiasing fornisce un risultato visivo più fluido. Puoi anche cambiare `options` in `ImageFormat.Jpeg` se preferisci un file più leggero. + +## Passo 4 – Salva HTML in ZIP (Raggruppa le risorse) + +Spesso è necessario distribuire l’HTML originale insieme a CSS, immagini e font. `ZipArchiveSaveOptions` di Aspose.HTML fa esattamente questo. Inseriamo anche un `ResourceHandler` personalizzato così tutte le risorse esterne vengono scritte nella stessa cartella dell’archivio. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Caso limite:* se il tuo HTML fa riferimento a immagini remote che richiedono autenticazione, il gestore predefinito fallirà. In tal caso puoi estendere `MyResourceHandler` per iniettare gli header HTTP necessari. + +## Passo 5 – Collega tutto in un’unica classe Converter + +Di seguito trovi la classe completa, pronta per l’esecuzione, che unisce tutti i passaggi precedenti. Copiala in una console app, chiama `Convert` e osserva i file generati. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Output previsto + +Dopo aver eseguito lo snippet sopra troverai due file nella cartella `outputDirectory`: + +| File | Descrizione | +|------|-------------| +| `page.png` | Un rendering PNG 1200 × 800 dell’HTML sorgente, con ogni paragrafo visualizzato in **grassetto**. | +| `archive.zip` | Un bundle ZIP contenente l’`input.html` originale, i suoi CSS, le immagini e tutti i web‑font – perfetto per la distribuzione offline. | + +Puoi aprire `page.png` con qualsiasi visualizzatore di immagini per verificare che lo stile bold sia stato applicato, ed estrarre `archive.zip` per vedere l’HTML intatto insieme alle sue risorse. + +## Domande frequenti e insidie + +- **E se l’HTML contiene JavaScript?** + Aspose.HTML **non** esegue script durante il rendering, quindi il contenuto dinamico non verrà visualizzato. Per pagine completamente renderizzate serve un browser headless, ma per template statici questo approccio è più veloce e leggero. + +- **Posso cambiare il formato di output in JPEG o BMP?** + Sì—basta modificare la proprietà `ImageFormat` di `ImageRenderingOptions`, ad esempio `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Devo rilasciare manualmente l’`HTMLDocument`?** + La classe implementa `IDisposable`. In un servizio a lunga esecuzione avvolgila in un blocco `using` o chiama `document.Dispose()` al termine. + +- **Come funziona il `MyResourceHandler` personalizzato?** + Riceve ogni risorsa esterna (CSS, immagini, font) e la scrive nella cartella specificata. Questo garantisce che lo ZIP contenga una copia fedele di tutto ciò a cui l’HTML fa riferimento. + +## Conclusione + +Ora disponi di una soluzione compatta, pronta per la produzione, che **convert html to png**, **render html as image**, **save html to zip**, **apply font style html** e **add bold to p**—tutto in poche righe di C#. Il codice è autonomo, funziona con .NET 6+ e può essere inserito in qualsiasi servizio backend che necessiti di snapshot visivi rapidi di contenuti web. + +Pronto per il passo successivo? Prova a modificare la dimensione di rendering, sperimenta con altre proprietà CSS (come `font-family` o `color`) o integra questo converter in un endpoint ASP.NET Core che restituisce il PNG su richiesta. Le possibilità sono infinite, e con Aspose.HTML rimani lontano dalle dipendenze di browser pesanti. + +Se hai incontrato problemi o hai idee per estensioni, lascia un commento qui sotto. Buon coding! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/italian/net/html-document-manipulation/_index.md index 830312f0e..56b55e01e 100644 --- a/html/italian/net/html-document-manipulation/_index.md +++ b/html/italian/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Impara a usare Aspose.HTML per .NET. Importa namespace, unisci HTML con XML e mi Sfrutta il potenziale dello sviluppo web con Aspose.HTML per .NET. Crea, converti e manipola documenti HTML con facilità. ### [Creare HTML da stringa in C# – Guida al gestore di risorse personalizzato](./create-html-from-string-in-c-custom-resource-handler-guide/) Impara a generare documenti HTML da stringhe C# usando un gestore di risorse personalizzato con Aspose.HTML. +### [Creare documento HTML in C# – Guida passo‑a‑passo](./create-html-document-c-step-by-step-guide/) +Scopri come creare un documento HTML in C# con Aspose.HTML, passo dopo passo, con esempi pratici e consigli utili. ## Conclusione diff --git a/html/italian/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/italian/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..9cf4736c7 --- /dev/null +++ b/html/italian/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: Crea un documento HTML in C# e impara come ottenere un elemento per ID, + localizzare un elemento per ID, modificare lo stile dell'elemento HTML e aggiungere + grassetto e corsivo usando Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: it +og_description: Crea un documento HTML in C# e impara subito a ottenere un elemento + per ID, individuare un elemento per ID, modificare lo stile di un elemento HTML + e aggiungere grassetto e corsivo con chiari esempi di codice. +og_title: Crea documento HTML C# – Guida completa alla programmazione +tags: +- Aspose.Html +- C# +- DOM manipulation +title: Crea documento HTML C# – Guida passo passo +url: /it/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea Documento HTML C# – Guida Passo‑Passo + +Hai mai dovuto **creare un documento HTML C#** da zero e poi modificare l’aspetto di un singolo paragrafo? Non sei l’unico. In molti progetti di web‑automation creerai un file HTML, troverai un tag per ID e poi applicherai uno stile—spesso grassetto + corsivo—senza mai toccare un browser. + +In questo tutorial passeremo passo passo: creeremo un documento HTML in C#, **get element by id**, **locate element by id**, **change HTML element style**, e infine **add bold italic** usando la libreria Aspose.Html. Alla fine avrai uno snippet completamente eseguibile da inserire in qualsiasi progetto .NET. + +## Cosa Ti Serve + +- .NET 6 o versioni successive (il codice funziona anche su .NET Framework 4.7+) +- Visual Studio 2022 (o qualsiasi editor tu preferisca) +- Il pacchetto NuGet **Aspose.Html** (`Install-Package Aspose.Html`) + +È tutto—nessun file HTML aggiuntivo, nessun server web, solo poche righe di C#. + +## Crea Documento HTML C# – Inizializza il Documento + +Prima di tutto: ti serve un oggetto `HTMLDocument` attivo con cui il motore Aspose.Html può lavorare. Pensalo come aprire un nuovo quaderno dove scriverai il tuo markup. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Perché è importante:** Passando la stringa grezza a `HTMLDocument`, eviti di gestire I/O di file e mantieni tutto in memoria—perfetto per test unitari o generazione on‑the‑fly. + +## Ottieni Elemento per ID – Trovare il Paragrafo + +Ora che il documento esiste, dobbiamo **get element by id**. L'API DOM fornisce `GetElementById`, che restituisce un riferimento `IElement` o `null` se l'ID non è presente. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Consiglio:** Anche se il nostro markup è piccolo, aggiungere un controllo su null evita problemi quando la stessa logica viene riutilizzata su pagine più grandi e dinamiche. + +## Individua Elemento per ID – Un Approccio Alternativo + +A volte potresti già avere un riferimento alla radice del documento e preferire una ricerca in stile query. Usare i selettori CSS (`QuerySelector`) è un altro modo per **locate element by id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **Quando usare quale?** `GetElementById` è leggermente più veloce perché è una ricerca hash diretta. `QuerySelector` brilla quando hai bisogno di selettori complessi (es., `div > p.highlight`). + +## Cambia Stile Elemento HTML – Aggiungere Grassetto Corsivo + +Con l'elemento in mano, il passo successivo è **change HTML element style**. Aspose.Html espone un oggetto `Style` dove puoi regolare le proprietà CSS o usare la comoda enumerazione `WebFontStyle` per applicare più tratti di font contemporaneamente. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Quella singola riga imposta `font-weight` dell'elemento a `bold` e `font-style` a `italic`. Internamente Aspose.Html traduce l'enum nella stringa CSS appropriata. + +### Esempio Completo Funzionante + +Unendo tutti i pezzi ottieni un programma compatto e autonomo che puoi compilare ed eseguire immediatamente: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Output previsto** + +``` +Rendered HTML: +

Hello world

+``` + +Il tag `

` ora contiene un attributo `style` inline che rende il testo sia grassetto che corsivo—esattamente quello che volevamo. + +## Casi Limite & Problemi Comuni + +| Situazione | Cosa Controllare | Come Gestire | +|------------|------------------|--------------| +| **ID non esiste** | `GetElementById` restituisce `null`. | Lancia un'eccezione o ricorri a un elemento predefinito. | +| **Più elementi condividono lo stesso ID** | La specifica HTML dice che gli ID devono essere unici, ma le pagine reali a volte violano la regola. | `GetElementById` restituisce la prima corrispondenza; considera l'uso di `QuerySelectorAll` se devi gestire duplicati. | +| **Conflitti di stile** | Gli stili inline esistenti potrebbero essere sovrascritti. | Aggiungi all'oggetto `Style` invece di impostare l'intera stringa `style`: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Rendering in un browser** | Alcuni browser ignorano `WebFontStyle` se l'elemento ha già una classe CSS con specificità più alta. | Usa `!important` tramite `paragraph.Style.SetProperty("font-weight", "bold", "important");` se necessario. | + +## Consigli Pro per Progetti Reali + +- **Cache the document** se stai elaborando molti elementi; creare un nuovo `HTMLDocument` per ogni piccolo snippet può penalizzare le prestazioni. +- **Combine style changes** in una singola transazione `Style` per evitare più ricalcoli del DOM. +- **Leverage Aspose.Html’s rendering engine** per esportare il documento finale come PDF o immagine—ottimo per gli strumenti di reporting. + +## Conferma Visiva (Opzionale) + +Se preferisci vedere il risultato in un browser, puoi salvare la stringa renderizzata in un file `.html`: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Apri `output.html` e vedrai **Hello world** visualizzato in grassetto + corsivo. + +![Esempio di Create HTML Document C# che mostra paragrafo in grassetto corsivo](/images/create-html-document-csharp.png "Create HTML Document C# – output renderizzato") + +*Testo alternativo: Create HTML Document C# – output renderizzato con testo in grassetto e corsivo.* + +## Conclusione + +Abbiamo appena **created an HTML document C#**, **got element by id**, **located element by id**, **changed HTML element style**, e infine **added bold italic**—tutto con poche righe usando Aspose.Html. L'approccio è semplice, funziona in qualsiasi ambiente .NET, e scala a manipolazioni DOM più grandi. + +Pronto per il passo successivo? Prova a sostituire `WebFontStyle` con altre enum come `Underline` o combina più stili manualmente. Oppure sperimenta caricando un file HTML esterno e applicando la stessa tecnica a centinaia di elementi. Il cielo è il limite, e ora hai una solida base su cui costruire. + +Buona programmazione! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/italian/net/html-extensions-and-conversions/_index.md b/html/italian/net/html-extensions-and-conversions/_index.md index fcf4daa30..4a884b920 100644 --- a/html/italian/net/html-extensions-and-conversions/_index.md +++ b/html/italian/net/html-extensions-and-conversions/_index.md @@ -61,6 +61,8 @@ Scopri come convertire HTML in Markdown in .NET usando Aspose.HTML per una manip Converti HTML in MHTML in .NET con Aspose.HTML - Una guida passo passo per un'archiviazione efficiente dei contenuti web. Scopri come usare Aspose.HTML per .NET per creare archivi MHTML. ### [Convertire HTML in PNG in .NET con Aspose.HTML](./convert-html-to-png/) Scopri come usare Aspose.HTML per .NET per manipolare e convertire documenti HTML. Guida passo passo per uno sviluppo .NET efficace. +### [Convertire HTML in immagine in C# – Guida completa](./convert-html-to-image-in-c-complete-guide/) +Scopri come convertire HTML in immagini usando Aspose.HTML per .NET con C#. Guida passo‑passo completa con esempi di codice. ### [Convertire HTML in TIFF in .NET con Aspose.HTML](./convert-html-to-tiff/) Scopri come convertire HTML in TIFF con Aspose.HTML per .NET. Segui la nostra guida passo passo per un'ottimizzazione efficiente dei contenuti web. ### [Convertire HTML in XPS in .NET con Aspose.HTML](./convert-html-to-xps/) @@ -69,10 +71,16 @@ Scopri la potenza di Aspose.HTML per .NET: converti HTML in XPS senza sforzo. Pr Scopri come comprimere un documento HTML in un file ZIP usando Aspose.HTML per .NET in C#. ### [Creare PDF da HTML – Guida passo‑a‑passo C#](./create-pdf-from-html-c-step-by-step-guide/) Crea un PDF da HTML in C# con Aspose.HTML per .NET. Segui la nostra guida passo passo per una conversione semplice ed efficace. +### [Crea PDF da HTML con Aspose – Guida passo‑a‑passo C#](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Crea PDF da HTML con Aspose in C#. Segui la nostra guida passo‑a‑passo per una conversione rapida e personalizzabile. ### [Salva HTML come ZIP – Tutorial completo C#](./save-html-as-zip-complete-c-tutorial/) 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 in C# – Guida completa con archiviazione personalizzata](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Impara a salvare HTML in un archivio ZIP con opzioni di archiviazione personalizzate usando Aspose.HTML per .NET in C#. +### [Come comprimere HTML con Aspose.HTML – Guida completa](./how-to-zip-html-with-aspose-html-complete-guide/) +Scopri come comprimere HTML in un archivio ZIP con Aspose.HTML in una guida completa passo passo. ## Conclusione diff --git a/html/italian/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/italian/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..e0357ff6f --- /dev/null +++ b/html/italian/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Converti HTML in immagine usando Aspose.HTML in C#. Scopri come salvare + HTML come PNG, impostare la dimensione di rendering dell'immagine e scrivere l'immagine + su file in pochi passaggi. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: it +og_description: Converti rapidamente HTML in immagine. Questa guida mostra come salvare + HTML come PNG, impostare le dimensioni del rendering dell'immagine e scrivere l'immagine + su file con Aspose.HTML. +og_title: Converti HTML in immagine in C# – Guida passo passo +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Converti HTML in immagine in C# – Guida completa +url: /it/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertire HTML in Immagine in C# – Guida Completa + +Ti è mai capitato di **convertire HTML in immagine** per una miniatura di dashboard, un'anteprima email o un report PDF? È uno scenario che compare più spesso di quanto ti aspetteresti, soprattutto quando lavori con contenuti web dinamici che devono essere incorporati altrove. + +La buona notizia? Con Aspose.HTML puoi **convertire HTML in immagine** in poche righe di codice, e imparerai anche come *salvare HTML come PNG*, controllare le dimensioni dell'output e *scrivere l'immagine su file* senza sforzo. + +In questo tutorial vedremo tutto ciò che devi sapere: dal caricamento di una pagina remota alla regolazione della dimensione di rendering, fino al salvataggio del risultato come file PNG su disco. Nessuno strumento esterno, nessun trucco da riga di comando complicato—solo puro codice C# che puoi inserire in qualsiasi progetto .NET. + +## Cosa Imparerai + +- Come **renderizzare una pagina web in PNG** usando la classe `HTMLDocument` di Aspose.HTML. +- I passaggi esatti per **impostare il rendering delle dimensioni dell'immagine** in modo che l'output corrisponda ai requisiti del tuo layout. +- Modi per **scrivere l'immagine su file** in modo sicuro, gestendo stream e percorsi dei file. +- Suggerimenti per risolvere problemi comuni come font mancanti o timeout di rete. + +### Prerequisiti + +- .NET 6.0 o successivo (l'API funziona anche con .NET Framework, ma si consiglia .NET 6+). +- Un riferimento al pacchetto NuGet Aspose.HTML per .NET (`Aspose.Html`). +- Familiarità di base con C# e async/await (opzionale ma utile). + +Se hai già tutto questo, sei pronto per iniziare a convertire HTML in immagine subito. + +## Passo 1: Carica la Pagina Web – La Base per Convertire HTML in Immagine + +Prima che possa avvenire qualsiasi rendering, hai bisogno di un'istanza `HTMLDocument` che rappresenti la pagina che desideri catturare. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Perché è importante:* `HTMLDocument` analizza l'HTML, risolve il CSS e costruisce il DOM. Se il documento non può essere caricato (ad esempio, per problemi di rete), il rendering successivo produrrà un'immagine vuota. Verifica sempre che l'URL sia raggiungibile prima di procedere. + +## Passo 2: Imposta il Rendering delle Dimensioni dell'Immagine – Controllo di Larghezza, Altezza e Qualità + +Aspose.HTML ti permette di regolare finemente le dimensioni dell'output con `ImageRenderingOptions`. Qui è dove **imposti il rendering delle dimensioni dell'immagine** per corrispondere al layout desiderato. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Consiglio professionale:* Se ometti `Width` e `Height`, Aspose.HTML utilizzerà la dimensione intrinseca della pagina, che può essere imprevedibile per design responsivi. Specificare dimensioni esplicite garantisce che il risultato del tuo **salva HTML come PNG** appaia esattamente come ti aspetti. + +## Passo 3: Scrivi l'Immagine su File – Persistenza del PNG Renderizzato + +Ora che il documento è pronto e le opzioni di rendering sono impostate, puoi finalmente **scrivere l'immagine su file**. L'uso di un `FileStream` garantisce che il file venga creato in modo sicuro, anche se la cartella non esiste ancora. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +Dopo l'esecuzione di questo blocco, troverai `page.png` nella posizione specificata. Hai appena **renderizzato la pagina web in PNG** e l'hai salvata su disco in un'unica operazione semplice. + +### Risultato Atteso + +Apri `C:\Temp\page.png` con qualsiasi visualizzatore di immagini. Dovresti vedere un'istantanea fedele di `https://example.com`, renderizzata a 1024 × 768 pixel con bordi lisci grazie all'antialiasing. Se la pagina contiene contenuti dinamici (ad esempio elementi generati da JavaScript), saranno catturati purché il DOM sia completamente caricato prima del rendering. + +## Passo 4: Gestione dei Casi Limite – Font, Autenticazione e Pagine Grandi + +Mentre il flusso di base funziona per la maggior parte dei siti pubblici, gli scenari reali spesso presentano imprevisti: + +| Situazione | Cosa Fare | +|------------|-----------| +| **Font personalizzati non vengono caricati** | Incorpora i file dei font localmente e imposta `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Pagine protette da autenticazione** | Usa la sovraccarico di `HTMLDocument` che accetta `HttpWebRequest` con cookie o token. | +| **Pagine molto lunghe** | Aumenta `Height` o abilita `PageScaling` in `ImageRenderingOptions` per evitare il troncamento. | +| **Picchi di utilizzo della memoria** | Renderizza a blocchi usando la sovraccarico di `RenderToImage` che accetta una regione `Rectangle`. | + +Affrontare queste sfumature del *scrivere l'immagine su file* garantisce che la tua pipeline di `convert html to image` rimanga solida in produzione. + +## Passo 5: Esempio Completo Funzionante – Pronto per Copia‑Incolla + +Di seguito trovi l'intero programma, pronto per la compilazione. Include tutti i passaggi, la gestione degli errori e i commenti necessari. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Esegui questo programma e vedrai il messaggio di conferma nella console. Il file PNG sarà esattamente ciò che ti aspetteresti quando **renderizzi una pagina web in PNG** manualmente in un browser e fai uno screenshot—solo più veloce e completamente automatizzato. + +## Domande Frequenti + +**D: Posso convertire un file HTML locale invece di un URL?** +Assolutamente. Basta sostituire l'URL con un percorso file: `new HTMLDocument(@"C:\myPage.html")`. + +**D: È necessaria una licenza per Aspose.HTML?** +Una licenza di valutazione gratuita funziona per sviluppo e test. Per la produzione, acquista una licenza per rimuovere il watermark di valutazione. + +**D: Cosa succede se la pagina utilizza JavaScript per caricare contenuti dopo il caricamento iniziale?** +Aspose.HTML esegue JavaScript in modo sincrono durante il parsing, ma script di lunga durata potrebbero richiedere un ritardo manuale. Puoi usare `HTMLDocument.WaitForReadyState` prima del rendering. + +## Conclusione + +Ora disponi di una soluzione solida, end‑to‑end, per **convertire HTML in immagine** in C#. Seguendo i passaggi sopra potrai **salvare HTML come PNG**, impostare con precisione il **rendering delle dimensioni dell'immagine**, e scrivere con fiducia **l'immagine su file** su qualsiasi ambiente Windows o Linux. + +Dalle semplici schermate alla generazione automatizzata di report, questa tecnica scala bene. Successivamente, prova a sperimentare altri formati di output come JPEG o BMP, o integra il codice in un'API ASP.NET Core che restituisce direttamente il PNG agli chiamanti. Le possibilità sono praticamente infinite. + +Buona programmazione, e che le tue immagini renderizzate siano sempre pixel‑perfect! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/italian/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..1952ddc72 --- /dev/null +++ b/html/italian/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-03-21 +description: Crea PDF da HTML rapidamente usando Aspose HTML. Impara a rendere HTML + in PDF, convertire HTML in PDF e come utilizzare Aspose in un tutorial conciso. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: it +og_description: Crea PDF da HTML con Aspose in C#. Questa guida mostra come renderizzare + HTML in PDF, convertire HTML in PDF e come utilizzare Aspose in modo efficace. +og_title: Crea PDF da HTML – Tutorial completo Aspose C# +tags: +- Aspose +- C# +- PDF generation +title: Crea PDF da HTML con Aspose – Guida passo‑passo C# +url: /it/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea PDF da HTML con Aspose – Guida passo‑passo C# + +Hai mai avuto bisogno di **creare PDF da HTML** ma non eri sicuro quale libreria ti avrebbe fornito risultati pixel‑perfect? Non sei solo. Molti sviluppatori inciampano quando provano a trasformare un frammento web in un documento stampabile, per finire con testo sfocato o layout rotti. + +La buona notizia è che Aspose HTML rende l'intero processo indolore. In questo tutorial ti guideremo attraverso il codice esatto di cui hai bisogno per **renderizzare HTML in PDF**, esploreremo perché ogni impostazione è importante e ti mostreremo come **convertire HTML in PDF** senza trucchi nascosti. Alla fine saprai **come usare Aspose** per una generazione affidabile di PDF in qualsiasi progetto .NET. + +## Prerequisiti – Cosa ti serve prima di iniziare + +- **.NET 6.0 o successivo** (l'esempio funziona anche su .NET Framework 4.7+) +- **Visual Studio 2022** o qualsiasi IDE che supporti C# +- **Aspose.HTML for .NET** pacchetto NuGet (versione di prova gratuita o licenziata) +- Una comprensione di base della sintassi C# (non è necessario conoscere a fondo i PDF) + +Se li hai, sei pronto a partire. Altrimenti, scarica l'ultimo .NET SDK e installa il pacchetto NuGet con: + +```bash +dotnet add package Aspose.HTML +``` + +Quella singola riga importa tutto il necessario per la conversione **aspose html to pdf**. + +## Passo 1: Configura il tuo progetto per creare PDF da HTML + +La prima cosa da fare è creare una nuova applicazione console (o integrare il codice in un servizio esistente). Ecco uno scheletro minimale di `Program.cs`: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Suggerimento:** Se vedi `Aspise.Html.Rendering.Text` nei campioni più vecchi, sostituiscilo con `Aspose.Html.Rendering.Text`. L'errore di battitura causerà un errore di compilazione. + +Avere i namespace corretti garantisce che il compilatore possa trovare la classe **TextOptions** di cui avremo bisogno più tardi. + +## Passo 2: Costruisci il documento HTML (Renderizza HTML in PDF) + +Ora creiamo l'HTML di origine. Aspose ti permette di passare una stringa grezza, un percorso file o anche un URL. Per questa demo lo manterremo semplice: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Perché passare una stringa? Evita I/O del filesystem, accelera la conversione e garantisce che l'HTML che vedi nel codice sia esattamente quello che viene renderizzato. Se preferisci caricare da un file, basta sostituire l'argomento del costruttore con un URI del file. + +## Passo 3: Ottimizza il rendering del testo (Converti HTML in PDF con migliore qualità) + +Il rendering del testo spesso determina se il tuo PDF appare nitido o sfocato. Aspose offre una classe `TextOptions` che ti permette di abilitare il sub‑pixel hinting—essenziale per output ad alta DPI. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Abilitare `UseHinting` è particolarmente utile quando l'HTML di origine contiene font personalizzati o dimensioni di carattere piccole. Senza di esso, potresti notare bordi frastagliati nel PDF finale. + +## Passo 4: Associa le opzioni di testo alla configurazione del rendering PDF (Come usare Aspose) + +Successivamente, colleghiamo quelle opzioni di testo al renderer PDF. È qui che **aspose html to pdf** brilla davvero—tutto, dalla dimensione della pagina alla compressione, può essere regolato. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Puoi omettere `PageSetup` se va bene la dimensione A4 predefinita. Il punto chiave è che l'oggetto `TextOptions` vive all'interno di `PdfRenderingOptions`, ed è così che indichi ad Aspose *come* renderizzare il testo. + +## Passo 5: Renderizza l'HTML e salva il PDF (Converti HTML in PDF) + +Infine, trasmettiamo l'output in un file. L'uso di un blocco `using` garantisce che il handle del file venga chiuso correttamente, anche in caso di eccezione. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Quando esegui il programma, troverai `output.pdf` accanto all'eseguibile. Aprilo e dovresti vedere un'intestazione e un paragrafo puliti—esattamente come definiti nella stringa HTML. + +### Output previsto + +![crea pdf da html esempio output](https://example.com/images/pdf-output.png "crea pdf da html esempio output") + +*Lo screenshot mostra il PDF generato con l'intestazione “Hello, Aspose!” renderizzata nitidamente grazie al text hinting.* + +## Domande comuni e casi particolari + +### 1. E se il mio HTML fa riferimento a risorse esterne (immagini, CSS)? + +Aspose risolve gli URL relativi in base all'URI di base del documento. Se stai fornendo una stringa grezza, imposta manualmente l'URI di base: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Ora qualsiasi `` verrà cercato relativo a `C:/MyProject/`. + +### 2. Come incorporare font che non sono installati sul server? + +Aggiungi un blocco ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Passo 4: Configura le opzioni di salvataggio per usare l'archiviazione personalizzata + +`HtmlSaveOptions` ci permette di dire ad Aspose di impacchettare tutto in un file ZIP. La proprietà `OutputStorage` (legacy) riceve la nostra istanza `MyStorage`. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Nota:** In Aspose HTML 23.9+ la proprietà si chiama `OutputStorage` ma è contrassegnata come obsoleta. L'alternativa moderna è `ZipOutputStorage`. Il codice qui sotto funziona con entrambe perché l'interfaccia è la stessa. + +### Passo 5: Salva il documento come archivio ZIP + +Scegli una cartella di destinazione (o uno stream) e lascia che Aspose faccia il lavoro pesante. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Al termine del programma troverai `output.zip` contenente: + +* `index.html` – il documento principale. +* Eventuali immagini incorporate, file CSS o script (se il tuo HTML li fa riferimento). + +Puoi aprire lo ZIP con qualsiasi gestore di archivi per verificare la struttura. + +--- + +## Verifica del risultato (opzionale) + +Se vuoi ispezionare programmaticamente l'archivio senza estrarlo su disco: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Output tipico: + +``` +- index.html (452 bytes) +``` + +Se avessi immagini o CSS, apparirebbero come voci aggiuntive. Questo rapido controllo conferma che **create html zip archive** ha funzionato come previsto. + +--- + +## Domande comuni e casi particolari + +| Domanda | Risposta | +|----------|--------| +| **E se devo scrivere lo ZIP direttamente su uno stream di risposta?** | Restituisci il `MemoryStream` ottenuto da `MyStorage` dopo `document.Save`. Converti in `byte[]` e scrivilo su `HttpResponse.Body`. | +| **Il mio HTML fa riferimento a URL esterni—verranno scaricati?** | No. Aspose impacchetta solo le risorse che sono *incorporate* (ad es., `` o file locali). Per le risorse remote devi prima scaricarle e modificare il markup. | +| **La proprietà `OutputStorage` è contrassegnata come obsoleta—devo ignorarla?** | Funziona ancora, ma la più recente `ZipOutputStorage` offre la stessa API con un nome diverso. Sostituisci `OutputStorage` con `ZipOutputStorage` se vuoi una compilazione senza avvisi. | +| **Posso criptare lo ZIP?** | Sì. Dopo il salvataggio, apri il file con `System.IO.Compression.ZipArchive` e imposta una password usando librerie di terze parti come `SharpZipLib`. Aspose di per sé non fornisce la crittografia. | + +--- + +## Esempio completo funzionante (copia‑incolla) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Esegui il programma, apri `output.zip` e vedrai un unico file `index.html` che visualizza il titolo “Hello from ZIP!” quando aperto in un browser. + +--- + +## Conclusione + +Ora sai **come salvare HTML come ZIP** in C# usando una classe di **archiviazione personalizzata**, come **esportare HTML in ZIP** e come **creare un archivio ZIP HTML** pronto per la distribuzione. Il modello è flessibile—sostituisci `MemoryStream` con uno stream cloud, aggiungi la crittografia o integralo in un'API web che restituisce lo ZIP su richiesta. Il cielo è il limite quando combini le capacità ZIP di Aspose.HTML con la tua logica di archiviazione. + +Pronto per il passo successivo? Prova a fornire una pagina web completa con immagini e stili, o collega l'archiviazione a Azure Blob Storage per bypassare completamente il file system locale. Il cielo è il limite quando combini le capacità ZIP di Aspose.HTML con la tua logica di archiviazione. + +Buon coding, e che i tuoi archivi siano sempre ordinati! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/japanese/net/generate-jpg-and-png-images/_index.md b/html/japanese/net/generate-jpg-and-png-images/_index.md index 57de57175..3d9e0bc03 100644 --- a/html/japanese/net/generate-jpg-and-png-images/_index.md +++ b/html/japanese/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET を使用して HTML ドキュメントを操作したり DOCX 文書を PNG または JPG 画像に変換する際に、アンチエイリアシングを有効にして高品質な出力を得る手順を解説します。 ### [DOCX を PNG に変換 – ZIP アーカイブを作成する C# チュートリアル](./convert-docx-to-png-create-zip-archive-c-tutorial/) C# で DOCX を PNG に変換し、ZIP アーカイブを作成する方法を学びます。 +### [HTML を PNG に変換 – ZIP エクスポート付き完全 C# ガイド](./convert-html-to-png-full-c-guide-with-zip-export/) +HTML を PNG に変換し、生成された画像を ZIP ファイルとしてエクスポートする手順を詳しく解説します。 ## 結論 diff --git a/html/japanese/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/japanese/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..1c10b7336 --- /dev/null +++ b/html/japanese/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-03-21 +description: HTML を PNG に変換し、HTML を画像としてレンダリングしながら ZIP に保存します。数ステップでフォントスタイルを HTML + に適用し、p 要素に太字を追加する方法を学びましょう。 +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: ja +og_description: HTML をすばやく PNG に変換します。このガイドでは、HTML を画像としてレンダリングする方法、HTML を ZIP に保存する方法、HTML + にフォントスタイルを適用する方法、そして p 要素に太字を追加する方法を示します。 +og_title: HTMLをPNGに変換 – 完全なC#チュートリアル +tags: +- Aspose +- C# +title: HTML を PNG に変換 – ZIP エクスポート付きの完全 C# ガイド +url: /ja/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML を PNG に変換 – ZIP エクスポート付き 完全 C# ガイド + +HTML を PNG に **変換**したいが、ヘッドレスブラウザを導入せずに実現できるライブラリが分からない、ということはありませんか?メールのサムネイルやドキュメントのプレビュー、クイックビュー画像など、ウェブページを静的な画像に変換する必要は実務で頻繁に出てきます。 + +朗報です!Aspose.HTML を使えば **HTML を画像としてレンダリング**でき、マークアップをその場で調整し、さらに **HTML を ZIP に保存**して後から配布することも可能です。このチュートリアルでは、**フォントスタイル HTML を適用**し、具体的には **p 要素に太字を追加**したうえで PNG ファイルを生成する、完全に実行可能なサンプルをステップバイステップで解説します。最後まで読めば、ページの読み込みからリソースのアーカイブまでをすべて行う単一の C# クラスが手に入ります。 + +## 必要な環境 + +- .NET 6.0 以上(API は .NET Core でも動作) +- Aspose.HTML for .NET 6+(NuGet パッケージ `Aspose.Html`) +- C# の基本構文が分かっていれば OK(高度な概念は不要) + +以上だけです。外部ブラウザや phantomjs は不要で、純粋にマネージドコードだけで完結します。 + +## Step 1 – HTML ドキュメントの読み込み + +まず、ソースファイル(または URL)を `HTMLDocument` オブジェクトに取り込みます。このステップが **render html as image** と **save html to zip** の土台となります。 + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*ポイント:* `HTMLDocument` クラスはマークアップを解析し DOM を構築、CSS・画像・フォントといった外部リソースを解決します。ドキュメントオブジェクトがなければ、スタイルの操作やレンダリングはできません。 + +## Step 2 – フォントスタイル HTML の適用(p に太字を追加) + +次に、すべての `

` 要素を走査し `font-weight` を bold に設定することで **font style HTML** を適用します。これにより、元のファイルを変更せずに **add bold to p** タグをプログラム上で実現できます。 + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*プロのコツ:* 特定のサブセットだけを太字にしたい場合は、セレクタを `"p.intro"` のようにより具体的に変更してください。 + +## Step 3 – HTML を画像としてレンダリング(HTML を PNG に変換) + +DOM が整ったら `ImageRenderingOptions` を設定し、`RenderToImage` を呼び出します。ここで **convert html to png** の魔法が実行されます。 + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*オプションの重要性:* 固定の幅・高さを指定すると出力が大きくなりすぎるのを防げますし、アンチエイリアスを有効にすると滑らかなビジュアルになります。ファイルサイズを抑えたい場合は `options.ImageFormat = ImageFormat.Jpeg` に切り替えることも可能です。 + +## Step 4 – HTML を ZIP に保存(リソースをバンドル) + +元の HTML とその CSS、画像、フォントを一緒に配布したいケースが多くあります。Aspose.HTML の `ZipArchiveSaveOptions` がまさにそれを実現します。さらにカスタム `ResourceHandler` を組み込んで、外部アセットをアーカイブと同じフォルダーに書き出します。 + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*エッジケース:* HTML が認証が必要なリモート画像を参照している場合、デフォルトハンドラは失敗します。その際は `MyResourceHandler` を拡張して HTTP ヘッダーを注入してください。 + +## Step 5 – すべてを単一のコンバータークラスにまとめる + +以下は、これまでの手順をすべて統合した、すぐに実行可能なクラスです。コンソールアプリに貼り付けて `Convert` を呼び出すだけで、ファイルが生成されます。 + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### 期待される出力 + +上記スニペットを実行すると、`outputDirectory` に次の 2 つのファイルが作成されます。 + +| ファイル | 説明 | +|------|-------------| +| `page.png` | ソース HTML を 1200 × 800 の PNG にレンダリングしたもの。すべての段落が **bold** で表示されます。 | +| `archive.zip` | 元の `input.html` とその CSS、画像、Web フォントをすべて含む ZIP バンドル。オフライン配布に最適です。 | + +`page.png` は任意の画像ビューアで開き、太字スタイルが適用されていることを確認できます。`archive.zip` を展開すれば、未加工の HTML とそのリソースがそのまま確認できます。 + +## よくある質問と落とし穴 + +- **HTML に JavaScript が含まれている場合は?** + Aspose.HTML はレンダリング時にスクリプトを実行しません。そのため動的コンテンツは表示されません。完全にレンダリングされたページが必要な場合はヘッドレスブラウザが必要ですが、静的テンプレートではこの手法の方が高速かつ軽量です。 + +- **出力形式を JPEG や BMP に変更できますか?** + はい。`ImageRenderingOptions` の `ImageFormat` プロパティを `ImageFormat.Jpeg` などに変更すれば OK です。 + +- **`HTMLDocument` は手動で破棄する必要がありますか?** + クラスは `IDisposable` を実装しています。長時間動作するサービスでは `using` ブロックで囲むか、使用後に `document.Dispose()` を呼び出してください。 + +- **カスタム `MyResourceHandler` の仕組みは?** + 外部リソース(CSS、画像、フォント)を取得するたびに呼び出され、指定したフォルダーに書き出します。これにより ZIP に HTML が参照するすべてのファイルが正確に含まれます。 + +## 結論 + +これで **convert html to png**、**render html as image**、**save html to zip**、**apply font style html**、そして **add bold to p** を数行の C# で実現できる、コンパクトで本番環境向けのソリューションが完成しました。コードは自己完結型で .NET 6+ に対応し、ウェブコンテンツのスナップショットを迅速に取得したいバックエンドサービスに簡単に組み込めます。 + +次のステップに進みませんか?レンダリングサイズを変更したり、`font-family` や `color` といった他の CSS プロパティを試したり、ASP.NET Core のエンドポイントに組み込んでオンデマンドで PNG を返す実装に挑戦してみてください。可能性は無限大です。Aspose.HTML を使えば、重たいブラウザ依存から解放されます。 + +問題が発生したり、拡張アイデアがあれば下のコメント欄にぜひ書き込んでください。ハッピーコーディング! + +![HTML を PNG に変換した例](example.png "HTML を PNG に変換した例") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/japanese/net/html-document-manipulation/_index.md b/html/japanese/net/html-document-manipulation/_index.md index 38a8521fa..7d996f501 100644 --- a/html/japanese/net/html-document-manipulation/_index.md +++ b/html/japanese/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aspose.HTML for .NET の使い方を学びます。この包括的なガイド Aspose.HTML for .NET で Web 開発の可能性を最大限に引き出します。HTML ドキュメントを簡単に作成、変換、操作できます。 ### [C# の文字列から HTML を作成 – カスタム リソース ハンドラ ガイド](./create-html-from-string-in-c-custom-resource-handler-guide/) C# の文字列から HTML を生成し、カスタム リソース ハンドラで処理する方法をステップバイステップで解説します。 +### [C# で HTML ドキュメントを作成 – ステップバイステップ ガイド](./create-html-document-c-step-by-step-guide/) +C# を使用して HTML ドキュメントを作成し、カスタム リソース ハンドラを活用する手順を詳しく紹介します。 ## 結論 diff --git a/html/japanese/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/japanese/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..09a95181e --- /dev/null +++ b/html/japanese/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,186 @@ +--- +category: general +date: 2026-03-21 +description: C#でHTMLドキュメントを作成し、idで要素を取得・検索する方法、HTML要素のスタイルを変更する方法、そしてAspose.Htmlを使用して太字と斜体を追加する方法を学びます。 +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: ja +og_description: C#でHTMLドキュメントを作成し、要素をIDで取得、IDで要素を検索、HTML要素のスタイルを変更、太字と斜体を追加する方法を、明確なコード例とともにすぐに学べます。 +og_title: HTMLドキュメント作成 C# – 完全プログラミングガイド +tags: +- Aspose.Html +- C# +- DOM manipulation +title: C#でHTMLドキュメントを作成 – ステップバイステップガイド +url: /ja/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML ドキュメント C# の作成 – ステップバイステップ ガイド + +最初から **HTML ドキュメント C#** を作成し、単一の段落の見た目を調整したことがありますか? あなただけではありません。多くのウェブ自動化プロジェクトでは、HTML ファイルを作成し、ID でタグを検索し、ブラウザに触れずにスタイリング(たいていは太字 + 斜体)を適用します。 + +このチュートリアルでは、まさにそれを順を追って解説します。C# で HTML ドキュメントを作成し、**get element by id**、**locate element by id**、**change HTML element style** を行い、最後に Aspose.Html ライブラリを使用して **add bold italic** します。最後までに、任意の .NET プロジェクトに組み込める完全に実行可能なコードスニペットが手に入ります。 + +## 必要なもの + +- .NET 6 以降(コードは .NET Framework 4.7+ でも動作します) +- Visual Studio 2022(またはお好みのエディタ) +- **Aspose.Html** NuGet パッケージ (`Install-Package Aspose.Html`) + +以上です—余分な HTML ファイルやウェブサーバーは不要で、C# の数行だけです。 + +## HTML ドキュメント C# の作成 – ドキュメントの初期化 + +まず最初に、Aspose.Html エンジンが操作できるライブな `HTMLDocument` オブジェクトが必要です。これは、マークアップを書くための新しいノートブックを開くことと同じです。 + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Why this matters:** 生の文字列を `HTMLDocument` に渡すことで、ファイル I/O を扱わずにすべてメモリ上に保持できます—ユニットテストやオンザフライ生成に最適です。 + +## ID で要素を取得 – 段落の検索 + +ドキュメントが存在するので、**get element by id** が必要です。DOM API の `GetElementById` は、ID が存在しない場合 `null`、それ以外は `IElement` 参照を返します。 + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Pro tip:** マークアップは小さくても、null チェックを追加することで、同じロジックを大規模かつ動的なページで再利用した際のトラブルを防げます。 + +## ID で要素を検索 – 代替アプローチ + +場合によっては、ドキュメントのルートへの参照がすでにあり、クエリ形式の検索を好むことがあります。CSS セレクタ(`QuerySelector`)を使用することも **locate element by id** の別の方法です: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **When to use which?** `GetElementById` は直接ハッシュ検索のため若干高速です。`QuerySelector` は複雑なセレクタ(例:`div > p.highlight`)が必要なときに有効です。 + +## HTML 要素のスタイル変更 – 太字斜体の追加 + +要素を取得したら、次のステップは **change HTML element style** です。Aspose.Html は `Style` オブジェクトを提供し、CSS プロパティを調整したり、便利な `WebFontStyle` 列挙体を使って複数のフォント属性を一度に適用できます。 + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +この1行で要素の `font-weight` が `bold`、`font-style` が `italic` に設定されます。内部では Aspose.Html が列挙体を適切な CSS 文字列に変換します。 + +### 完全な動作例 + +すべての部品を組み合わせると、コンパイルしてすぐに実行できるコンパクトな自己完結型プログラムが得られます: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**期待される出力** + +``` +Rendered HTML: +

Hello world

+``` + +`

` タグにはインラインの `style` 属性が付与され、テキストが太字かつ斜体になっています—まさに求めていた通りです。 + +## エッジケースと一般的な落とし穴 + +| 状況 | 注意点 | 対処方法 | +|-----------|-------------------|---------------| +| **ID が存在しない** | `GetElementById` は `null` を返します。 | 例外をスローするか、デフォルト要素にフォールバックします。 | +| **複数の要素が同じ ID を共有** | HTML 仕様では ID は一意であるべきですが、実際のページではルールが破られることがあります。 | `GetElementById` は最初に一致した要素を返します;重複を処理する必要がある場合は `QuerySelectorAll` の使用を検討してください。 | +| **スタイルの競合** | 既存のインラインスタイルが上書きされる可能性があります。 | `style` 全体の文字列を設定するのではなく、`Style` オブジェクトに追加します:`paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **ブラウザでのレンダリング** | 要素により高い特異性を持つ CSS クラスが既にある場合、いくつかのブラウザは `WebFontStyle` を無視します。 | 必要に応じて `paragraph.Style.SetProperty("font-weight", "bold", "important");` のように `!important` を使用します。 | + +## 実務プロジェクト向けのプロティップス + +- **Cache the document**:多数の要素を処理する場合はドキュメントをキャッシュしてください。各スニペットごとに新しい `HTMLDocument` を作成するとパフォーマンスが低下します。 +- **Combine style changes**:単一の `Style` トランザクションでスタイル変更をまとめ、複数の DOM リフローを防ぎます。 +- **Leverage Aspose.Html’s rendering engine**:最終ドキュメントを PDF や画像としてエクスポートできます—レポートツールに最適です。 + +## ビジュアル確認(オプション) + +結果をブラウザで確認したい場合は、レンダリングされた文字列を `.html` ファイルに保存できます: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +`output.html` を開くと、**Hello world** が太字 + 斜体で表示されます。 + +![Create HTML Document C# の例(太字斜体段落を表示)](/images/create-html-document-csharp.png "Create HTML Document C# – レンダリング結果") + +*Alt text: Create HTML Document C# – 太字斜体テキストが含まれるレンダリング結果.* + +## 結論 + +私たちは **HTML ドキュメント C# を作成**、**get element by id**、**locate element by id**、**change HTML element style**、そして最終的に **add bold italic** を行いました—すべて Aspose.Html を使用した数行のコードで実現しました。この手法はシンプルで、任意の .NET 環境で動作し、より大規模な DOM 操作にもスケールします。 + +次のステップに進む準備はできましたか? `WebFontStyle` を `Underline` などの他の列挙体に置き換えたり、複数のスタイルを手動で組み合わせてみてください。また、外部 HTML ファイルを読み込み、同じ手法を数百の要素に適用する実験もできます。可能性は無限で、これでしっかりとした基盤ができました。 + +コーディングを楽しんで! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/japanese/net/html-extensions-and-conversions/_index.md b/html/japanese/net/html-extensions-and-conversions/_index.md index 4110fd8e8..f91a77bd2 100644 --- a/html/japanese/net/html-extensions-and-conversions/_index.md +++ b/html/japanese/net/html-extensions-and-conversions/_index.md @@ -43,6 +43,9 @@ Aspose.HTML for .NET を使用すると、HTML を PDF に簡単に変換でき ### [HTML から PDF を作成する – C# ステップバイステップ ガイド](./create-pdf-from-html-c-step-by-step-guide/) Aspose.HTML for .NET を使用して、C# で HTML から PDF を作成する手順をステップバイステップで解説します。 +### [Aspose を使用して HTML から PDF を作成する – ステップバイステップ C# ガイド](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Aspose.HTML for .NET を使用し、C# で HTML から PDF を作成する手順を詳細に解説します。 + ### [スタイル付きテキストで HTML ドキュメントを作成し、PDF にエクスポートする – 完全ガイド](./create-html-document-with-styled-text-and-export-to-pdf-full/) Aspose.HTML for .NET を使用して、スタイル付きテキストを含む HTML ドキュメントを作成し、PDF にエクスポートする手順を詳しく解説します。 @@ -66,6 +69,10 @@ Aspose.HTML for .NET を使用して、.NET で HTML を JPEG に変換する方 Aspose.HTML を使用して .NET で HTML を MHTML に変換する - 効率的な Web コンテンツのアーカイブ化のためのステップバイステップ ガイド。Aspose.HTML for .NET を使用して MHTML アーカイブを作成する方法を学習します。 ### [Aspose.HTML を使用して .NET で HTML を PNG に変換する](./convert-html-to-png/) Aspose.HTML for .NET を使用して HTML ドキュメントを操作および変換する方法を学びます。効果的な .NET 開発のためのステップバイステップ ガイドです。 + +### [C# で HTML を画像に変換する – 完全ガイド](./convert-html-to-image-in-c-complete-guide/) +Aspose.HTML for .NET を使用して、C# で HTML を画像に変換する方法をステップバイステップで解説します。 + ### [Aspose.HTML を使用して .NET で HTML を TIFF に変換する](./convert-html-to-tiff/) Aspose.HTML for .NET を使用して HTML を TIFF に変換する方法を学びます。効率的な Web コンテンツの最適化については、当社のステップバイステップ ガイドに従ってください。 ### [Aspose.HTML を使用して .NET で HTML を XPS に変換する](./convert-html-to-xps/) @@ -75,9 +82,16 @@ 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 アーカイブに保存する手順をステップバイステップで解説します。 +### [C# で HTML を ZIP として保存 – カスタムストレージを使用した完全ガイド](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Aspose.HTML for .NET を使用し、カスタムストレージに HTML を ZIP アーカイブとして保存する完全な手順を解説します。 + +### [Aspose.HTML を使用して HTML を Zip に圧縮する – 完全ガイド](./how-to-zip-html-with-aspose-html-complete-guide/) +Aspose.HTML を活用し、HTML コンテンツを Zip アーカイブにまとめる手順を完全に解説します。 + ## 結論 結論として、HTML の拡張と変換は、現代の Web 開発に不可欠な要素です。Aspose.HTML for .NET はプロセスを簡素化し、あらゆるレベルの開発者が利用できるようにします。当社のチュートリアルに従うことで、幅広いスキルを備えた熟練した Web 開発者になるための道を順調に進むことができます。 diff --git a/html/japanese/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/japanese/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..50bde1792 --- /dev/null +++ b/html/japanese/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,186 @@ +--- +category: general +date: 2026-03-21 +description: C# で Aspose.HTML を使用して HTML を画像に変換します。HTML を PNG として保存し、画像サイズのレンダリングを設定し、数ステップで画像をファイルに書き込む方法を学びましょう。 +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: ja +og_description: HTML をすばやく画像に変換します。このガイドでは、HTML を PNG として保存し、画像サイズのレンダリングを設定し、Aspose.HTML + を使用して画像をファイルに書き込む方法を示します。 +og_title: C#でHTMLを画像に変換する – ステップバイステップガイド +tags: +- Aspose.HTML +- C# +- Image Rendering +title: C#でHTMLを画像に変換する – 完全ガイド +url: /ja/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で HTML を画像に変換する – 完全ガイド + +ダッシュボードのサムネイルやメールプレビュー、PDF レポート用に **HTML を画像に変換** したことがありますか? 動的な Web コンテンツを別の場所に埋め込む必要があるときに、思いがけず頻繁に出てくるシナリオです。 + +良いニュースは、Aspose.HTML を使えば **HTML を画像に変換** できるコードが数行で済み、*HTML を PNG として保存*、出力サイズの制御、*画像をファイルに書き込む* 方法も簡単に学べます。 + +このチュートリアルでは、リモートページの読み込みからレンダリングサイズの調整、最終的に PNG ファイルとしてディスクに保存するまでのすべての手順を解説します。外部ツールや面倒なコマンドライン操作は不要です。純粋な C# コードだけで、任意の .NET プロジェクトに組み込めます。 + +## 学べること + +- Aspose.HTML の `HTMLDocument` クラスを使って **ウェブページを PNG にレンダリング** する方法。 +- **画像サイズのレンダリング** を設定し、出力がレイアウト要件に合うようにする正確な手順。 +- ストリームやファイルパスを扱いながら **画像をファイルに書き込む** 安全な方法。 +- フォントが欠落している、ネットワークタイムアウトが発生するなど、一般的な落とし穴のトラブルシューティングのコツ。 + +### 前提条件 + +- .NET 6.0 以上(API は .NET Framework でも動作しますが、.NET 6+ が推奨です)。 +- Aspose.HTML for .NET NuGet パッケージ(`Aspose.Html`)への参照。 +- C# と async/await の基本的な知識(任意ですがあると便利)。 + +これらが揃っていれば、すぐに HTML を画像に変換し始められます。 + +## Step 1: Web ページの読み込み – HTML を画像に変換する基礎 + +レンダリングを行う前に、対象ページを表す `HTMLDocument` インスタンスが必要です。 + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*重要ポイント:* `HTMLDocument` は HTML を解析し、CSS を解決し、DOM を構築します。ドキュメントが読み込めない(例: ネットワーク障害)と、後続のレンダリングは空白画像になってしまいます。URL が到達可能か必ず確認してから進めましょう。 + +## Step 2: 画像サイズのレンダリング設定 – 幅・高さ・品質の制御 + +Aspose.HTML の `ImageRenderingOptions` を使うと、出力サイズを細かく調整できます。ここで **画像サイズのレンダリング** を設定し、ターゲットレイアウトに合わせます。 + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*プロのコツ:* `Width` と `Height` を省略すると、Aspose.HTML はページの固有サイズを使用しますが、レスポンシブデザインでは予測が難しいことがあります。明示的にサイズを指定すれば、**HTML を PNG として保存** したときの出力が期待通りになります。 + +## Step 3: 画像をファイルに書き込む – レンダリングした PNG の永続化 + +ドキュメントとレンダリングオプションの準備ができたら、いよいよ **画像をファイルに書き込む** 時です。`FileStream` を使えば、フォルダーがまだ存在しなくても安全にファイルを作成できます。 + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +このブロックが実行されると、指定した場所に `page.png` が生成されます。これで **ウェブページを PNG にレンダリング** し、ディスクに書き込むというシンプルな操作が完了です。 + +### 期待される結果 + +任意の画像ビューアで `C:\Temp\page.png` を開いてください。`https://example.com` の忠実なスナップショットが、1024 × 768 ピクセルでアンチエイリアスにより滑らかなエッジで表示されます。ページに動的コンテンツ(例: JavaScript で生成された要素)がある場合でも、DOM が完全にロードされていればキャプチャされます。 + +## Step 4: エッジケースの処理 – フォント、認証、巨大ページ + +基本フローは多くの公開サイトで機能しますが、実務ではさまざまな障害が発生します。 + +| 状況 | 対応策 | +|-----------|------------| +| **カスタムフォントが読み込まれない** | フォントファイルをローカルに配置し、`htmlDoc.Fonts.Add("path/to/font.ttf")` で追加します。 | +| **認証が必要なページ** | クッキーやトークンを含む `HttpWebRequest` を受け取る `HTMLDocument` のオーバーロードを使用します。 | +| **非常に長いページ** | `Height` を増やすか、`ImageRenderingOptions` の `PageScaling` を有効にして切り捨てを防ぎます。 | +| **メモリ使用量が急増** | `RenderToImage` の `Rectangle` 領域を受け取るオーバーロードを使い、チャンク単位でレンダリングします。 | + +これらの *画像をファイルに書き込む* に関する細かな調整を行うことで、**HTML を画像に変換** パイプラインを本番環境でも安定させられます。 + +## Step 5: 完全動作サンプル – コピペで即実行 + +以下はコンパイル可能なフルプログラムです。すべての手順、エラーハンドリング、コメントが含まれています。 + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +プログラムを実行するとコンソールに確認メッセージが表示されます。生成された PNG は、ブラウザで **ウェブページを PNG にレンダリング** してスクリーンショットを撮ったときと同等の結果ですが、はるかに高速で自動化されています。 + +## よくある質問 + +**Q: URL ではなくローカルの HTML ファイルを変換したいです。** +A: 問題ありません。URL の代わりにファイルパスを指定します: `new HTMLDocument(@"C:\myPage.html")`。 + +**Q: Aspose.HTML のライセンスは必要ですか?** +A: 無料評価ライセンスで開発・テストは可能です。商用環境では評価ウォーターマークを除去するためにライセンスを購入してください。 + +**Q: ページが JavaScript でコンテンツを遅延ロードする場合は?** +A: Aspose.HTML はパース時に JavaScript を同期的に実行しますが、長時間実行されるスクリプトは手動で遅延させる必要があります。レンダリング前に `HTMLDocument.WaitForReadyState` を呼び出すと安全です。 + +## 結論 + +これで C# で **HTML を画像に変換** するためのエンドツーエンドソリューションが完成しました。上記手順に従えば **HTML を PNG として保存**、正確な **画像サイズのレンダリング**、そして確実な **画像をファイルに書き込む** が Windows でも Linux でも実行できます。 + +シンプルなスクリーンショットから自動レポート生成まで、この手法はスケーラブルです。次は JPEG や BMP といった他の出力形式に挑戦したり、ASP.NET Core API に組み込んで PNG を直接呼び出し元に返す実装に挑んでみてください。可能性は実質無限です。 + +Happy coding, and may your rendered images always look pixel‑perfect! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/japanese/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..8bcf4cc37 --- /dev/null +++ b/html/japanese/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-03-21 +description: Aspose HTML を使用して HTML から PDF を素早く作成します。HTML を PDF にレンダリングする方法、HTML を + PDF に変換する方法、そして Aspose の使い方を簡潔なチュートリアルで学びましょう。 +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: ja +og_description: C#でAsposeを使用してHTMLからPDFを作成します。このガイドでは、HTMLをPDFにレンダリングする方法、HTMLをPDFに変換する方法、そしてAsposeを効果的に活用する方法を示します。 +og_title: HTMLからPDFを作成 – 完全なAspose C#チュートリアル +tags: +- Aspose +- C# +- PDF generation +title: AsposeでHTMLからPDFを作成する – ステップバイステップ C# ガイド +url: /ja/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# AsposeでHTMLからPDFを作成 – ステップバイステップ C# ガイド + +HTMLから**PDFを作成**したことがありますか?しかし、どのライブラリがピクセル単位で完璧な結果を提供するか分からなかったことはありませんか?あなたは一人ではありません。多くの開発者がウェブのスニペットを印刷可能なドキュメントに変換しようとして、テキストがぼやけたりレイアウトが崩れたりしてしまいます。 + +良いニュースは、Aspose HTML がこのプロセスを全く手間なくしてくれることです。このチュートリアルでは、**HTMLをPDFにレンダリング**するために必要な正確なコードを順に解説し、各設定がなぜ重要なのかを探り、**HTMLをPDFに変換**する際の隠れたコツは一切ありません。最後まで読めば、任意の .NET プロジェクトで信頼性の高い PDF 生成のために**Asposeの使い方**が分かります。 + +## 前提条件 – 作業開始前に必要なもの + +- **.NET 6.0 以上**(例は .NET Framework 4.7+ でも動作します) +- **Visual Studio 2022** または C# をサポートする任意の IDE +- **Aspose.HTML for .NET** NuGet パッケージ(無料トライアルまたは正規版) +- C# の基本的な構文理解(PDF の深い知識は不要) + +これらが揃っていればすぐに始められます。まだの場合は、最新の .NET SDK を取得し、以下のコマンドで NuGet パッケージをインストールしてください。 + +```bash +dotnet add package Aspose.HTML +``` + +この一行で **aspose html to pdf** 変換に必要なすべてが取り込まれます。 + +--- + +## Step 1: HTMLからPDFを作成するためのプロジェクト設定 + +最初に行うことは、新しいコンソール アプリを作成すること(既存のサービスにコードを組み込んでも構いません)。以下は最小構成の `Program.cs` の雛形です。 + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** 古いサンプルで `Aspise.Html.Rendering.Text` が見える場合は、`Aspose.Html.Rendering.Text` に置き換えてください。タイプミスが原因でコンパイル エラーになります。 + +正しい名前空間を使用することで、後で必要になる **TextOptions** クラスをコンパイラが正しく認識できるようになります。 + +## Step 2: HTML ドキュメントの構築(Render HTML to PDF) + +次にソース HTML を作成します。Aspose は生文字列、ファイルパス、あるいは URL のいずれでも受け取れます。このデモではシンプルに文字列で渡します。 + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +文字列で渡す理由は、ファイルシステム I/O を回避し、変換速度を上げ、コード中に記述した HTML がそのままレンダリングされることを保証できるからです。ファイルから読み込みたい場合は、コンストラクタの引数をファイル URI に置き換えるだけです。 + +## Step 3: テキストレンダリングの微調整(Convert HTML to PDF with Better Quality) + +テキストのレンダリングは、PDF が鮮明になるかぼやけるかを左右します。Aspose は `TextOptions` クラスを提供しており、サブピクセル ヒンティングを有効にできます。これは高 DPI 出力に必須です。 + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +`UseHinting` を有効にすると、ソース HTML にカスタムフォントや小さなフォントサイズが含まれている場合に特に有効です。これを無効にすると、最終的な PDF にギザギザが目立つことがあります。 + +## Step 4: テキストオプションを PDF レンダリング設定に結び付ける(How to Use Aspose) + +次に、先ほどのテキストオプションを PDF レンダラにバインドします。ここが **aspose html to pdf** の真価が発揮されるポイントで、ページサイズから圧縮設定まで自由に調整できます。 + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +デフォルトの A4 サイズで問題なければ `PageSetup` は省略可能です。重要なのは、`TextOptions` オブジェクトが `PdfRenderingOptions` の内部に存在し、これが Aspose にテキストのレンダリング方法を指示する仕組みだということです。 + +## Step 5: HTML をレンダリングして PDF を保存する(Convert HTML to PDF) + +最後に、出力をファイルにストリームします。`using` ブロックを使用すれば、例外が発生した場合でもファイルハンドルが確実に閉じられます。 + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +プログラムを実行すると、実行ファイルと同じディレクトリに `output.pdf` が生成されます。開いてみると、HTML 文字列で定義した見出しと段落がきれいに表示されているはずです。 + +### Expected Output + +![HTMLからPDF作成例の出力](https://example.com/images/pdf-output.png "HTMLからPDF作成例の出力") + +*このスクリーンショットは、テキスト ヒンティングのおかげで「Hello, Aspose!」という見出しが鮮明にレンダリングされた生成 PDF を示しています。* + +--- + +## よくある質問とエッジケース + +### 1. HTML が外部リソース(画像、CSS)を参照している場合は? + +Aspose はドキュメントのベース URI を基に相対 URL を解決します。文字列を直接渡す場合は、ベース URI を手動で設定してください。 + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +これで `` は `C:/MyProject/` を基準に検索されます。 + +### 2. サーバーにインストールされていないフォントを埋め込むには? + +ローカルまたはリモートのフォントファイルを指す `@font-face` を使用した ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### 手順 4: カスタムストレージを使用するように保存オプションを構成 + +`HtmlSaveOptions` を使用すると、Aspose にすべてを ZIP ファイルにパックさせることができます。`OutputStorage` プロパティ(レガシー)は `MyStorage` インスタンスを受け取ります。 + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Note:** Aspose HTML 23.9 以降ではプロパティ名は `OutputStorage` ですが、非推奨とされています。最新の代替は `ZipOutputStorage` です。以下のコードはインターフェイスが同じなので両方で動作します。 + +### 手順 5: ドキュメントを ZIP アーカイブとして保存 + +対象フォルダー(またはストリーム)を選択し、Aspose に処理を任せます。 + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +プログラムが終了すると、`output.zip` に以下が含まれます: + +- `index.html` – メインドキュメント。 +- 埋め込まれた画像、CSS ファイル、スクリプト(HTML が参照している場合)。 + +任意のアーカイブマネージャで ZIP を開き、構造を確認できます。 + +--- + +## 結果の検証(オプション) + +ディスクに展開せずにプログラムでアーカイブを検査したい場合は: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +典型的な出力: + +``` +- index.html (452 bytes) +``` + +画像や CSS があれば、追加エントリとして表示されます。この簡易チェックにより、**create html zip archive** が期待通りに動作したことが確認できます。 + +--- + +## よくある質問とエッジケース + +| Question | Answer | +|----------|--------| +| **ZIP を直接レスポンスストリームに書き込む必要がある場合はどうすればよいですか?** | `document.Save` 後に `MyStorage` から取得した `MemoryStream` を返します。`byte[]` にキャストして `HttpResponse.Body` に書き込みます。 | +| **HTML が外部 URL を参照している場合、ダウンロードされますか?** | いいえ。Aspose は *埋め込み* されたリソース(例: `` やローカルファイル)だけをパックします。リモート資産は事前にダウンロードし、マークアップを調整する必要があります。 | +| **`OutputStorage` プロパティが非推奨とマークされていますが、無視してよいですか?** | 依然として機能しますが、 newer `ZipOutputStorage` は同じ API を別名で提供しています。警告なしのビルドにしたい場合は `OutputStorage` を `ZipOutputStorage` に置き換えてください。 | +| **ZIP を暗号化できますか?** | はい。保存後に `System.IO.Compression.ZipArchive` でファイルを開き、`SharpZipLib` などのサードパーティライブラリを使用してパスワードを設定します。Aspose 自体は暗号化機能を提供していません。 | + +## 完全動作例(コピー&ペースト) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +プログラムを実行し、`output.zip` を開くと、ブラウザで開いたときに “Hello from ZIP!” の見出しが表示される単一の `index.html` ファイルが含まれていることが確認できます。 + +## 結論 + +これで、C# で **HTML を ZIP として保存** する方法、**custom storage** クラスを使用する方法、**HTML を ZIP にエクスポート** し、配布可能な **HTML zip archive** を作成する方法が分かりました。このパターンは柔軟で、`MemoryStream` をクラウドストリームに置き換えたり、暗号化を追加したり、要求に応じて ZIP を返す Web API に統合したりできます。Aspose.HTML の ZIP 機能と独自のストレージロジックを組み合わせれば、可能性は無限です。 + +次のステップに進む準備はできましたか?画像やスタイルを含む本格的なウェブページを入力してみたり、ストレージを Azure Blob Storage に接続してローカルファイルシステムを完全に回避したりしてみてください。Aspose.HTML の ZIP 機能と独自のストレージロジックを組み合わせれば、可能性は無限です。 + +コーディングを楽しんで、アーカイブが常に整然としていますように! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/korean/net/generate-jpg-and-png-images/_index.md b/html/korean/net/generate-jpg-and-png-images/_index.md index 2f2fd11d0..da02fe886 100644 --- a/html/korean/net/generate-jpg-and-png-images/_index.md +++ b/html/korean/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML for .NET을 .NET 프로젝트에 통합하는 것은 번거롭지 DOCX 문서를 PNG 또는 JPG 이미지로 변환할 때 안티앨리어싱을 적용하는 방법을 단계별로 안내합니다. ### [DOCX를 PNG로 변환하고 ZIP 아카이브 만들기 C# 튜토리얼](./convert-docx-to-png-create-zip-archive-c-tutorial/) C#을 사용해 DOCX 파일을 PNG 이미지로 변환하고, 결과를 ZIP 파일로 압축하는 방법을 단계별로 안내합니다. +### [HTML을 PNG로 변환 – ZIP 내보내기 포함 전체 C# 가이드](./convert-html-to-png-full-c-guide-with-zip-export/) +HTML을 PNG 이미지로 변환하고 ZIP 파일로 내보내는 전체 C# 단계별 가이드를 제공합니다. ## 결론 diff --git a/html/korean/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/korean/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..8033162cc --- /dev/null +++ b/html/korean/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-03-21 +description: HTML을 PNG로 변환하고 HTML을 이미지로 렌더링하면서 HTML을 ZIP으로 저장합니다. 몇 단계만으로 폰트 스타일을 + 적용하고 p 요소에 굵게(bold)를 추가하는 방법을 배워보세요. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: ko +og_description: HTML을 빠르게 PNG로 변환합니다. 이 가이드는 HTML을 이미지로 렌더링하는 방법, HTML을 ZIP으로 저장하는 + 방법, HTML에 폰트 스타일을 적용하는 방법 및 p 요소에 굵게 적용하는 방법을 보여줍니다. +og_title: HTML을 PNG로 변환 – 완전한 C# 튜토리얼 +tags: +- Aspose +- C# +title: HTML을 PNG로 변환 – ZIP 내보내기가 포함된 전체 C# 가이드 +url: /ko/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML을 PNG로 변환 – ZIP 내보내기 포함 전체 C# 가이드 + +**convert HTML to PNG**가 필요했지만 헤드리스 브라우저 없이 이를 수행할 수 있는 라이브러리를 몰라 고민한 적이 있나요? 당신만 그런 것이 아닙니다. 많은 프로젝트—이메일 썸네일, 문서 미리보기, 혹은 퀵‑룩 이미지—에서 웹 페이지를 정적인 그림으로 바꾸는 것은 실제적인 요구입니다. + +좋은 소식은? Aspose.HTML을 사용하면 **render HTML as image**를 수행하고, 마크업을 즉시 조정하며, 나중에 배포할 수 있도록 **save HTML to ZIP**도 할 수 있습니다. 이 튜토리얼에서는 PNG 파일을 생성하기 전에 **applies font style HTML**을 적용하고, 특히 **add bold to p** 요소에 굵게 적용하는 완전한 실행 가능한 예제를 단계별로 살펴봅니다. 최종적으로 페이지 로드부터 리소스 아카이브까지 모든 작업을 수행하는 단일 C# 클래스를 얻게 됩니다. + +## 필요한 사항 + +- .NET 6.0 이상 (API는 .NET Core에서도 작동합니다) +- Aspose.HTML for .NET 6+ (NuGet 패키지 `Aspose.Html`) +- C# 구문에 대한 기본 이해 (고급 개념은 필요 없음) + +그게 전부입니다. 외부 브라우저도, phantomjs도 필요 없으며 순수 관리 코드만 사용합니다. + +## 1단계 – HTML 문서 로드 + +먼저 소스 파일(또는 URL)을 `HTMLDocument` 객체에 로드합니다. 이 단계는 이후 **render html as image**와 **save html to zip** 모두의 기반이 됩니다. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*왜 중요한가:* `HTMLDocument` 클래스는 마크업을 파싱하고 DOM을 구축하며 연결된 리소스(CSS, 이미지, 폰트)를 해석합니다. 적절한 문서 객체가 없으면 스타일을 조작하거나 렌더링할 수 없습니다. + +## 2단계 – Font Style HTML 적용 (p에 굵게 적용) + +이제 모든 `

` 요소를 순회하면서 `font-weight`를 bold로 설정하여 **apply font style HTML**을 수행합니다. 이는 원본 파일을 수정하지 않고 **add bold to p** 태그를 적용하는 프로그래밍 방식입니다. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*팁:* 굵게 적용할 부분이 일부만 필요하면 선택자를 더 구체적으로 바꾸세요, 예: `"p.intro"`. + +## 3단계 – HTML을 이미지로 렌더링 (HTML을 PNG로 변환) + +DOM이 준비되면 `ImageRenderingOptions`를 설정하고 `RenderToImage`를 호출합니다. 여기서 **convert html to png** 마법이 실행됩니다. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*옵션이 중요한 이유:* 고정된 너비/높이를 설정하면 출력이 지나치게 커지는 것을 방지하고, 안티앨리어싱은 시각을 부드럽게 합니다. 파일 크기를 줄이고 싶다면 `options`를 `ImageFormat.Jpeg`으로 변경할 수도 있습니다. + +## 4단계 – HTML을 ZIP으로 저장 (리소스 번들링) + +종종 원본 HTML을 CSS, 이미지, 폰트와 함께 배포해야 할 때가 있습니다. Aspose.HTML의 `ZipArchiveSaveOptions`가 바로 이를 수행합니다. 또한 커스텀 `ResourceHandler`를 연결하여 모든 외부 자산을 아카이브와 동일한 폴더에 기록하도록 합니다. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*예외 상황:* HTML이 인증이 필요한 원격 이미지를 참조하면 기본 핸들러가 실패합니다. 이 경우 `MyResourceHandler`를 확장하여 HTTP 헤더를 삽입할 수 있습니다. + +## 5단계 – 모든 작업을 하나의 Converter 클래스에 연결 + +아래는 앞서 설명한 모든 단계를 하나로 연결한 완전한 실행 가능한 클래스입니다. 콘솔 앱에 복사‑붙여넣기하고 `Convert`를 호출하면 파일이 생성되는 것을 확인할 수 있습니다. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### 예상 출력 + +위 코드를 실행하면 `outputDirectory`에 두 개의 파일이 생성됩니다: + +| File | Description | +|------|-------------| +| `page.png` | 원본 HTML을 1200 × 800 PNG로 렌더링한 이미지이며, 모든 단락이 **bold**로 표시됩니다. | +| `archive.zip` | 원본 `input.html`과 그 CSS, 이미지, 웹 폰트를 포함한 ZIP 번들로, 오프라인 배포에 적합합니다. | + +`page.png`를 이미지 뷰어로 열어 굵은 스타일이 적용됐는지 확인하고, `archive.zip`을 추출하면 원본 HTML과 해당 자산들을 함께 볼 수 있습니다. + +## 자주 묻는 질문 및 주의사항 + +- **HTML에 JavaScript가 포함되어 있으면 어떻게 되나요?** + Aspose.HTML은 렌더링 중에 스크립트를 **실행하지 않**으므로 동적 콘텐츠가 표시되지 않습니다. 완전한 렌더링이 필요하면 헤드리스 브라우저가 필요하지만, 정적 템플릿에는 이 방법이 더 빠르고 가볍습니다. + +- **출력 형식을 JPEG 또는 BMP로 변경할 수 있나요?** + 예—`ImageRenderingOptions`의 `ImageFormat` 속성을 교체하면 됩니다, 예: `options.ImageFormat = ImageFormat.Jpeg;`. + +- **`HTMLDocument`를 수동으로 Dispose 해야 하나요?** + 이 클래스는 `IDisposable`을 구현합니다. 장기 실행 서비스에서는 `using` 블록으로 감싸거나 작업이 끝난 후 `document.Dispose()`를 호출하세요. + +- **커스텀 `MyResourceHandler`는 어떻게 동작하나요?** + 외부 리소스(CSS, 이미지, 폰트)를 각각 받아 지정한 폴더에 기록합니다. 이를 통해 ZIP에 HTML이 참조하는 모든 항목이 정확히 복사됩니다. + +## 결론 + +이제 **convert html to png**, **render html as image**, **save html to zip**, **apply font style html**, **add bold to p**를 모두 수행하는 간결하고 프로덕션 준비된 솔루션을 보유하게 되었습니다—몇 줄의 C# 코드만으로 가능합니다. 코드는 독립적이며 .NET 6+에서 동작하고, 웹 콘텐츠의 빠른 시각 스냅샷이 필요한 모든 백엔드 서비스에 적용할 수 있습니다. + +다음 단계가 준비되셨나요? 렌더링 크기를 바꾸어 보거나 다른 CSS 속성(`font-family` 또는 `color` 등)을 실험해 보세요. 혹은 이 컨버터를 ASP.NET Core 엔드포인트에 통합해 요청 시 PNG를 반환하도록 할 수도 있습니다. 가능성은 무궁무진하며, Aspose.HTML을 사용하면 무거운 브라우저 의존성을 피할 수 있습니다. + +문제가 발생했거나 확장 아이디어가 있다면 아래에 댓글을 남겨 주세요. 즐거운 코딩 되세요! + +![HTML을 PNG로 변환 예시](example.png "HTML을 PNG로 변환 예시") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/korean/net/html-document-manipulation/_index.md b/html/korean/net/html-document-manipulation/_index.md index dc4818e47..8408f014e 100644 --- a/html/korean/net/html-document-manipulation/_index.md +++ b/html/korean/net/html-document-manipulation/_index.md @@ -59,6 +59,8 @@ Aspose.HTML for .NET으로 SEO를 강화하는 방법을 알아보세요. 순위 .NET용 Aspose.HTML의 힘을 활용하는 방법을 알아보세요. HTML 조작 및 렌더링으로 웹 개발을 강화하세요. ### [Aspose.HTML을 사용하여 .NET에서 문서 만들기](./creating-a-document/) .NET용 Aspose.HTML의 힘을 최대한 활용하세요. HTML 및 SVG 문서를 쉽게 만들고, 조작하고, 최적화하는 방법을 배우세요. 단계별 예제와 FAQ를 살펴보세요. +### [C#를 사용하여 HTML 문서 만들기 – 단계별 가이드](./create-html-document-c-step-by-step-guide/) +Aspose.HTML for .NET을 사용해 C#에서 HTML 문서를 생성하고, 단계별 예제로 쉽게 따라 할 수 있습니다. ### [C#에서 문자열로 HTML 만들기 – 사용자 정의 리소스 핸들러 가이드](./create-html-from-string-in-c-custom-resource-handler-guide/) Aspose.HTML for .NET을 사용해 문자열에서 HTML을 생성하고 사용자 정의 리소스 핸들러로 처리하는 방법을 단계별로 안내합니다. ### [Aspose.HTML을 사용하여 .NET에서 문서 편집](./editing-a-document/) diff --git a/html/korean/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/korean/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..5f8f38fe9 --- /dev/null +++ b/html/korean/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,188 @@ +--- +category: general +date: 2026-03-21 +description: C#로 HTML 문서를 생성하고, id로 요소를 가져오는 방법, id로 요소를 찾는 방법, HTML 요소의 스타일을 변경하는 + 방법 및 Aspose.Html을 사용하여 굵게와 기울임을 추가하는 방법을 배우세요. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: ko +og_description: HTML 문서를 C#으로 만들고 즉시 id로 요소를 가져오는 방법, id로 요소를 찾는 방법, HTML 요소 스타일을 + 변경하는 방법, 그리고 굵은 기울임꼴을 추가하는 방법을 명확한 코드 예제로 배워보세요. +og_title: C#로 HTML 문서 만들기 – 완전한 프로그래밍 가이드 +tags: +- Aspose.Html +- C# +- DOM manipulation +title: C#로 HTML 문서 만들기 – 단계별 가이드 +url: /ko/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML 문서 C# 만들기 – 단계별 가이드 + +처음부터 **HTML 문서 C# 만들기**를 하고 단일 문단의 모양을 조정해야 했던 적이 있나요? 당신만 그런 것이 아닙니다. 많은 웹 자동화 프로젝트에서 HTML 파일을 생성하고, ID로 태그를 찾아낸 다음, 종종 굵게 + 기울임꼴로 스타일을 적용합니다—브라우저를 전혀 사용하지 않고도. + +이 튜토리얼에서는 바로 그 과정을 단계별로 살펴보겠습니다: C#에서 HTML 문서를 만들고, **get element by id**, **locate element by id**, **change HTML element style**를 수행한 뒤, 마지막으로 Aspose.Html 라이브러리를 사용해 **add bold italic**을 추가합니다. 끝까지 진행하면 .NET 프로젝트에 바로 넣어 실행할 수 있는 완전한 코드 스니펫을 얻게 됩니다. + +## 필요한 준비물 + +- .NET 6 또는 그 이후 버전 (코드는 .NET Framework 4.7+에서도 작동합니다) +- Visual Studio 2022 (또는 원하는 편집기) +- The **Aspose.Html** NuGet package (`Install-Package Aspose.Html`) + +그게 전부입니다—추가 HTML 파일도, 웹 서버도 필요 없으며, C# 몇 줄만 있으면 됩니다. + +## HTML 문서 C# 만들기 – 문서 초기화 + +우선 가장 먼저: Aspose.Html 엔진이 작업할 수 있는 실시간 `HTMLDocument` 객체가 필요합니다. 이를 마크업을 작성할 새 노트북을 여는 것으로 생각하면 됩니다. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **왜 중요한가:** 원시 문자열을 `HTMLDocument`에 전달하면 파일 I/O를 다루지 않아도 되고 모든 것을 메모리 내에 유지할 수 있어 단위 테스트나 실시간 생성에 최적입니다. + +## ID로 요소 가져오기 – 문단 찾기 + +문서가 존재하므로 이제 **get element by id**가 필요합니다. DOM API는 `GetElementById`를 제공하며, 이는 ID가 존재하지 않을 경우 `null`을 반환하거나 `IElement` 참조를 반환합니다. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **팁:** 마크업이 작더라도 null 검사를 추가하면 동일한 로직을 더 크고 동적인 페이지에 재사용할 때 문제를 예방할 수 있습니다. + +## ID로 요소 찾기 – 대체 접근법 + +때때로 문서의 루트에 대한 참조가 이미 있어 쿼리 스타일 검색을 선호할 수 있습니다. CSS 선택자(`QuerySelector`)를 사용하는 것이 **locate element by id**의 또 다른 방법입니다: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **언제 사용하나요?** `GetElementById`는 직접 해시 조회이기 때문에 약간 더 빠릅니다. `QuerySelector`는 복잡한 선택자(예: `div > p.highlight`)가 필요할 때 유용합니다. + +## HTML 요소 스타일 변경 – 굵게 기울임 적용 + +요소를 확보했으니 다음 단계는 **change HTML element style**입니다. Aspose.Html은 CSS 속성을 조정하거나 `WebFontStyle` 열거형을 사용해 한 번에 여러 글꼴 특성을 적용할 수 있는 `Style` 객체를 제공합니다. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +그 한 줄은 요소의 `font-weight`를 `bold`로, `font-style`을 `italic`으로 설정합니다. 내부적으로 Aspose.Html은 열거형을 적절한 CSS 문자열로 변환합니다. + +### 전체 작동 예제 + +모든 요소를 합치면 즉시 컴파일하고 실행할 수 있는 간결하고 독립적인 프로그램이 됩니다: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**예상 출력** + +``` +Rendered HTML: +

Hello world

+``` + +`

` 태그에 이제 인라인 `style` 속성이 추가되어 텍스트가 굵게와 기울임 모두 적용됩니다—우리가 원했던 바로 그 결과입니다. + +## 엣지 케이스 및 일반적인 함정 + +| 상황 | 주의할 점 | 해결 방법 | +|-----------|-------------------|---------------| +| **ID가 존재하지 않음** | `GetElementById`는 `null`을 반환합니다. | 예외를 발생시키거나 기본 요소로 대체합니다. | +| **여러 요소가 동일한 ID를 공유** | HTML 사양에서는 ID가 고유해야 하지만 실제 페이지에서는 규칙이 깨지는 경우가 있습니다. | `GetElementById`는 첫 번째 일치를 반환합니다; 중복을 처리해야 하면 `QuerySelectorAll` 사용을 고려하세요. | +| **스타일 충돌** | 기존 인라인 스타일이 덮어쓰기될 수 있습니다. | `style` 문자열 전체를 설정하는 대신 `Style` 객체에 추가합니다: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **브라우저 렌더링** | 요소에 더 높은 특이성을 가진 CSS 클래스가 이미 있으면 일부 브라우저는 `WebFontStyle`을 무시합니다. | 필요하면 `paragraph.Style.SetProperty("font-weight", "bold", "important");`와 같이 `!important`를 사용합니다. | + +## 실제 프로젝트를 위한 팁 + +- **문서를 캐시**하면 많은 요소를 처리할 때 매번 작은 스니펫마다 새로운 `HTMLDocument`를 생성하는 것이 성능에 영향을 줄 수 있습니다. +- **스타일 변경을 하나의 `Style` 트랜잭션으로 결합**하면 여러 DOM 재흐름을 방지할 수 있습니다. +- **Aspose.Html의 렌더링 엔진을 활용**해 최종 문서를 PDF 또는 이미지로 내보낼 수 있습니다—보고서 도구에 유용합니다. + +## 시각적 확인 (선택 사항) + +브라우저에서 결과를 확인하고 싶다면 렌더링된 문자열을 `.html` 파일로 저장할 수 있습니다: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +`output.html`을 열면 **Hello world**가 굵게 + 기울임으로 표시되는 것을 볼 수 있습니다. + +![굵게 기울임 문단을 보여주는 HTML 문서 C# 예시](/images/create-html-document-csharp.png "HTML 문서 C# – 렌더링 결과") + +*Alt text: 굵게 기울임 텍스트가 포함된 HTML 문서 C# – 렌더링 결과.* + +## 결론 + +우리는 이제 **HTML 문서 C#를 만들고**, **ID로 요소를 가져오고**, **ID로 요소를 찾고**, **HTML 요소 스타일을 변경하고**, 마지막으로 **굵게 기울임을 추가**했습니다—모두 Aspose.Html을 사용한 몇 줄의 코드로 구현했습니다. 이 접근법은 간단하고, 모든 .NET 환경에서 작동하며, 더 큰 DOM 조작에도 확장됩니다. + +다음 단계가 준비되셨나요? `WebFontStyle`을 `Underline` 같은 다른 열거형으로 교체하거나 여러 스타일을 수동으로 결합해 보세요. 또는 외부 HTML 파일을 로드하고 수백 개의 요소에 동일한 기술을 적용해 실험해 볼 수도 있습니다. 가능성은 무한하며, 이제 튼튼한 기반이 마련되었습니다. + +코딩 즐겁게 하세요! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/korean/net/html-extensions-and-conversions/_index.md b/html/korean/net/html-extensions-and-conversions/_index.md index 38fc3bd7e..796e0ca7c 100644 --- a/html/korean/net/html-extensions-and-conversions/_index.md +++ b/html/korean/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML for .NET은 단순한 라이브러리가 아니라 웹 개발의 세 ## HTML 확장 및 변환 튜토리얼 ### [Aspose.HTML을 사용하여 .NET에서 HTML을 PDF로 변환](./convert-html-to-pdf/) Aspose.HTML for .NET으로 HTML을 PDF로 손쉽게 변환하세요. 단계별 가이드를 따라 HTML-PDF 변환의 힘을 활용하세요. +### [Aspose를 사용해 HTML에서 PDF 만들기 – 단계별 C# 가이드](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Aspose.HTML for .NET을 활용해 C#에서 HTML을 PDF로 변환하는 단계별 가이드입니다. ### [HTML에서 PDF 만들기 – C# 단계별 가이드](./create-pdf-from-html-c-step-by-step-guide/) Aspose.HTML for .NET을 사용하여 C#에서 HTML을 PDF로 변환하는 단계별 가이드입니다. ### [Aspose.HTML을 사용하여 .NET에서 EPUB를 이미지로 변환](./convert-epub-to-image/) @@ -61,6 +63,8 @@ Aspose.HTML 사용하여 .NET에서 HTML을 Markdown으로 변환하는 방법 Aspose.HTML을 사용하여 .NET에서 HTML을 MHTML로 변환 - 효율적인 웹 콘텐츠 보관을 위한 단계별 가이드. .NET용 Aspose.HTML을 사용하여 MHTML 보관소를 만드는 방법을 알아보세요. ### [Aspose.HTML을 사용하여 .NET에서 HTML을 PNG로 변환](./convert-html-to-png/) Aspose.HTML for .NET을 사용하여 HTML 문서를 조작하고 변환하는 방법을 알아보세요. 효과적인 .NET 개발을 위한 단계별 가이드. +### [Aspose.HTML을 사용하여 .NET에서 HTML을 이미지로 변환 – 완전 가이드](./convert-html-to-image-in-c-complete-guide/) +Aspose.HTML for .NET을 사용하여 C#에서 HTML을 이미지로 변환하는 전체 단계별 가이드. ### [Aspose.HTML을 사용하여 .NET에서 HTML을 TIFF로 변환](./convert-html-to-tiff/) Aspose.HTML for .NET을 사용하여 HTML을 TIFF로 변환하는 방법을 알아보세요. 효율적인 웹 콘텐츠 최적화를 위한 단계별 가이드를 따르세요. ### [Aspose.HTML을 사용하여 .NET에서 HTML을 XPS로 변환](./convert-html-to-xps/) @@ -73,12 +77,11 @@ Aspose.HTML for .NET을 사용하여 스타일이 적용된 텍스트가 포함 Aspose.HTML for .NET을 사용해 HTML을 ZIP 파일로 저장하는 전체 C# 단계별 튜토리얼. ### [C#에서 HTML을 ZIP으로 저장 – 완전 인메모리 예제](./save-html-to-zip-in-c-complete-in-memory-example/) Aspose.HTML for .NET을 사용하여 메모리 내에서 HTML을 ZIP 파일로 저장하는 방법을 단계별로 안내합니다. +### [C#에서 HTML을 ZIP으로 저장 – 사용자 지정 스토리지를 활용한 완전 가이드](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +C#와 Aspose.HTML을 이용해 사용자 지정 스토리지를 활용해 HTML을 ZIP 파일로 저장하는 전체 가이드 +### [Aspose.HTML을 사용하여 HTML을 ZIP으로 압축하는 방법 – 전체 가이드](./how-to-zip-html-with-aspose-html-complete-guide/) +Aspose.HTML for .NET을 활용해 HTML을 ZIP 파일을 압축하는 전체 단계별 가이드를 확인하세요. -## 결론 - -결론적으로 HTML 확장 및 변환은 현대 웹 개발의 필수 요소입니다. Aspose.HTML for .NET은 프로세스를 단순화하고 모든 레벨의 개발자가 접근할 수 있도록 합니다. 튜토리얼을 따르면 광범위한 기술 세트를 갖춘 유능한 웹 개발자가 되는 길에 한 걸음 더 다가갈 수 있습니다. - -그럼, 무엇을 기다리고 계신가요? Aspose.HTML for .NET을 사용하여 HTML 확장 및 변환을 탐색하는 이 흥미로운 여정을 시작해 봅시다. 귀하의 웹 개발 프로젝트는 다시는 같지 않을 것입니다! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/korean/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/korean/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..c3b0847b1 --- /dev/null +++ b/html/korean/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,187 @@ +--- +category: general +date: 2026-03-21 +description: C#에서 Aspose.HTML을 사용해 HTML을 이미지로 변환합니다. HTML을 PNG로 저장하고, 이미지 크기 렌더링을 + 설정하며, 몇 단계만으로 이미지를 파일에 쓰는 방법을 배워보세요. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: ko +og_description: HTML을 이미지로 빠르게 변환합니다. 이 가이드는 HTML을 PNG로 저장하고, 이미지 크기 렌더링을 설정하며, Aspose.HTML을 + 사용해 이미지를 파일에 쓰는 방법을 보여줍니다. +og_title: C#에서 HTML을 이미지로 변환하기 – 단계별 가이드 +tags: +- Aspose.HTML +- C# +- Image Rendering +title: C#에서 HTML을 이미지로 변환하기 – 완전 가이드 +url: /ko/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 HTML을 이미지로 변환 – 완전 가이드 + +대시보드 썸네일, 이메일 미리보기, 혹은 PDF 보고서용 **HTML을 이미지로 변환**해야 할 때가 있나요? 동적인 웹 콘텐츠를 다른 곳에 삽입해야 할 때 이런 상황이 생각보다 자주 발생합니다. + +좋은 소식은? Aspose.HTML을 사용하면 **HTML을 이미지로 변환**을 몇 줄의 코드만으로 할 수 있으며, *HTML을 PNG로 저장*하고, 출력 크기를 제어하며, *이미지를 파일에 쓰는* 방법도 손쉽게 배울 수 있습니다. + +이 튜토리얼에서는 원격 페이지 로드부터 렌더링 크기 조정, 최종적으로 PNG 파일로 저장하는 전체 과정을 단계별로 살펴봅니다. 외부 도구나 복잡한 명령줄 트릭 없이 순수 C# 코드만으로 .NET 프로젝트 어디에든 바로 넣어 사용할 수 있습니다. + +## 배울 내용 + +- Aspose.HTML의 `HTMLDocument` 클래스를 사용해 **웹 페이지를 PNG로 렌더링**하는 방법. +- **이미지 크기 렌더링**을 설정해 출력이 레이아웃 요구사항에 맞도록 하는 정확한 단계. +- 스트림 및 파일 경로를 안전하게 다루며 **이미지를 파일에 쓰는** 방법. +- 폰트 누락이나 네트워크 타임아웃 같은 흔한 문제를 해결하는 팁. + +### 사전 요구 사항 + +- .NET 6.0 이상 (API는 .NET Framework에서도 동작하지만 .NET 6+ 권장). +- Aspose.HTML for .NET NuGet 패키지(`Aspose.Html`)에 대한 참조. +- C# 및 async/await에 대한 기본 지식 (선택 사항이지만 도움이 됨). + +위 조건을 이미 갖추었다면 바로 HTML을 이미지로 변환할 준비가 된 것입니다. + +## Step 1: 웹 페이지 로드 – HTML을 이미지로 변환하기 위한 기반 + +렌더링을 시작하기 전에 캡처하려는 페이지를 나타내는 `HTMLDocument` 인스턴스가 필요합니다. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*왜 중요한가:* `HTMLDocument`는 HTML을 파싱하고 CSS를 해석하며 DOM을 구축합니다. 문서를 로드하지 못하면(예: 네트워크 문제) 이후 렌더링은 빈 이미지가 됩니다. 진행하기 전에 URL에 접근 가능한지 반드시 확인하세요. + +## Step 2: 이미지 크기 렌더링 설정 – 너비, 높이 및 품질 제어 + +Aspose.HTML은 `ImageRenderingOptions`를 통해 출력 차원을 세밀하게 조정할 수 있습니다. 여기서 **이미지 크기 렌더링**을 목표 레이아웃에 맞게 **설정**합니다. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*프로 팁:* `Width`와 `Height`를 생략하면 Aspose.HTML은 페이지의 고유 크기를 사용하게 되는데, 반응형 디자인에서는 예측하기 어렵습니다. 명시적인 차원을 지정하면 **HTML을 PNG로 저장**한 결과가 정확히 기대한 대로 나옵니다. + +## Step 3: 이미지 파일에 쓰기 – 렌더링된 PNG 저장 + +문서와 렌더링 옵션이 준비되었으니 이제 **이미지를 파일에 쓰는** 작업을 수행합니다. `FileStream`을 사용하면 폴더가 아직 존재하지 않더라도 파일을 안전하게 생성할 수 있습니다. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +이 블록이 실행된 후 지정한 위치에 `page.png`가 생성됩니다. 이제 **웹 페이지를 PNG로 렌더링**하고 한 번에 디스크에 저장하는 작업을 마쳤습니다. + +### 예상 결과 + +`C:\Temp\page.png`를 이미지 뷰어로 열어 보세요. `https://example.com`의 스냅샷이 1024 × 768 픽셀 해상도로 부드러운 가장자리(안티앨리어싱 적용)와 함께 정확히 표시됩니다. 페이지에 동적 콘텐츠(예: JavaScript로 생성된 요소)가 포함돼 있어도 DOM이 완전히 로드된 뒤 렌더링하면 캡처됩니다. + +## Step 4: 엣지 케이스 처리 – 폰트, 인증, 대용량 페이지 + +기본 흐름은 대부분의 공개 사이트에 잘 동작하지만 실제 환경에서는 다양한 변수들이 발생합니다. + +| 상황 | 조치 | +|-----------|------------| +| **커스텀 폰트 로드 안 됨** | 폰트 파일을 로컬에 배치하고 `htmlDoc.Fonts.Add("path/to/font.ttf")`로 추가합니다. | +| **인증이 필요한 페이지** | 쿠키나 토큰을 포함한 `HttpWebRequest`를 받아들이는 `HTMLDocument` 오버로드를 사용합니다. | +| **매우 긴 페이지** | `Height`를 늘리거나 `ImageRenderingOptions`의 `PageScaling`을 활성화해 잘림을 방지합니다. | +| **메모리 사용량 급증** | `RenderToImage`의 `Rectangle` 영역 오버로드를 이용해 청크 단위로 렌더링합니다. | + +이러한 *이미지를 파일에 쓰는* 세부 사항을 다루면 **HTML을 이미지로 변환** 파이프라인이 프로덕션 환경에서도 견고하게 동작합니다. + +## Step 5: 전체 작업 예제 – 복사‑붙여넣기 바로 사용 가능 + +아래는 전체 프로그램 코드이며, 컴파일이 가능한 상태입니다. 모든 단계, 오류 처리 및 주석이 포함되어 있습니다. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +프로그램을 실행하면 콘솔에 확인 메시지가 표시됩니다. PNG 파일은 브라우저에서 **웹 페이지를 PNG로 렌더링**하고 스크린샷을 찍은 결과와 동일하지만, 훨씬 빠르고 완전 자동화된 형태입니다. + +## Frequently Asked Questions + +**Q: URL 대신 로컬 HTML 파일을 변환할 수 있나요?** +물론입니다. URL 대신 파일 경로를 지정하면 됩니다: `new HTMLDocument(@"C:\myPage.html")`. + +**Q: Aspose.HTML에 라이선스가 필요합니까?** +무료 평가 라이선스로 개발 및 테스트가 가능합니다. 프로덕션에서는 평가 워터마크를 제거하기 위해 라이선스를 구매해야 합니다. + +**Q: 페이지가 JavaScript로 콘텐츠를 동적으로 로드한다면 어떻게 해야 하나요?** +Aspose.HTML은 파싱 중에 JavaScript를 동기식으로 실행하지만, 장시간 실행되는 스크립트는 수동 지연이 필요할 수 있습니다. 렌더링 전에 `HTMLDocument.WaitForReadyState`를 호출하면 됩니다. + +## Conclusion + +이제 C#에서 **HTML을 이미지로 변환**하는 완전한 엔드‑투‑엔드 솔루션을 갖추었습니다. 위 단계를 따르면 **HTML을 PNG로 저장**, 정확한 **이미지 크기 렌더링** 설정, 그리고 어떤 Windows 혹은 Linux 환경에서도 **이미지를 파일에 쓰는** 작업을 자신 있게 수행할 수 있습니다. + +간단한 스크린샷부터 자동화된 보고서 생성까지, 이 기술은 규모에 따라 유연하게 확장됩니다. 다음 단계로 JPEG나 BMP 같은 다른 포맷을 시도하거나, ASP.NET Core API에 통합해 호출자에게 PNG를 직접 반환하도록 해보세요. 가능성은 사실상 무한합니다. + +Happy coding, and may your rendered images always look pixel‑perfect! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/korean/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..7f9b0685a --- /dev/null +++ b/html/korean/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-03-21 +description: Aspose HTML을 사용하여 HTML에서 PDF를 빠르게 생성하세요. HTML을 PDF로 렌더링하고, HTML을 PDF로 + 변환하는 방법 및 Aspose 사용법을 간결한 튜토리얼에서 배워보세요. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: ko +og_description: C#에서 Aspose를 사용하여 HTML에서 PDF 만들기. 이 가이드는 HTML을 PDF로 렌더링하고, HTML을 PDF로 + 변환하는 방법 및 Aspose를 효과적으로 사용하는 방법을 보여줍니다. +og_title: HTML에서 PDF 만들기 – 완전한 Aspose C# 튜토리얼 +tags: +- Aspose +- C# +- PDF generation +title: Aspose를 사용하여 HTML에서 PDF 만들기 – 단계별 C# 가이드 +url: /ko/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose를 사용한 HTML에서 PDF 만들기 – 단계별 C# 가이드 + +**HTML에서 PDF 만들기**가 필요했지만, 어떤 라이브러리가 픽셀 단위로 완벽한 결과를 제공할지 몰랐던 적이 있나요? 당신만 그런 것이 아닙니다. 많은 개발자들이 웹 스니펫을 인쇄 가능한 문서로 변환하려다 텍스트가 흐리게 보이거나 레이아웃이 깨지는 문제를 겪습니다. + +좋은 소식은 Aspose HTML이 전체 과정을 손쉽게 만들어 준다는 것입니다. 이 튜토리얼에서는 **HTML을 PDF로 렌더링**하는 정확한 코드를 단계별로 살펴보고, 각 설정이 왜 중요한지 설명하며, **HTML을 PDF로 변환**하는 방법을 숨은 트릭 없이 보여드립니다. 마지막까지 읽으면 .NET 프로젝트 어디서든 신뢰할 수 있는 PDF 생성을 위해 **Aspose 사용 방법**을 알게 됩니다. + +## 사전 요구 사항 – 시작하기 전에 준비할 것 + +- **.NET 6.0 이상** (예제는 .NET Framework 4.7+에서도 작동합니다) +- **Visual Studio 2022** 또는 C#를 지원하는 모든 IDE +- **Aspose.HTML for .NET** NuGet 패키지 (무료 체험 또는 정식 라이선스 버전) +- C# 구문에 대한 기본 이해 (깊은 PDF 지식은 필요 없음) + +위 항목들을 갖추었다면 바로 시작할 수 있습니다. 아직이라면 최신 .NET SDK를 다운로드하고 다음 명령으로 NuGet 패키지를 설치하세요: + +```bash +dotnet add package Aspose.HTML +``` + +이 한 줄만으로 **aspose html to pdf** 변환에 필요한 모든 것이 포함됩니다. + +--- + +## 단계 1: HTML에서 PDF를 만들기 위한 프로젝트 설정 + +먼저 새 콘솔 애플리케이션을 만들거나(또는 기존 서비스에 코드를 통합)합니다. 아래는 최소한의 `Program.cs` 골격입니다: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** 이전 샘플에서 `Aspise.Html.Rendering.Text`를 보면 `Aspose.Html.Rendering.Text`로 교체하세요. 오타 때문에 컴파일 오류가 발생합니다. + +올바른 네임스페이스를 사용하면 컴파일러가 나중에 필요하게 될 **TextOptions** 클래스를 찾을 수 있습니다. + +## 단계 2: HTML 문서 만들기 (HTML을 PDF로 렌더링) + +이제 소스 HTML을 생성합니다. Aspose는 원시 문자열, 파일 경로, 혹은 URL을 전달할 수 있습니다. 이번 데모에서는 간단히 진행합니다: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +왜 문자열을 전달할까요? 파일 시스템 I/O를 피하고 변환 속도를 높이며, 코드에 보이는 HTML이 그대로 렌더링된다는 것을 보장합니다. 파일에서 로드하고 싶다면 생성자 인자를 파일 URI로 교체하면 됩니다. + +## 단계 3: 텍스트 렌더링 미세 조정 (품질 향상된 HTML을 PDF로 변환) + +텍스트 렌더링은 PDF가 선명하게 보일지 흐릿하게 보일지를 결정합니다. Aspose는 `TextOptions` 클래스를 제공해 서브픽셀 힌팅을 활성화할 수 있게 하며, 이는 고 DPI 출력에 필수적입니다. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +`UseHinting`을 활성화하면 소스 HTML에 사용자 정의 폰트나 작은 글꼴 크기가 있을 때 특히 유용합니다. 이를 사용하지 않으면 최종 PDF에서 톱니 모양 가장자리를 볼 수 있습니다. + +## 단계 4: 텍스트 옵션을 PDF 렌더링 구성에 연결하기 (Aspose 사용 방법) + +다음으로, 텍스트 옵션을 PDF 렌더러에 바인딩합니다. 여기서 **aspose html to pdf**가 진가를 발휘합니다—페이지 크기부터 압축까지 모든 설정을 조정할 수 있습니다. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +기본 A4 크기가 괜찮다면 `PageSetup`을 생략할 수 있습니다. 핵심은 `TextOptions` 객체가 `PdfRenderingOptions` 안에 존재한다는 것이며, 이를 통해 Aspose에 텍스트를 어떻게 렌더링할지 알려줍니다. + +## 단계 5: HTML을 렌더링하고 PDF로 저장하기 (HTML을 PDF로 변환) + +마지막으로, 출력을 파일 스트림으로 저장합니다. `using` 블록을 사용하면 예외가 발생하더라도 파일 핸들이 올바르게 닫히게 보장됩니다. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +프로그램을 실행하면 실행 파일 옆에 `output.pdf`가 생성됩니다. 이를 열면 HTML 문자열에 정의된 대로 깔끔한 제목과 단락을 확인할 수 있습니다. + +### 예상 출력 + +![HTML에서 PDF 생성 예시 출력](https://example.com/images/pdf-output.png "HTML에서 PDF 생성 예시 출력") + +*스크린샷은 텍스트 힌팅 덕분에 “Hello, Aspose!”라는 제목이 선명하게 렌더링된 생성된 PDF를 보여줍니다.* + +--- + +## 일반적인 질문 및 엣지 케이스 + +### 1. HTML이 외부 리소스(이미지, CSS)를 참조하는 경우는 어떻게 하나요? + +Aspose는 문서의 기본 URI를 기준으로 상대 URL을 해석합니다. 원시 문자열을 전달하는 경우, 기본 URI를 수동으로 설정하세요: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +이제 ``는 `C:/MyProject/`를 기준으로 찾아집니다. + +### 2. 서버에 설치되지 않은 폰트를 어떻게 임베드하나요? + +`@font-face`를 사용해 로컬 또는 원격 폰트 파일을 지정하는 ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### 단계 4: 저장 옵션을 맞춤 저장소 사용하도록 구성 + +`HtmlSaveOptions`를 사용하면 Aspose에게 모든 내용을 ZIP 파일로 압축하도록 지시할 수 있습니다. `OutputStorage` 속성(레거시)은 우리의 `MyStorage` 인스턴스를 받습니다. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Note:** Aspose HTML 23.9+에서는 속성 이름이 `OutputStorage`이지만 사용 중단(Obsolete) 표시됩니다. 최신 대안은 `ZipOutputStorage`입니다. 아래 코드는 인터페이스가 동일하기 때문에 두 속성 모두에서 동작합니다. + +### 단계 5: 문서를 ZIP 아카이브로 저장 + +대상 폴더(또는 스트림)를 선택하고 Aspose가 작업을 수행하도록 합니다. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +프로그램이 종료되면 `output.zip` 안에 다음이 포함되어 있음을 확인할 수 있습니다: + +* `index.html` – 메인 문서. +* 포함된 이미지, CSS 파일 또는 스크립트(HTML에서 참조한 경우). + +아카이브 관리자를 사용해 ZIP을 열어 구조를 확인할 수 있습니다. + +--- + +## 결과 검증 (선택 사항) + +디스크에 추출하지 않고 프로그램matically 아카이브를 검사하고 싶다면: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +예시 출력: + +``` +- index.html (452 bytes) +``` + +이미지나 CSS가 있었다면 추가 항목으로 나타납니다. 이 간단한 확인을 통해 **create html zip archive**가 정상적으로 작동했음을 확인할 수 있습니다. + +--- + +## 일반적인 질문 및 엣지 케이스 + +| Question | Answer | +|----------|--------| +| **ZIP을 직접 응답 스트림에 쓰고 싶다면 어떻게 해야 하나요?** | `document.Save` 후 `MyStorage`에서 얻은 `MemoryStream`을 반환합니다. 이를 `byte[]`로 변환한 뒤 `HttpResponse.Body`에 씁니다. | +| **내 HTML이 외부 URL을 참조하는데, 해당 리소스가 다운로드되나요?** | 아니요. Aspose는 *내장된* 리소스(예: `` 또는 로컬 파일)만 압축합니다. 원격 자산은 먼저 다운로드하고 마크업을 수정해야 합니다. | +| **`OutputStorage` 속성이 사용 중단 표시되어 있는데, 무시해도 될까요?** | 여전히 동작하지만, 최신 `ZipOutputStorage`가 동일한 API를 다른 이름으로 제공합니다. 경고 없이 빌드하려면 `OutputStorage`를 `ZipOutputStorage`로 교체하세요. | +| **ZIP을 암호화할 수 있나요?** | 예. 저장 후 `System.IO.Compression.ZipArchive`를 열고 `SharpZipLib`와 같은 서드파티 라이브러리를 사용해 비밀번호를 설정합니다. Aspose 자체는 암호화를 제공하지 않습니다. | + +## 전체 작동 예제 (복사‑붙여넣기) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +프로그램을 실행하고 `output.zip`을 열면, 브라우저에서 열었을 때 “Hello from ZIP!” 헤딩을 표시하는 단일 `index.html` 파일을 확인할 수 있습니다. + +## 결론 + +이제 **HTML을 ZIP으로 저장하는** 방법을 C#에서 **맞춤 저장소** 클래스를 사용해 알게 되었으며, **HTML을 ZIP으로 내보내는** 방법과 배포 준비가 된 **HTML zip archive**를 만드는 방법을 이해했습니다. 이 패턴은 유연합니다—`MemoryStream`을 클라우드 스트림으로 교체하거나, 암호화를 추가하거나, 필요 시 ZIP을 반환하는 웹 API에 통합할 수 있습니다. + +다음 단계가 준비되셨나요? 이미지와 스타일이 포함된 완전한 웹 페이지를 입력해 보거나, 저장소를 Azure Blob Storage에 연결해 로컬 파일 시스템을 완전히 우회해 보세요. Aspose.HTML의 ZIP 기능과 자체 저장소 로직을 결합하면 가능성은 무한합니다. + +코딩 즐겁게 하시고, 여러분의 아카이브가 언제나 깔끔하기를 바랍니다! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/polish/net/generate-jpg-and-png-images/_index.md b/html/polish/net/generate-jpg-and-png-images/_index.md index fff5f7a92..2eee31d0e 100644 --- a/html/polish/net/generate-jpg-and-png-images/_index.md +++ b/html/polish/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Naucz się używać Aspose.HTML dla .NET do manipulowania dokumentami HTML, konw Dowiedz się, jak włączyć antyaliasing przy konwersji dokumentów DOCX do formatów PNG i JPG przy użyciu Aspose.HTML. ### [Konwertuj docx do png – utwórz archiwum zip w C# – samouczek](./convert-docx-to-png-create-zip-archive-c-tutorial/) Dowiedz się, jak konwertować pliki DOCX na obrazy PNG i spakować je do archiwum ZIP przy użyciu C# i Aspose.HTML. +### [Konwertuj HTML do PNG – Pełny przewodnik C# z eksportem ZIP](./convert-html-to-png-full-c-guide-with-zip-export/) +Kompletny samouczek w C#, który pokazuje, jak konwertować HTML do PNG i zapisywać wyniki w archiwum ZIP. ## Wniosek diff --git a/html/polish/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/polish/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..741445d8c --- /dev/null +++ b/html/polish/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Konwertuj HTML na PNG i renderuj HTML jako obraz, jednocześnie zapisując + HTML do pliku ZIP. Dowiedz się, jak zastosować styl czcionki w HTML i dodać pogrubienie + do elementów p w kilku prostych krokach. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: pl +og_description: Szybko konwertuj HTML na PNG. Ten przewodnik pokazuje, jak renderować + HTML jako obraz, zapisać HTML do ZIP, zastosować styl czcionki w HTML oraz dodać + pogrubienie do elementów p. +og_title: Konwertuj HTML na PNG – Kompletny samouczek C# +tags: +- Aspose +- C# +title: Konwertuj HTML na PNG – Pełny przewodnik C# z eksportem ZIP +url: /pl/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konwertuj HTML do PNG – Pełny przewodnik C# z eksportem do ZIP + +Kiedykolwiek potrzebowałeś **konwertować HTML do PNG**, ale nie wiedziałeś, która biblioteka potrafi to zrobić bez użycia przeglądarki headless? Nie jesteś sam. W wielu projektach — miniaturki e‑maili, podglądy dokumentacji czy obrazy podglądu — przekształcenie strony internetowej w statyczny obraz to realna potrzeba. + +Dobre wieści? Dzięki Aspose.HTML możesz **renderować HTML jako obraz**, modyfikować znacznik w locie, a nawet **zapisać HTML do ZIP** na późniejsze udostępnienie. W tym tutorialu przejdziemy krok po kroku przez kompletny, gotowy do uruchomienia przykład, który **stosuje styl czcionki HTML**, konkretnie **dodaje pogrubienie do elementów p**, zanim wygeneruje plik PNG. Na końcu będziesz mieć jedną klasę C#, która robi wszystko — od wczytania strony po archiwizację jej zasobów. + +## Czego będziesz potrzebować + +- .NET 6.0 lub nowszy (API działa także na .NET Core) +- Aspose.HTML dla .NET 6+ (pakiet NuGet `Aspose.Html`) +- Podstawowa znajomość składni C# (nie są wymagane zaawansowane koncepcje) + +To wszystko. Bez zewnętrznych przeglądarek, bez phantomjs, tylko czysty kod zarządzany. + +## Krok 1 – Wczytaj dokument HTML + +Najpierw wprowadzamy plik źródłowy (lub URL) do obiektu `HTMLDocument`. Ten krok jest podstawą zarówno **renderowania html jako obrazu**, jak i **zapisu html do zip** później. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Dlaczego to ważne:* Klasa `HTMLDocument` parsuje znacznik, buduje DOM i rozwiązuje powiązane zasoby (CSS, obrazy, czcionki). Bez prawidłowego obiektu dokumentu nie możesz manipulować stylami ani nic renderować. + +## Krok 2 – Zastosuj styl czcionki HTML (Dodaj pogrubienie do p) + +Teraz **zastosujemy styl czcionki HTML**, iterując po każdym elemencie `

` i ustawiając jego `font-weight` na `bold`. To programistyczny sposób na **dodanie pogrubienia do p** bez modyfikacji oryginalnego pliku. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Wskazówka:* Jeśli potrzebujesz pogrubić tylko wybraną część, zmień selektor na bardziej specyficzny, np. `"p.intro"`. + +## Krok 3 – Renderuj HTML jako obraz (Konwertuj HTML do PNG) + +Gdy DOM jest gotowy, konfigurujemy `ImageRenderingOptions` i wywołujemy `RenderToImage`. To właśnie tutaj dzieje się magia **konwersji html do png**. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Dlaczego opcje mają znaczenie:* Ustawienie stałej szerokości/wysokości zapobiega zbyt dużemu rozmiarowi wyjścia, a antyaliasing zapewnia płynniejszy efekt wizualny. Możesz także zmienić `options` na `ImageFormat.Jpeg`, jeśli wolisz mniejszy rozmiar pliku. + +## Krok 4 – Zapisz HTML do ZIP (Pakowanie zasobów) + +Często trzeba dostarczyć oryginalny HTML wraz z jego CSS, obrazami i czcionkami. `ZipArchiveSaveOptions` Aspose.HTML robi dokładnie to. Dodatkowo podpinamy własny `ResourceHandler`, aby wszystkie zewnętrzne zasoby zostały zapisane w tym samym folderze co archiwum. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Przypadek brzegowy:* Jeśli Twój HTML odwołuje się do zdalnych obrazów wymagających uwierzytelnienia, domyślny handler zawiedzie. W takim scenariuszu możesz rozszerzyć `MyResourceHandler`, aby wstrzyknąć nagłówki HTTP. + +## Krok 5 – Połącz wszystko w jednej klasie konwertera + +Poniżej pełna, gotowa do uruchomienia klasa, która łączy wszystkie poprzednie kroki. Skopiuj‑wklej ją do aplikacji konsolowej, wywołaj `Convert` i obserwuj, jak pojawiają się pliki. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Oczekiwany wynik + +Po uruchomieniu powyższego fragmentu znajdziesz dwa pliki w `outputDirectory`: + +| Plik | Opis | +|------|------| +| `page.png` | Renderowanie PNG o wymiarach 1200 × 800 źródłowego HTML, z każdym akapitem wyświetlonym w **pogrubieniu**. | +| `archive.zip` | Pakiet ZIP zawierający oryginalny `input.html`, jego CSS, obrazy oraz wszelkie web‑fonty – idealny do dystrybucji offline. | + +Możesz otworzyć `page.png` w dowolnej przeglądarce obrazów, aby zweryfikować zastosowanie stylu pogrubienia, oraz rozpakować `archive.zip`, aby zobaczyć niezmieniony HTML wraz z jego zasobami. + +## Częste pytania i pułapki + +- **Co jeśli HTML zawiera JavaScript?** + Aspose.HTML **nie** wykonuje skryptów podczas renderowania, więc dynamiczna zawartość nie pojawi się. Do w pełni wyrenderowanych stron potrzebna jest przeglądarka headless, ale dla statycznych szablonów to rozwiązanie jest szybsze i lżejsze. + +- **Czy mogę zmienić format wyjściowy na JPEG lub BMP?** + Tak — zamień właściwość `ImageFormat` w `ImageRenderingOptions`, np. `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Czy muszę ręcznie zwalniać `HTMLDocument`?** + Klasa implementuje `IDisposable`. W długotrwałej usłudze otocz ją blokiem `using` lub wywołaj `document.Dispose()` po zakończeniu pracy. + +- **Jak działa niestandardowy `MyResourceHandler`?** + Otrzymuje każdy zewnętrzny zasób (CSS, obrazy, czcionki) i zapisuje go w określonym folderze. Dzięki temu ZIP zawiera wierną kopię wszystkiego, do czego odwołuje się HTML. + +## Zakończenie + +Masz teraz kompaktowe, gotowe do produkcji rozwiązanie, które **konwertuje html do png**, **renderuje html jako obraz**, **zapisuje html do zip**, **stosuje styl czcionki html** i **dodaje pogrubienie do p** — wszystko w kilku linijkach C#. Kod jest samodzielny, działa z .NET 6+ i może być wstawiony do dowolnej usługi backendowej, potrzebującej szybkich wizualnych migawków treści webowych. + +Gotowy na kolejny krok? Spróbuj zmienić rozmiar renderowania, poeksperymentuj z innymi właściwościami CSS (np. `font-family` lub `color`) lub zintegrować ten konwerter z endpointem ASP.NET Core, który zwraca PNG na żądanie. Możliwości są nieograniczone, a dzięki Aspose.HTML omijasz ciężkie zależności przeglądarkowe. + +Jeśli napotkasz problemy lub masz pomysły na rozszerzenia, zostaw komentarz poniżej. Szczęśliwego kodowania! + +![przykład konwersji html do png](example.png "przykład konwersji html do png") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/polish/net/html-document-manipulation/_index.md b/html/polish/net/html-document-manipulation/_index.md index 4d8dfd764..828610c12 100644 --- a/html/polish/net/html-document-manipulation/_index.md +++ b/html/polish/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Naucz się korzystać z Aspose.HTML dla .NET. Importuj przestrzenie nazw, scalaj Odblokuj potencjał rozwoju sieci z Aspose.HTML dla .NET. Twórz, konwertuj i manipuluj dokumentami HTML w prosty sposób. ### [Tworzenie HTML z ciągu w C# – Przewodnik po niestandardowym obsługiwaniu zasobów](./create-html-from-string-in-c-custom-resource-handler-guide/) Dowiedz się, jak generować dokumenty HTML z łańcucha znaków w C# przy użyciu niestandardowego obsługiwacza zasobów w Aspose.HTML. +### [Tworzenie dokumentu HTML w C# – Przewodnik krok po kroku](./create-html-document-c-step-by-step-guide/) +Poznaj, jak w prosty sposób utworzyć dokument HTML w C# przy użyciu Aspose.HTML, krok po kroku z przykładami. ## Wniosek diff --git a/html/polish/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/polish/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..91f4a1a10 --- /dev/null +++ b/html/polish/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: Utwórz dokument HTML w C# i dowiedz się, jak pobrać element po identyfikatorze, + zlokalizować element po identyfikatorze, zmienić styl elementu HTML oraz dodać pogrubienie + i kursywę przy użyciu Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: pl +og_description: Utwórz dokument HTML w C# i natychmiast naucz się pobierać element + po id, znajdować element po id, zmieniać styl elementu HTML oraz dodawać pogrubienie + i kursywę, z przejrzystymi przykładami kodu. +og_title: Tworzenie dokumentu HTML w C# – Kompletny przewodnik programistyczny +tags: +- Aspose.Html +- C# +- DOM manipulation +title: Tworzenie dokumentu HTML w C# – Przewodnik krok po kroku +url: /pl/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utwórz dokument HTML w C# – Przewodnik krok po kroku + +Kiedykolwiek potrzebowałeś **utworzyć dokument HTML w C#** od podstaw, a potem zmienić wygląd jednego akapitu? Nie jesteś sam. W wielu projektach automatyzacji sieciowej tworzysz plik HTML, wyszukujesz znacznik po jego ID i stosujesz styl – często pogrubienie + pochylenie – bez wchodzenia w przeglądarkę. + +W tym tutorialu przejdziemy dokładnie przez to: utworzymy dokument HTML w C#, **get element by id**, **locate element by id**, **change HTML element style**, a na koniec **add bold italic** przy użyciu biblioteki Aspose.Html. Po zakończeniu będziesz mieć w pełni działający fragment kodu, który możesz wkleić do dowolnego projektu .NET. + +## Co będzie potrzebne + +- .NET 6 lub nowszy (kod działa także na .NET Framework 4.7+) +- Visual Studio 2022 (lub dowolny ulubiony edytor) +- Pakiet NuGet **Aspose.Html** (`Install-Package Aspose.Html`) + +To wszystko – żadnych dodatkowych plików HTML, żadnego serwera, tylko kilka linii C#. + +## Utwórz dokument HTML w C# – Inicjalizacja dokumentu + +Na początek potrzebujesz żywego obiektu `HTMLDocument`, z którym silnik Aspose.Html może pracować. Pomyśl o tym jak o otwarciu świeżego notesu, w którym zapiszesz swój znacznik. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Dlaczego to ważne:** Przekazując surowy łańcuch znaków do `HTMLDocument`, unikasz operacji I/O na plikach i trzymasz wszystko w pamięci – idealne do testów jednostkowych lub generowania w locie. + +## Get Element by ID – Znajdowanie akapitu + +Teraz, gdy dokument istnieje, musimy **get element by id**. API DOM udostępnia `GetElementById`, które zwraca referencję `IElement` lub `null`, jeśli podane ID nie istnieje. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Pro tip:** Nawet jeśli nasz znacznik jest mały, dodanie sprawdzenia na `null` oszczędza kłopotów, gdy ta sama logika jest używana na większych, dynamicznych stronach. + +## Locate Element by ID – Alternatywne podejście + +Czasami możesz już mieć referencję do korzenia dokumentu i wolisz wyszukiwanie w stylu zapytania. Użycie selektorów CSS (`QuerySelector`) to kolejny sposób na **locate element by id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **Kiedy używać którego?** `GetElementById` jest nieco szybszy, bo to bezpośrednie wyszukiwanie w hash‑ie. `QuerySelector` błyszczy, gdy potrzebujesz złożonych selektorów (np. `div > p.highlight`). + +## Change HTML Element Style – Dodawanie pogrubienia i pochylenia + +Mając już element, następnym krokiem jest **change HTML element style**. Aspose.Html udostępnia obiekt `Style`, w którym możesz modyfikować właściwości CSS lub użyć wygodnej enumeracji `WebFontStyle`, aby jednocześnie zastosować kilka cech czcionki. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Ta jedyna linia ustawia `font-weight` na `bold` oraz `font-style` na `italic`. W tle Aspose.Html przetłumaczy enumerację na odpowiedni ciąg CSS. + +### Pełny działający przykład + +Połączenie wszystkich elementów daje kompaktowy, samodzielny program, który możesz od razu skompilować i uruchomić: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Oczekiwany wynik** + +``` +Rendered HTML: +

Hello world

+``` + +Tag `

` posiada teraz atrybut `style` inline, który sprawia, że tekst jest zarówno pogrubiony, jak i pochylony – dokładnie to, czego potrzebowaliśmy. + +## Edge Cases & Common Pitfalls + +| Sytuacja | Na co zwrócić uwagę | Jak postąpić | +|-----------|-------------------|---------------| +| **ID nie istnieje** | `GetElementById` zwraca `null`. | Rzuć wyjątek lub przejdź do elementu domyślnego. | +| **Wiele elementów ma to samo ID** | Specyfikacja HTML wymaga unikalności ID, ale w rzeczywistości strony czasem łamią tę regułę. | `GetElementById` zwraca pierwszy dopasowany element; rozważ użycie `QuerySelectorAll`, jeśli musisz obsłużyć duplikaty. | +| **Konflikty stylów** | Istniejące style inline mogą zostać nadpisane. | Dodawaj do obiektu `Style` zamiast nadpisywać cały ciąg `style`: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Renderowanie w przeglądarce** | Niektóre przeglądarki ignorują `WebFontStyle`, jeśli element ma już klasę CSS o wyższej specyficzności. | Użyj `!important` poprzez `paragraph.Style.SetProperty("font-weight", "bold", "important");` w razie potrzeby. | + +## Pro Tips dla projektów produkcyjnych + +- **Cache'uj dokument**, jeśli przetwarzasz wiele elementów; tworzenie nowego `HTMLDocument` dla każdego małego fragmentu może obniżyć wydajność. +- **Łącz zmiany stylów** w jednej transakcji `Style`, aby uniknąć wielu przeliczeń DOM. +- **Wykorzystaj silnik renderujący Aspose.Html** do eksportu finalnego dokumentu jako PDF lub obraz – świetne w narzędziach raportujących. + +## Wizualna weryfikacja (opcjonalnie) + +Jeśli wolisz zobaczyć rezultat w przeglądarce, możesz zapisać wygenerowany łańcuch do pliku `.html`: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Otwórz `output.html`, a zobaczysz **Hello world** wyświetlone pogrubioną + pochyloną czcionką. + +![Utwórz dokument HTML w C# – przykład pokazujący pogrubiony i pochylony akapit](/images/create-html-document-csharp.png "Utwórz dokument HTML w C# – renderowany wynik") + +*Alt text: Utwórz dokument HTML w C# – renderowany wynik z pogrubionym i pochylonym tekstem.* + +## Zakończenie + +Właśnie **utworzyliśmy dokument HTML w C#**, **pobieraliśmy element po id**, **lokalizowaliśmy element po id**, **zmieniliśmy styl elementu HTML**, i na koniec **dodaliśmy pogrubienie i pochylenie** — wszystko w kilku linijkach przy użyciu Aspose.Html. Podejście jest proste, działa w każdym środowisku .NET i skaluje się do większych manipulacji DOM. + +Gotowy na kolejny krok? Spróbuj zamienić `WebFontStyle` na inne enumy, np. `Underline`, lub połącz kilka stylów ręcznie. Albo eksperymentuj z ładowaniem zewnętrznego pliku HTML i zastosuj tę samą technikę do setek elementów. Nie ma granic, a Ty masz solidne podstawy, na których możesz budować. + +Miłego kodowania! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/polish/net/html-extensions-and-conversions/_index.md b/html/polish/net/html-extensions-and-conversions/_index.md index 5b553b002..80e92b094 100644 --- a/html/polish/net/html-extensions-and-conversions/_index.md +++ b/html/polish/net/html-extensions-and-conversions/_index.md @@ -41,6 +41,8 @@ Aspose.HTML dla .NET to nie tylko biblioteka; to przełom w świecie tworzenia s Konwertuj HTML do PDF bez wysiłku dzięki Aspose.HTML dla .NET. Postępuj zgodnie z naszym przewodnikiem krok po kroku i uwolnij moc konwersji HTML do PDF. ### [Utwórz PDF z HTML – przewodnik krok po kroku w C#](./create-pdf-from-html-c-step-by-step-guide/) Dowiedz się, jak w C# wygenerować plik PDF z kodu HTML, korzystając z Aspose.HTML – kompletny przewodnik krok po kroku. +### [Utwórz PDF z HTML przy użyciu Aspose – Przewodnik krok po kroku w C#](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Dowiedz się, jak w C# wygenerować plik PDF z kodu HTML przy użyciu Aspose – kompletny przewodnik krok po kroku. ### [Konwersja EPUB do obrazu w .NET za pomocą Aspose.HTML](./convert-epub-to-image/) Dowiedz się, jak konwertować EPUB na obrazy za pomocą Aspose.HTML dla .NET. Samouczek krok po kroku z przykładami kodu i opcjami dostosowywania. ### [Konwertuj EPUB do PDF w .NET za pomocą Aspose.HTML](./convert-epub-to-pdf/) @@ -52,7 +54,9 @@ Dowiedz się, jak przekonwertować HTML na BMP w .NET przy użyciu Aspose.HTML d ### [Konwertuj HTML na DOC i DOCX w .NET za pomocą Aspose.HTML](./convert-html-to-doc-docx/) Dowiedz się, jak wykorzystać moc Aspose.HTML dla .NET w tym przewodniku krok po kroku. Konwertuj HTML do DOCX bez wysiłku i podnieś poziom swoich projektów .NET. Zacznij już dziś! ### [Konwertuj HTML na GIF w .NET za pomocą Aspose.HTML](./convert-html-to-gif/) -Odkryj moc Aspose.HTML dla .NET: przewodnik krok po kroku po konwersji HTML na GIF. Wymagania wstępne, przykłady kodu, FAQ i więcej! Zoptymalizuj manipulację HTML za pomocą Aspose.HTML. +Odkryj moc Aspose.HTML dla .NET: Konwertuj HTML na GIF. Wymagania wstępne, przewodnik krok po kroku i FAQ. Zoptymalizuj manipulację HTML za pomocą Aspose.HTML. +### [Konwertuj HTML na obraz w C# – Kompletny przewodnik](./convert-html-to-image-in-c-complete-guide/) +Dowiedz się, jak konwertować HTML na obrazy w C# przy użyciu Aspose.HTML – kompletny przewodnik krok po kroku. ### [Konwersja HTML do JPEG w .NET za pomocą Aspose.HTML](./convert-html-to-jpeg/) Dowiedz się, jak konwertować HTML na JPEG w .NET za pomocą Aspose.HTML dla .NET. Przewodnik krok po kroku, jak wykorzystać moc Aspose.HTML dla .NET. Zoptymalizuj swoje zadania związane z tworzeniem stron internetowych bez wysiłku. ### [Konwersja HTML do Markdown w .NET za pomocą Aspose.HTML](./convert-html-to-markdown/) @@ -73,6 +77,10 @@ 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 jako ZIP w C# – Kompletny przewodnik z niestandardowym magazynem](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Zapisz dokument HTML jako archiwum ZIP w C# przy użyciu Aspose.HTML – kompletny przewodnik krok po kroku z niestandardowym magazynem. +### [Jak spakować HTML przy użyciu Aspose.HTML – Kompletny przewodnik](./how-to-zip-html-with-aspose-html-complete-guide/) +Kompletny przewodnik, jak spakować plik HTML do archiwum ZIP przy użyciu Aspose.HTML w .NET. ## Wniosek diff --git a/html/polish/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/polish/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..801352274 --- /dev/null +++ b/html/polish/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Konwertuj HTML na obraz przy użyciu Aspose.HTML w C#. Dowiedz się, jak + zapisać HTML jako PNG, ustawić rozmiar renderowanego obrazu oraz zapisać go do pliku + w kilku prostych krokach. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: pl +og_description: Szybko konwertuj HTML na obraz. Ten przewodnik pokazuje, jak zapisać + HTML jako PNG, ustawić rozmiar renderowanego obrazu oraz zapisać obraz do pliku + przy użyciu Aspose.HTML. +og_title: Konwertuj HTML na obraz w C# – Przewodnik krok po kroku +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Konwertuj HTML na obraz w C# – Kompletny przewodnik +url: /pl/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konwertowanie HTML do obrazu w C# – Kompletny przewodnik + +Czy kiedykolwiek potrzebowałeś **convert HTML to image** dla miniaturki pulpitu, podglądu e‑maila lub raportu PDF? To sytuacja, która pojawia się częściej niż się spodziewasz, szczególnie gdy pracujesz z dynamiczną treścią webową, którą trzeba gdzieś osadzić. + +Dobra wiadomość? Dzięki Aspose.HTML możesz **convert HTML to image** w zaledwie kilku linijkach kodu, a także dowiesz się, jak *save HTML as PNG*, kontrolować wymiary wyjściowe oraz *write image to file* bez żadnego wysiłku. + +W tym samouczku przejdziemy przez wszystko, co musisz wiedzieć: od ładowania zdalnej strony, przez dostosowanie rozmiaru renderowania, po zapisanie wyniku jako plik PNG na dysku. Bez zewnętrznych narzędzi, bez skomplikowanych trików w wierszu poleceń — po prostu czysty kod C#, który możesz wkleić do dowolnego projektu .NET. + +## What You’ll Learn + +- Jak **render webpage to PNG** przy użyciu klasy `HTMLDocument` z Aspose.HTML. +- Dokładne kroki, aby **set image size rendering**, tak aby wynik odpowiadał Twoim wymaganiom layoutu. +- Sposoby na **write image to file** w bezpieczny sposób, obsługując strumienie i ścieżki plików. +- Wskazówki dotyczące rozwiązywania typowych problemów, takich jak brakujące czcionki czy przekroczenia czasu sieciowego. + +### Prerequisites + +- .NET 6.0 lub nowszy (API działa także z .NET Framework, ale zalecany jest .NET 6+). +- Odwołanie do pakietu NuGet Aspose.HTML for .NET (`Aspose.Html`). +- Podstawowa znajomość C# i async/await (opcjonalnie, ale pomocna). + +Jeśli już to masz, możesz od razu rozpocząć konwersję HTML do obrazu. + +## Step 1: Load the Web Page – The Foundation of Converting HTML to Image + +Before any rendering can happen, you need an `HTMLDocument` instance that represents the page you want to capture. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Why this matters:* The `HTMLDocument` parses the HTML, resolves CSS, and builds the DOM. If the document can’t load (e.g., network issue), the subsequent rendering will produce a blank image. Always verify the URL is reachable before moving on. + +## Step 2: Set Image Size Rendering – Controlling Width, Height, and Quality + +Aspose.HTML lets you fine‑tune the output dimensions with `ImageRenderingOptions`. This is where you **set image size rendering** to match your target layout. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Pro tip:* If you omit `Width` and `Height`, Aspose.HTML will use the page’s intrinsic size, which can be unpredictable for responsive designs. Specifying explicit dimensions ensures your **save HTML as PNG** output looks exactly how you expect. + +## Step 3: Write Image to File – Persisting the Rendered PNG + +Now that the document is ready and the rendering options are set, you can finally **write image to file**. Using a `FileStream` guarantees the file is created safely, even if the folder doesn’t exist yet. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +After this block runs, you’ll find `page.png` at the location you specified. You’ve just **rendered webpage to PNG** and written it to disk in a single, straightforward operation. + +### Expected Result + +Open `C:\Temp\page.png` with any image viewer. You should see a faithful snapshot of `https://example.com`, rendered at 1024 × 768 pixels with smooth edges thanks to antialiasing. If the page contains dynamic content (e.g., JavaScript‑generated elements), they’ll be captured as long as the DOM is fully loaded before rendering. + +## Step 4: Handling Edge Cases – Fonts, Authentication, and Large Pages + +While the basic flow works for most public sites, real‑world scenarios often throw curveballs: + +| Situation | What to Do | +|-----------|------------| +| **Custom fonts not loading** | Embed the font files locally and set `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Pages behind authentication** | Use `HTMLDocument` overload that accepts `HttpWebRequest` with cookies or tokens. | +| **Very tall pages** | Increase `Height` or enable `PageScaling` in `ImageRenderingOptions` to avoid truncation. | +| **Memory usage spikes** | Render in chunks using `RenderToImage` overload that accepts a `Rectangle` region. | + +Addressing these *write image to file* nuances ensures your `convert html to image` pipeline stays robust in production. + +## Step 5: Full Working Example – Copy‑Paste Ready + +Below is the entire program, ready to compile. It includes all the steps, error handling, and comments you need. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Run this program, and you’ll see the confirmation message in the console. The PNG file will be exactly what you’d expect when you **render webpage to PNG** manually in a browser and take a screenshot—only faster and fully automated. + +## Frequently Asked Questions + +**Q: Can I convert a local HTML file instead of a URL?** +Absolutely. Just replace the URL with a file path: `new HTMLDocument(@"C:\myPage.html")`. + +**Q: Do I need a license for Aspose.HTML?** +A free evaluation license works for development and testing. For production, purchase a license to remove the evaluation watermark. + +**Q: What if the page uses JavaScript to load content after the initial load?** +Aspose.HTML executes JavaScript synchronously during parsing, but long‑running scripts might need a manual delay. You can use `HTMLDocument.WaitForReadyState` before rendering. + +## Conclusion + +You now have a solid, end‑to‑end solution to **convert HTML to image** in C#. By following the steps above you can **save HTML as PNG**, precisely **set image size rendering**, and confidently **write image to file** on any Windows or Linux environment. + +From simple screenshots to automated report generation, this technique scales nicely. Next, try experimenting with other output formats like JPEG or BMP, or integrate the code into an ASP.NET Core API that returns the PNG directly to callers. The possibilities are practically endless. + +Happy coding, and may your rendered images always look pixel‑perfect! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/polish/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..24915e311 --- /dev/null +++ b/html/polish/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-03-21 +description: Szybko twórz PDF z HTML przy użyciu Aspose HTML. Dowiedz się, jak renderować + HTML do PDF, konwertować HTML na PDF oraz jak używać Aspose w zwięzłym samouczku. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: pl +og_description: Utwórz PDF z HTML przy użyciu Aspose w C#. Ten przewodnik pokazuje, + jak renderować HTML do PDF, konwertować HTML na PDF oraz jak skutecznie korzystać + z Aspose. +og_title: Utwórz PDF z HTML – Kompletny samouczek Aspose C# +tags: +- Aspose +- C# +- PDF generation +title: Tworzenie PDF z HTML przy użyciu Aspose – Przewodnik krok po kroku w C# +url: /pl/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utwórz PDF z HTML przy użyciu Aspose – Przewodnik krok po kroku w C# + +Czy kiedykolwiek potrzebowałeś **create PDF from HTML**, ale nie byłeś pewien, która biblioteka zapewni wyniki piksel‑perfekcyjne? Nie jesteś sam. Wielu programistów napotyka problemy, gdy próbują przekształcić fragment strony internetowej w dokument do druku, kończąc z rozmytym tekstem lub zepsutymi układami. + +Dobrą wiadomością jest to, że Aspose HTML sprawia, że cały proces jest bezproblemowy. W tym samouczku przeprowadzimy Cię przez dokładny kod potrzebny do **render HTML to PDF**, wyjaśnimy, dlaczego każde ustawienie ma znaczenie, i pokażemy, jak **convert HTML to PDF** bez ukrytych sztuczek. Po zakończeniu będziesz wiedział **how to use Aspose** do niezawodnego generowania PDF w każdym projekcie .NET. + +## Wymagania wstępne – Co będziesz potrzebował przed rozpoczęciem + +- **.NET 6.0 lub nowszy** (przykład działa również na .NET Framework 4.7+) +- **Visual Studio 2022** lub dowolne IDE obsługujące C# +- **Aspose.HTML for .NET** pakiet NuGet (wersja próbna lub licencjonowana) +- Podstawowa znajomość składni C# (nie wymaga dogłębnej wiedzy o PDF) + +Jeśli masz te elementy, jesteś gotowy do startu. W przeciwnym razie pobierz najnowszy .NET SDK i zainstaluj pakiet NuGet za pomocą: + +```bash +dotnet add package Aspose.HTML +``` + +Ta pojedyncza linia pobiera wszystko, czego potrzebujesz do konwersji **aspose html to pdf**. + +--- + +## Krok 1: Skonfiguruj projekt, aby utworzyć PDF z HTML + +Pierwszą rzeczą, którą robisz, jest stworzenie nowej aplikacji konsolowej (lub włączenie kodu do istniejącej usługi). Oto minimalny szkielet `Program.cs`: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** Jeśli widzisz `Aspise.Html.Rendering.Text` w starszych przykładach, zamień go na `Aspose.Html.Rendering.Text`. Literówka spowoduje błąd kompilacji. + +Posiadanie prawidłowych przestrzeni nazw zapewnia, że kompilator może odnaleźć klasę **TextOptions**, której będziemy potrzebować później. + +## Krok 2: Zbuduj dokument HTML (Render HTML to PDF) + +Teraz tworzymy źródłowy HTML. Aspose pozwala przekazać surowy ciąg znaków, ścieżkę do pliku lub nawet URL. Dla tej demonstracji zachowamy prostotę: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Dlaczego przekazać ciąg znaków? Unika to operacji I/O na systemie plików, przyspiesza konwersję i gwarantuje, że HTML widziany w kodzie jest dokładnie tym, co zostanie wyrenderowane. Jeśli wolisz ładować z pliku, po prostu zamień argument konstruktora na URI pliku. + +## Krok 3: Dostosuj renderowanie tekstu (Convert HTML to PDF with Better Quality) + +Renderowanie tekstu często decyduje o tym, czy Twój PDF wygląda ostro czy rozmycie. Aspose udostępnia klasę `TextOptions`, która pozwala włączyć podpikselowe podpowiedzi — niezbędne przy wyjściu wysokiej rozdzielczości DPI. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Włączenie `UseHinting` jest szczególnie przydatne, gdy źródłowy HTML zawiera niestandardowe czcionki lub małe rozmiary czcionek. Bez tego możesz zauważyć ząbkowane krawędzie w finalnym PDF. + +## Krok 4: Dołącz opcje tekstu do konfiguracji renderowania PDF (How to Use Aspose) + +Następnie wiążemy te opcje tekstu z renderem PDF. To właśnie miejsce, w którym **aspose html to pdf** naprawdę błyszczy — wszystko od rozmiaru strony po kompresję można dostosować. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Możesz pominąć `PageSetup`, jeśli domyślny rozmiar A4 Ci odpowiada. Najważniejsze jest to, że obiekt `TextOptions` znajduje się wewnątrz `PdfRenderingOptions`, i w ten sposób informujesz Aspose *jak* renderować tekst. + +## Krok 5: Renderuj HTML i zapisz PDF (Convert HTML to PDF) + +Na koniec przesyłamy wyjście do pliku. Użycie bloku `using` zapewnia, że uchwyt pliku zostanie prawidłowo zamknięty, nawet w przypadku wystąpienia wyjątku. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Po uruchomieniu programu znajdziesz `output.pdf` obok pliku wykonywalnego. Otwórz go, a zobaczysz czysty nagłówek i akapit — dokładnie tak, jak zdefiniowano w ciągu HTML. + +### Oczekiwany wynik + +![przykładowy wynik pdf z html](https://example.com/images/pdf-output.png "przykładowy wynik pdf z html") + +*Zrzut ekranu pokazuje wygenerowany PDF z nagłówkiem „Hello, Aspose!” wyświetlonym wyraźnie dzięki podpowiedziom tekstowym.* + +--- + +## Częste pytania i przypadki brzegowe + +### 1. Co zrobić, jeśli mój HTML odwołuje się do zewnętrznych zasobów (obrazy, CSS)? + +Aspose rozwiązuje względne URL‑e na podstawie bazowego URI dokumentu. Jeśli podajesz surowy ciąg, ustaw bazowy URI ręcznie: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Teraz każde `` będzie wyszukiwane względem `C:/MyProject/`. + +### 2. Jak osadzić czcionki, które nie są zainstalowane na serwerze? + +Dodaj blok ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Krok 4: Skonfiguruj opcje zapisu, aby używać Custom Storage + +`HtmlSaveOptions` pozwala nam powiedzieć Aspose, aby spakował wszystko do pliku ZIP. Właściwość `OutputStorage` (legacy) przyjmuje naszą instancję `MyStorage`. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Uwaga:** W Aspose HTML 23.9+ właściwość nazywa się `OutputStorage`, ale jest oznaczona jako przestarzała. Nowoczesną alternatywą jest `ZipOutputStorage`. Poniższy kod działa z obiema, ponieważ interfejs jest taki sam. + +### Krok 5: Zapisz dokument jako archiwum ZIP + +Wybierz docelowy folder (lub strumień) i pozwól Aspose wykonać ciężką pracę. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Po zakończeniu programu znajdziesz `output.zip` zawierający: + +* `index.html` – główny dokument. +* Wszelkie osadzone obrazy, pliki CSS lub skrypty (jeśli Twój HTML je odwołuje). + +Możesz otworzyć ZIP dowolnym menedżerem archiwów, aby zweryfikować strukturę. + +## Weryfikacja wyniku (opcjonalnie) + +Jeśli chcesz programowo sprawdzić archiwum bez wypakowywania go na dysk: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Typowy wynik: + +``` +- index.html (452 bytes) +``` + +Jeśli miałbyś obrazy lub CSS, pojawiłyby się jako dodatkowe wpisy. To szybkie sprawdzenie potwierdza, że **create html zip archive** działało zgodnie z oczekiwaniami. + +## Częste pytania i przypadki brzegowe + +| Pytanie | Odpowiedź | +|----------|--------| +| **Co jeśli muszę zapisać ZIP bezpośrednio do strumienia odpowiedzi?** | Zwróć `MemoryStream` uzyskany z `MyStorage` po `document.Save`. Rzutuj go na `byte[]` i zapisz do `HttpResponse.Body`. | +| **Mój HTML odwołuje się do zewnętrznych URL‑ów — czy zostaną pobrane?** | Nie. Aspose pakuje tylko zasoby, które są *osadzone* (np. `` lub pliki lokalne). Dla zdalnych zasobów musisz je najpierw pobrać i dostosować znacznik. | +| **Właściwość `OutputStorage` jest oznaczona jako przestarzała — czy powinienem ją ignorować?** | Wciąż działa, ale nowsza `ZipOutputStorage` oferuje to samo API pod inną nazwą. Zamień `OutputStorage` na `ZipOutputStorage`, jeśli chcesz kompilację bez ostrzeżeń. | +| **Czy mogę zaszyfrować ZIP?** | Tak. Po zapisaniu otwórz plik za pomocą `System.IO.Compression.ZipArchive` i ustaw hasło przy użyciu bibliotek zewnętrznych, takich jak `SharpZipLib`. Aspose samo nie zapewnia szyfrowania. | + +## Pełny działający przykład (kopiuj‑wklej) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Uruchom program, otwórz `output.zip`, i zobaczysz pojedynczy plik `index.html`, który wyświetla nagłówek „Hello from ZIP!” po otwarciu w przeglądarce. + +## Podsumowanie + +Teraz wiesz **jak zapisać HTML jako ZIP** w C# używając klasy **custom storage**, jak **wyeksportować HTML do ZIP**, oraz jak **utworzyć archiwum HTML zip**, które jest gotowe do dystrybucji. Wzorzec jest elastyczny — zamień `MemoryStream` na strumień w chmurze, dodaj szyfrowanie lub zintegrować go z API webowym, które zwraca ZIP na żądanie. Nie ma ograniczeń, gdy połączysz możliwości ZIP Aspose.HTML z własną logiką przechowywania. + +Gotowy na kolejny krok? Spróbuj podać pełną stronę internetową z obrazami i stylami, lub podłączyć storage do Azure Blob Storage, aby całkowicie ominąć lokalny system plików. Nie ma granic, gdy łączysz możliwości ZIP Aspose.HTML z własną logiką przechowywania. + +Miłego kodowania i niech Twoje archiwa zawsze będą uporządkowane! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/portuguese/net/generate-jpg-and-png-images/_index.md b/html/portuguese/net/generate-jpg-and-png-images/_index.md index 25a4d8da7..c0d5e0f8f 100644 --- a/html/portuguese/net/generate-jpg-and-png-images/_index.md +++ b/html/portuguese/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aprenda a usar Aspose.HTML para .NET para manipular documentos HTML, converter H Aprenda a ativar antialiasing ao converter documentos DOCX em imagens PNG ou JPG usando Aspose.HTML para .NET. ### [Converter docx para png – criar arquivo zip em C# tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Aprenda a converter documentos DOCX em imagens PNG e compactá-los em um arquivo ZIP usando C# e Aspose.HTML. +### [Converter HTML para PNG – Guia completo em C# com exportação ZIP](./convert-html-to-png-full-c-guide-with-zip-export/) +Aprenda a converter HTML em PNG usando C#, gerar o PNG e exportá-lo em um arquivo ZIP com Aspose.HTML. ## Conclusão diff --git a/html/portuguese/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/portuguese/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..8ea217dfb --- /dev/null +++ b/html/portuguese/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Converter HTML para PNG e renderizar HTML como imagem enquanto salva + o HTML em um ZIP. Aprenda a aplicar estilo de fonte ao HTML e a adicionar negrito + aos elementos p em apenas alguns passos. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: pt +og_description: Converta HTML em PNG rapidamente. Este guia mostra como renderizar + HTML como imagem, salvar HTML em ZIP, aplicar estilo de fonte ao HTML e adicionar + negrito aos elementos p. +og_title: Converter HTML para PNG – Tutorial Completo de C# +tags: +- Aspose +- C# +title: Converter HTML para PNG – Guia Completo de C# com Exportação ZIP +url: /pt/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converter HTML para PNG – Guia Completo em C# com Exportação ZIP + +Já precisou **converter HTML para PNG** mas não sabia qual biblioteca faria isso sem precisar de um navegador headless? Você não está sozinho. Em muitos projetos—miniaturas de e‑mail, pré‑visualizações de documentação ou imagens de visualização rápida—transformar uma página web em uma imagem estática é uma necessidade real. + +A boa notícia? Com Aspose.HTML você pode **renderizar HTML como imagem**, ajustar a marcação em tempo real e até **salvar HTML em ZIP** para distribuição posterior. Neste tutorial vamos percorrer um exemplo completo e executável que **aplica estilo de fonte HTML**, especificamente **adiciona negrito a elementos p**, antes de gerar um arquivo PNG. Ao final você terá uma única classe C# que faz tudo, desde carregar a página até arquivar seus recursos. + +## O que você vai precisar + +- .NET 6.0 ou superior (a API funciona também no .NET Core) +- Aspose.HTML para .NET 6+ (pacote NuGet `Aspose.Html`) +- Noções básicas de sintaxe C# (não são necessários conceitos avançados) + +É só isso. Sem navegadores externos, sem phantomjs, apenas código gerenciado puro. + +## Etapa 1 – Carregar o Documento HTML + +Primeiro trazemos o arquivo fonte (ou URL) para um objeto `HTMLDocument`. Esta etapa é a base tanto para **render html as image** quanto para **save html to zip** posteriormente. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Por que isso importa:* A classe `HTMLDocument` analisa a marcação, constrói um DOM e resolve recursos vinculados (CSS, imagens, fontes). Sem um objeto de documento adequado você não pode manipular estilos nem renderizar nada. + +## Etapa 2 – Aplicar Estilo de Fonte HTML (Adicionar Negrito a p) + +Agora vamos **aplicar estilo de fonte HTML** percorrendo cada elemento `

` e definindo seu `font-weight` como bold. Esta é a forma programática de **add bold to p** sem tocar no arquivo original. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Dica de especialista:* Se precisar negritar apenas um subconjunto, altere o seletor para algo mais específico, por exemplo, `"p.intro"`. + +## Etapa 3 – Renderizar HTML como Imagem (Converter HTML para PNG) + +Com o DOM pronto, configuramos `ImageRenderingOptions` e chamamos `RenderToImage`. É aqui que a mágica de **convert html to png** acontece. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Por que as opções são importantes:* Definir largura/altura fixas impede que a saída fique muito grande, enquanto o antialiasing proporciona um resultado visual mais suave. Você também pode trocar `options` para `ImageFormat.Jpeg` se preferir um arquivo menor. + +## Etapa 4 – Salvar HTML em ZIP (Agrupar Recursos) + +Frequentemente é necessário distribuir o HTML original junto com seu CSS, imagens e fontes. O `ZipArchiveSaveOptions` da Aspose.HTML faz exatamente isso. Também conectamos um `ResourceHandler` personalizado para que todos os ativos externos sejam gravados na mesma pasta do arquivo ZIP. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Caso especial:* Se seu HTML referenciar imagens remotas que exigem autenticação, o manipulador padrão falhará. Nesse cenário você pode estender `MyResourceHandler` para injetar cabeçalhos HTTP. + +## Etapa 5 – Integrar Tudo em uma Única Classe Conversora + +A seguir está a classe completa, pronta‑para‑executar, que une todas as etapas anteriores. Basta copiar‑colar em um aplicativo console, chamar `Convert` e observar os arquivos sendo gerados. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Saída Esperada + +Após executar o trecho acima você encontrará dois arquivos em `outputDirectory`: + +| Arquivo | Descrição | +|------|-------------| +| `page.png` | Renderização PNG 1200 × 800 do HTML de origem, com cada parágrafo exibido em **negrito**. | +| `archive.zip` | Pacote ZIP contendo o `input.html` original, seu CSS, imagens e quaisquer web‑fonts – perfeito para distribuição offline. | + +Você pode abrir `page.png` em qualquer visualizador de imagens para verificar se o estilo negrito foi aplicado e extrair `archive.zip` para ver o HTML intacto junto aos seus recursos. + +## Perguntas Frequentes & Armadilhas + +- **E se o HTML contiver JavaScript?** + Aspose.HTML **não** executa scripts durante a renderização, portanto conteúdo dinâmico não aparecerá. Para páginas totalmente renderizadas você precisaria de um navegador headless, mas para templates estáticos essa abordagem é mais rápida e leve. + +- **Posso mudar o formato de saída para JPEG ou BMP?** + Sim—basta trocar a propriedade `ImageFormat` de `ImageRenderingOptions`, por exemplo, `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Preciso descartar manualmente o `HTMLDocument`?** + A classe implementa `IDisposable`. Em um serviço de longa execução, envolva-a em um bloco `using` ou chame `document.Dispose()` após o uso. + +- **Como funciona o `MyResourceHandler` personalizado?** + Ele recebe cada recurso externo (CSS, imagens, fontes) e grava na pasta que você especificar. Isso garante que o ZIP contenha uma cópia fiel de tudo que o HTML referencia. + +## Conclusão + +Agora você tem uma solução compacta e pronta para produção que **convert html to png**, **render html as image**, **save html to zip**, **apply font style html** e **add bold to p**—tudo em poucas linhas de C#. O código é autônomo, funciona com .NET 6+ e pode ser inserido em qualquer serviço backend que precise de snapshots visuais rápidos de conteúdo web. + +Pronto para o próximo passo? Experimente alterar o tamanho de renderização, teste outras propriedades CSS (como `font-family` ou `color`) ou integre este conversor em um endpoint ASP.NET Core que retorne o PNG sob demanda. As possibilidades são infinitas, e com Aspose.HTML você evita dependências pesadas de navegadores. + +Se encontrou algum obstáculo ou tem ideias para extensões, deixe um comentário abaixo. Feliz codificação! + +![exemplo de conversão de html para png](example.png "exemplo de conversão de html para png") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/portuguese/net/html-document-manipulation/_index.md b/html/portuguese/net/html-document-manipulation/_index.md index df151c49f..3679887cf 100644 --- a/html/portuguese/net/html-document-manipulation/_index.md +++ b/html/portuguese/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aprenda a usar Aspose.HTML para .NET. Importe namespace, mescle HTML com XML e a Desbloqueie o potencial do desenvolvimento web com Aspose.HTML para .NET. Crie, converta e manipule documentos HTML facilmente. ### [Criar HTML a partir de String em C# – Guia de Manipulador de Recurso Personalizado](./create-html-from-string-in-c-custom-resource-handler-guide/) Aprenda a gerar documentos HTML a partir de strings usando um manipulador de recurso personalizado em C# com Aspose.HTML. +### [Criar documento HTML em C# – Guia passo a passo](./create-html-document-c-step-by-step-guide/) +Aprenda a criar documentos HTML em C# usando Aspose.HTML com instruções detalhadas passo a passo. ## Conclusão diff --git a/html/portuguese/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/portuguese/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..af15500ab --- /dev/null +++ b/html/portuguese/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: Criar documento HTML em C# e aprender como obter elemento por ID, localizar + elemento por ID, alterar o estilo do elemento HTML e adicionar negrito itálico usando + Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: pt +og_description: Crie um documento HTML em C# e aprenda instantaneamente a obter elemento + por id, localizar elemento por id, alterar o estilo do elemento HTML e adicionar + negrito e itálico com exemplos de código claros. +og_title: Criar Documento HTML C# – Guia Completo de Programação +tags: +- Aspose.Html +- C# +- DOM manipulation +title: Criar Documento HTML C# – Guia Passo a Passo +url: /pt/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crie um Documento HTML em C# – Guia Passo a Passo + +Já precisou **criar um documento HTML em C#** do zero e depois ajustar a aparência de um único parágrafo? Você não está sozinho. Em muitos projetos de automação web você gera um arquivo HTML, localiza uma tag pelo seu ID e então aplica algum estilo—geralmente negrito + itálico—sem nunca tocar em um navegador. + +Neste tutorial vamos percorrer exatamente isso: vamos criar um documento HTML em C#, **obter elemento por id**, **localizar elemento por id**, **alterar o estilo do elemento HTML**, e finalmente **adicionar negrito itálico** usando a biblioteca Aspose.Html. Ao final você terá um trecho totalmente executável que pode ser inserido em qualquer projeto .NET. + +## O que Você Precisa + +- .NET 6 ou superior (o código também funciona no .NET Framework 4.7+) +- Visual Studio 2022 (ou qualquer editor de sua preferência) +- O pacote NuGet **Aspose.Html** (`Install-Package Aspose.Html`) + +É só isso—nenhum arquivo HTML extra, nenhum servidor web, apenas algumas linhas de C#. + +## Crie um Documento HTML em C# – Inicialize o Documento + +Primeiro de tudo: você precisa de um objeto `HTMLDocument` ativo que o motor Aspose.Html possa manipular. Pense nisso como abrir um caderno novo onde você escreverá sua marcação. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Por que isso importa:** Ao passar a string bruta para `HTMLDocument`, você evita lidar com I/O de arquivos e mantém tudo na memória—perfeito para testes unitários ou geração on‑the‑fly. + +## Obter Elemento por ID – Encontrando o Parágrafo + +Agora que o documento existe, precisamos **obter elemento por id**. A API DOM fornece `GetElementById`, que retorna uma referência `IElement` ou `null` se o ID não estiver presente. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Dica de especialista:** Mesmo que nossa marcação seja pequena, adicionar uma verificação de nulo evita dores de cabeça quando a mesma lógica é reutilizada em páginas maiores e dinâmicas. + +## Localizar Elemento por ID – Uma Abordagem Alternativa + +Às vezes você já tem uma referência à raiz do documento e prefere uma busca estilo consulta. Usar seletores CSS (`QuerySelector`) é outra forma de **localizar elemento por id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **Quando usar cada um?** `GetElementById` é marginalmente mais rápido porque faz uma busca direta por hash. `QuerySelector` se destaca quando você precisa de seletores complexos (ex.: `div > p.highlight`). + +## Alterar o Estilo do Elemento HTML – Adicionando Negrito Itálico + +Com o elemento em mãos, o próximo passo é **alterar o estilo do elemento HTML**. Aspose.Html expõe um objeto `Style` onde você pode ajustar propriedades CSS ou usar a prática enumeração `WebFontStyle` para aplicar múltiplas características de fonte de uma vez. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Essa única linha define `font-weight` como `bold` e `font-style` como `italic`. Nos bastidores, Aspose.Html converte a enumeração na string CSS apropriada. + +### Exemplo Completo Funcionando + +Juntando todas as peças, obtemos um programa compacto e autocontido que você pode compilar e executar imediatamente: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Saída esperada** + +``` +Rendered HTML: +

Hello world

+``` + +A tag `

` agora possui um atributo `style` inline que deixa o texto tanto em negrito quanto em itálico—exatamente o que queríamos. + +## Casos Limite & Armadilhas Comuns + +| Situação | O que observar | Como lidar | +|-----------|-------------------|---------------| +| **ID não existe** | `GetElementById` retorna `null`. | Lance uma exceção ou recorra a um elemento padrão. | +| **Múltiplos elementos compartilham o mesmo ID** | A especificação HTML exige IDs únicos, mas páginas reais às vezes quebram a regra. | `GetElementById` devolve a primeira correspondência; considere usar `QuerySelectorAll` se precisar tratar duplicatas. | +| **Conflitos de estilo** | Estilos inline existentes podem ser sobrescritos. | Anexe ao objeto `Style` em vez de definir a string completa: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Renderização em navegador** | Alguns navegadores ignoram `WebFontStyle` se o elemento já possuir uma classe CSS com maior especificidade. | Use `!important` via `paragraph.Style.SetProperty("font-weight", "bold", "important");` se necessário. | + +## Dicas de Especialista para Projetos Reais + +- **Cache o documento** se você estiver processando muitos elementos; criar um novo `HTMLDocument` para cada pequeno trecho pode prejudicar o desempenho. +- **Combine alterações de estilo** em uma única transação `Style` para evitar múltiplos reflows do DOM. +- **Aproveite o motor de renderização do Aspose.Html** para exportar o documento final como PDF ou imagem—ótimo para ferramentas de relatório. + +## Confirmação Visual (Opcional) + +Se preferir ver o resultado em um navegador, você pode salvar a string renderizada em um arquivo `.html`: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Abra `output.html` e verá **Hello world** exibido em negrito + itálico. + +![Create HTML Document C# example showing bold italic paragraph](/images/create-html-document-csharp.png "Create HTML Document C# – rendered output") + +*Texto alternativo: Exemplo de Criação de Documento HTML em C# – saída renderizada com texto em negrito itálico.* + +## Conclusão + +Acabamos de **criar um documento HTML em C#**, **obter elemento por id**, **localizar elemento por id**, **alterar o estilo do elemento HTML**, e finalmente **adicionar negrito itálico**—tudo com poucas linhas usando Aspose.Html. A abordagem é direta, funciona em qualquer ambiente .NET e escala para manipulações DOM maiores. + +Pronto para o próximo passo? Experimente substituir o `WebFontStyle` por outras enumerações como `Underline` ou combine vários estilos manualmente. Ou teste carregar um arquivo HTML externo e aplicar a mesma técnica a centenas de elementos. O céu é o limite, e agora você tem uma base sólida para construir. + +Bom código! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/portuguese/net/html-extensions-and-conversions/_index.md b/html/portuguese/net/html-extensions-and-conversions/_index.md index 8971d46a5..6fdaddfc9 100644 --- a/html/portuguese/net/html-extensions-and-conversions/_index.md +++ b/html/portuguese/net/html-extensions-and-conversions/_index.md @@ -43,6 +43,9 @@ Converta HTML para PDF sem esforço com Aspose.HTML para .NET. Siga nosso guia p ### [Criar PDF a partir de HTML – Guia passo a passo em C#](./create-pdf-from-html-c-step-by-step-guide/) Aprenda a criar um PDF a partir de HTML usando C# com Aspose.HTML, seguindo um guia passo a passo. +### [Criar PDF a partir de HTML com Aspose – Guia passo a passo em C#](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Aprenda a criar um PDF a partir de HTML usando Aspose em C# com um guia passo a passo. + ### [Criar documento HTML com texto estilizado e exportar para PDF – Guia completo](./create-html-document-with-styled-text-and-export-to-pdf-full/) Aprenda a criar um documento HTML com texto formatado e exportá-lo para PDF usando Aspose.HTML para .NET. Guia passo a passo. @@ -70,14 +73,23 @@ Descubra como usar Aspose.HTML para .NET para manipular e converter documentos H Aprenda como converter HTML para TIFF com Aspose.HTML para .NET. Siga nosso guia passo a passo para otimização eficiente de conteúdo web. ### [Converter HTML para XPS em .NET com Aspose.HTML](./convert-html-to-xps/) Descubra o poder do Aspose.HTML para .NET: Converta HTML para XPS sem esforço. Pré-requisitos, guia passo a passo e FAQs inclusos. +### [Converter HTML para Imagem em C# – Guia Completo](./convert-html-to-image-in-c-complete-guide/) +Aprenda a converter HTML em imagens usando C# com Aspose.HTML, seguindo um guia passo a passo completo. ### [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#. ### [Como compactar HTML em C# – Salvar HTML em ZIP](./how-to-zip-html-in-c-save-html-to-zip/) Aprenda a criar um arquivo ZIP contendo arquivos HTML usando Aspose.HTML para .NET em C#. + ### [Salvar HTML em ZIP em C# – Exemplo Completo em Memória](./save-html-to-zip-in-c-complete-in-memory-example/) Aprenda a salvar arquivos HTML em um arquivo ZIP usando C# com um exemplo completo totalmente em memória. +### [Salvar HTML como ZIP em C# – Guia Completo com Armazenamento Personalizado](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Aprenda a salvar documentos HTML em arquivos ZIP usando armazenamento personalizado com Aspose.HTML para .NET em C#. + +### [Como compactar HTML com Aspose.HTML – Guia Completo](./how-to-zip-html-with-aspose-html-complete-guide/) +Aprenda a compactar arquivos HTML em ZIP usando Aspose.HTML para .NET com um guia passo a passo completo. + ## Conclusão Concluindo, extensões e conversões HTML são elementos essenciais do desenvolvimento web moderno. O Aspose.HTML para .NET simplifica o processo e o torna acessível a desenvolvedores de todos os níveis. Ao seguir nossos tutoriais, você estará no caminho certo para se tornar um desenvolvedor web proficiente com um amplo conjunto de habilidades. diff --git a/html/portuguese/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/portuguese/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..83a43bc2f --- /dev/null +++ b/html/portuguese/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Converter HTML em imagem usando Aspose.HTML em C#. Aprenda como salvar + HTML como PNG, definir o tamanho de renderização da imagem e gravar a imagem em + um arquivo em apenas alguns passos. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: pt +og_description: Converta HTML em imagem rapidamente. Este guia mostra como salvar + HTML como PNG, definir o tamanho da renderização da imagem e gravar a imagem em + um arquivo com Aspose.HTML. +og_title: Converter HTML em Imagem em C# – Guia Passo a Passo +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Converter HTML em Imagem em C# – Guia Completo +url: /pt/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converter HTML em Imagem em C# – Guia Completo + +Já precisou **converter HTML em imagem** para uma miniatura de painel, uma pré‑visualização de e‑mail ou um relatório PDF? É um cenário que aparece mais vezes do que você imagina, especialmente quando você está lidando com conteúdo web dinâmico que precisa ser incorporado em outro lugar. + +A boa notícia? Com Aspose.HTML você pode **converter HTML em imagem** em apenas algumas linhas, e também aprenderá como *salvar HTML como PNG*, controlar as dimensões da saída e *escrever imagem em arquivo* sem esforço. + +Neste tutorial vamos percorrer tudo o que você precisa saber: desde carregar uma página remota até ajustar o tamanho de renderização e, finalmente, persistir o resultado como um arquivo PNG no disco. Sem ferramentas externas, sem truques complicados de linha de comando — apenas código C# puro que você pode inserir em qualquer projeto .NET. + +## O que você aprenderá + +- Como **renderizar página da web para PNG** usando a classe `HTMLDocument` da Aspose.HTML. +- As etapas exatas para **definir renderização de tamanho de imagem** para que a saída corresponda aos requisitos do seu layout. +- Como **escrever imagem em arquivo** com segurança, lidando com streams e caminhos de arquivo. +- Dicas para solucionar armadilhas comuns, como fontes ausentes ou tempos de espera de rede. + +### Pré-requisitos + +- .NET 6.0 ou superior (a API funciona também com .NET Framework, mas .NET 6+ é recomendado). +- Uma referência ao pacote NuGet Aspose.HTML for .NET (`Aspose.Html`). +- Familiaridade básica com C# e async/await (opcional, mas útil). + +Se você já tem isso, está pronto para começar a converter HTML em imagem imediatamente. + +## Etapa 1: Carregar a Página Web – A Base da Conversão de HTML em Imagem + +Antes que qualquer renderização possa acontecer, você precisa de uma instância `HTMLDocument` que represente a página que deseja capturar. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Por que isso importa:* O `HTMLDocument` analisa o HTML, resolve o CSS e constrói o DOM. Se o documento não puder ser carregado (por exemplo, problema de rede), a renderização subsequente produzirá uma imagem em branco. Sempre verifique se a URL está acessível antes de prosseguir. + +## Etapa 2: Definir Renderização de Tamanho de Imagem – Controlando Largura, Altura e Qualidade + +Aspose.HTML permite ajustar finamente as dimensões da saída com `ImageRenderingOptions`. É aqui que você **define a renderização de tamanho de imagem** para corresponder ao layout desejado. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Dica de especialista:* Se você omitir `Width` e `Height`, o Aspose.HTML usará o tamanho intrínseco da página, o que pode ser imprevisível para designs responsivos. Especificar dimensões explícitas garante que sua saída **salvar HTML como PNG** fique exatamente como você espera. + +## Etapa 3: Escrever Imagem em Arquivo – Persistindo o PNG Renderizado + +Agora que o documento está pronto e as opções de renderização definidas, você pode finalmente **escrever imagem em arquivo**. Usar um `FileStream` garante que o arquivo seja criado com segurança, mesmo que a pasta ainda não exista. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +Depois que este bloco for executado, você encontrará `page.png` no local especificado. Você acabou de **renderizar página da web para PNG** e gravá‑la no disco em uma única operação simples. + +### Resultado Esperado + +Abra `C:\Temp\page.png` com qualquer visualizador de imagens. Você deverá ver uma captura fiel de `https://example.com`, renderizada em 1024 × 768 pixels com bordas suaves graças ao antialiasing. Se a página contiver conteúdo dinâmico (por exemplo, elementos gerados por JavaScript), eles serão capturados desde que o DOM esteja totalmente carregado antes da renderização. + +## Etapa 4: Lidando com Casos de Borda – Fontes, Autenticação e Páginas Grandes + +Embora o fluxo básico funcione para a maioria dos sites públicos, cenários reais frequentemente apresentam desafios: + +| Situação | O que fazer | +|-----------|------------| +| **Custom fonts not loading** | Incorpore os arquivos de fonte localmente e defina `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Pages behind authentication** | Use a sobrecarga de `HTMLDocument` que aceita `HttpWebRequest` com cookies ou tokens. | +| **Very tall pages** | Aumente `Height` ou habilite `PageScaling` em `ImageRenderingOptions` para evitar truncamento. | +| **Memory usage spikes** | Renderize em partes usando a sobrecarga `RenderToImage` que aceita uma região `Rectangle`. | + +Abordar essas nuances de *escrever imagem em arquivo* garante que seu pipeline de `convert html to image` permaneça robusto em produção. + +## Etapa 5: Exemplo Completo Funcional – Pronto para Copiar‑Colar + +Abaixo está o programa completo, pronto para compilar. Ele inclui todas as etapas, tratamento de erros e comentários necessários. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Execute este programa e você verá a mensagem de confirmação no console. O arquivo PNG será exatamente o que você esperaria ao **renderizar página da web para PNG** manualmente em um navegador e tirar uma captura de tela — apenas mais rápido e totalmente automatizado. + +## Perguntas Frequentes + +**Q: Posso converter um arquivo HTML local em vez de uma URL?** +Claro. Basta substituir a URL por um caminho de arquivo: `new HTMLDocument(@"C:\myPage.html")`. + +**Q: Preciso de uma licença para Aspose.HTML?** +Uma licença de avaliação gratuita funciona para desenvolvimento e testes. Para produção, adquira uma licença para remover a marca d'água de avaliação. + +**Q: E se a página usar JavaScript para carregar conteúdo após o carregamento inicial?** +Aspose.HTML executa JavaScript de forma síncrona durante a análise, mas scripts de longa duração podem precisar de um atraso manual. Você pode usar `HTMLDocument.WaitForReadyState` antes da renderização. + +## Conclusão + +Agora você tem uma solução sólida, de ponta a ponta, para **converter HTML em imagem** em C#. Seguindo as etapas acima, você pode **salvar HTML como PNG**, definir com precisão **renderização de tamanho de imagem** e, com confiança, **escrever imagem em arquivo** em qualquer ambiente Windows ou Linux. + +De capturas de tela simples a geração automatizada de relatórios, esta técnica escala bem. Em seguida, experimente outros formatos de saída como JPEG ou BMP, ou integre o código em uma API ASP.NET Core que retorne o PNG diretamente aos chamadores. As possibilidades são praticamente infinitas. + +Feliz codificação, e que suas imagens renderizadas estejam sempre perfeitas em pixels! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/portuguese/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..5ddf2486a --- /dev/null +++ b/html/portuguese/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-03-21 +description: Crie PDF a partir de HTML rapidamente usando Aspose HTML. Aprenda a renderizar + HTML para PDF, converter HTML em PDF e como usar o Aspose em um tutorial conciso. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: pt +og_description: Crie PDF a partir de HTML com Aspose em C#. Este guia mostra como + renderizar HTML para PDF, converter HTML em PDF e como usar o Aspose de forma eficaz. +og_title: Criar PDF a partir de HTML – Tutorial Completo de Aspose C# +tags: +- Aspose +- C# +- PDF generation +title: Criar PDF a partir de HTML com Aspose – Guia passo a passo em C# +url: /pt/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar PDF a partir de HTML com Aspose – Guia passo a passo em C# + +Já precisou **criar PDF a partir de HTML** mas não tinha certeza de qual biblioteca lhe daria resultados perfeitos em pixel? Você não está sozinho. Muitos desenvolvedores tropeçam ao tentar transformar um trecho da web em um documento imprimível, acabando com texto borrado ou layouts quebrados. + +A boa notícia é que o Aspose HTML torna todo o processo indolor. Neste tutorial vamos percorrer o código exato que você precisa para **renderizar HTML para PDF**, explorar por que cada configuração importa e mostrar como **converter HTML para PDF** sem truques ocultos. Ao final, você saberá **como usar o Aspose** para geração confiável de PDFs em qualquer projeto .NET. + +## Pré-requisitos – O que você precisará antes de começar + +- **.NET 6.0 ou posterior** (o exemplo funciona também no .NET Framework 4.7+) +- **Visual Studio 2022** ou qualquer IDE que suporte C# +- **Aspose.HTML for .NET** pacote NuGet (versão de avaliação gratuita ou licenciada) +- Um entendimento básico da sintaxe C# (não é necessário conhecimento profundo de PDF) + +Se você tem isso, está pronto para começar. Caso contrário, obtenha o SDK .NET mais recente e instale o pacote NuGet com: + +```bash +dotnet add package Aspose.HTML +``` + +Essa única linha traz tudo que você precisa para a conversão **aspose html to pdf**. + +## Etapa 1: Configurar seu projeto para criar PDF a partir de HTML + +A primeira coisa a fazer é criar um novo aplicativo console (ou integrar o código em um serviço existente). Aqui está um esqueleto mínimo de `Program.cs`: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Dica profissional:** Se você vir `Aspise.Html.Rendering.Text` em exemplos antigos, substitua por `Aspose.Html.Rendering.Text`. O erro de digitação causará um erro de compilação. + +Usar os namespaces corretos garante que o compilador encontre a classe **TextOptions** que precisaremos mais adiante. + +## Etapa 2: Construir o documento HTML (Renderizar HTML para PDF) + +Agora criamos o HTML de origem. Aspose permite passar uma string bruta, um caminho de arquivo ou até uma URL. Para esta demonstração vamos manter simples: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Por que passar uma string? Isso evita I/O de sistema de arquivos, acelera a conversão e garante que o HTML que você vê no código seja exatamente o que será renderizado. Se preferir carregar de um arquivo, basta substituir o argumento do construtor por uma URI de arquivo. + +## Etapa 3: Ajustar a renderização de texto (Converter HTML para PDF com melhor qualidade) + +A renderização de texto costuma determinar se seu PDF fica nítido ou borrado. Aspose oferece a classe `TextOptions` que permite habilitar o sub‑pixel hinting — essencial para saída em alta DPI. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Habilitar `UseHinting` é especialmente útil quando o HTML de origem contém fontes personalizadas ou tamanhos de fonte pequenos. Sem isso, você pode notar bordas serrilhadas no PDF final. + +## Etapa 4: Anexar opções de texto à configuração de renderização PDF (Como usar o Aspose) + +Em seguida, vinculamos essas opções de texto ao renderizador PDF. É aqui que **aspose html to pdf** realmente se destaca — tudo, desde tamanho da página até compressão, pode ser ajustado. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Você pode omitir `PageSetup` se estiver satisfeito com o tamanho A4 padrão. O ponto principal é que o objeto `TextOptions` vive dentro de `PdfRenderingOptions`, e é assim que você indica ao Aspose *como* renderizar o texto. + +## Etapa 5: Renderizar o HTML e salvar o PDF (Converter HTML para PDF) + +Finalmente, transmitimos a saída para um arquivo. Usar um bloco `using` garante que o manipulador de arquivo seja fechado corretamente, mesmo se ocorrer uma exceção. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Ao executar o programa, você encontrará `output.pdf` ao lado do executável. Abra-o, e deverá ver um título e parágrafo limpos — exatamente como definidos na string HTML. + +### Saída esperada + +![create pdf from html example output](https://example.com/images/pdf-output.png "create pdf from html example output") + +*The screenshot shows the generated PDF with the heading “Hello, Aspose!” rendered sharply thanks to text hinting.* + +## Perguntas comuns e casos extremos + +### 1. E se meu HTML referenciar recursos externos (imagens, CSS)? + +Aspose resolve URLs relativas com base na URI base do documento. Se você estiver fornecendo uma string bruta, defina a URI base manualmente: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Agora qualquer `` será buscado relativo a `C:/MyProject/`. + +### 2. Como incorporar fontes que não estão instaladas no servidor? + +Adicione um bloco ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Passo 4: Configurar as Opções de Salvamento para Usar o Armazenamento Personalizado + +`HtmlSaveOptions` permite dizer ao Aspose para empacotar tudo em um arquivo ZIP. A propriedade `OutputStorage` (legado) recebe nossa instância `MyStorage`. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Observação:** No Aspose HTML 23.9+ a propriedade se chama `OutputStorage`, mas está marcada como obsoleta. A alternativa moderna é `ZipOutputStorage`. O código abaixo funciona com ambas porque a interface é a mesma. + +### Passo 5: Salvar o Documento como um Arquivo ZIP + +Escolha uma pasta de destino (ou um stream) e deixe o Aspose fazer o trabalho pesado. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Quando o programa terminar, você encontrará `output.zip` contendo: + +* `index.html` – o documento principal. +* Quaisquer imagens incorporadas, arquivos CSS ou scripts (se seu HTML os referenciar). + +Você pode abrir o ZIP com qualquer gerenciador de arquivos para verificar a estrutura. + +--- + +## Verificando o Resultado (Opcional) + +Se quiser inspecionar programaticamente o arquivo sem extraí‑lo para o disco: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Saída típica: + +``` +- index.html (452 bytes) +``` + +Se houver imagens ou CSS, eles aparecerão como entradas adicionais. Essa verificação rápida confirma que **create html zip archive** funcionou como esperado. + +--- + +## Perguntas Frequentes & Casos de Borda + +| Pergunta | Resposta | +|----------|----------| +| **E se eu precisar gravar o ZIP diretamente em um stream de resposta?** | Retorne o `MemoryStream` obtido de `MyStorage` após `document.Save`. Converta‑o para `byte[]` e escreva em `HttpResponse.Body`. | +| **Meu HTML referencia URLs externas — elas serão baixadas?** | Não. O Aspose só empacota recursos que estão *incorporados* (ex.: `` ou arquivos locais). Para ativos remotos, você deve baixá‑los primeiro e ajustar o markup. | +| **A propriedade `OutputStorage` está obsoleta — devo ignorá‑la?** | Ela ainda funciona, mas a nova `ZipOutputStorage` oferece a mesma API com nome diferente. Substitua `OutputStorage` por `ZipOutputStorage` se quiser uma compilação sem avisos. | +| **Posso criptografar o ZIP?** | Sim. Após salvar, abra o arquivo com `System.IO.Compression.ZipArchive` e defina uma senha usando bibliotecas de terceiros como `SharpZipLib`. O Aspose não fornece criptografia. | + +--- + +## Exemplo Completo Funcional (Copiar‑Colar) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Execute o programa, abra `output.zip` e você verá um único arquivo `index.html` que exibe o título “Hello from ZIP!” quando aberto em um navegador. + +--- + +## Conclusão + +Agora você sabe **como salvar HTML como ZIP** em C# usando uma **classe de armazenamento personalizada**, como **exportar HTML para ZIP** e como **criar um arquivo zip de HTML** pronto para distribuição. O padrão é flexível — troque `MemoryStream` por um stream de nuvem, adicione criptografia ou integre‑o a uma API web que retorne o ZIP sob demanda. + +Pronto para o próximo passo? Experimente alimentar uma página web completa com imagens e estilos, ou conecte o armazenamento ao Azure Blob Storage para eliminar totalmente o uso do sistema de arquivos local. O céu é o limite quando você combina as capacidades de ZIP do Aspose.HTML com sua própria lógica de armazenamento. + +Happy coding, and may your archives always be tidy! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/russian/net/generate-jpg-and-png-images/_index.md b/html/russian/net/generate-jpg-and-png-images/_index.md index 74f005949..f88e31770 100644 --- a/html/russian/net/generate-jpg-and-png-images/_index.md +++ b/html/russian/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML для .NET предлагает простой метод прео Узнайте, как включить сглаживание при преобразовании DOCX в PNG или JPG с помощью Aspose.HTML для .NET. ### [Конвертация DOCX в PNG – создание ZIP-архива на C#](./convert-docx-to-png-create-zip-archive-c-tutorial/) Узнайте, как преобразовать файлы DOCX в PNG и упаковать их в ZIP-архив с помощью C# и Aspose.HTML. +### [Конвертация HTML в PNG – Полное руководство на C# с экспортом в ZIP](./convert-html-to-png-full-c-guide-with-zip-export/) +Подробное руководство по конвертации HTML в PNG с использованием C# и сохранением результатов в ZIP-архив. ## Заключение diff --git a/html/russian/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/russian/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..5c969cb7d --- /dev/null +++ b/html/russian/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Преобразуйте HTML в PNG и отобразите HTML как изображение, одновременно + сохраняя HTML в ZIP. Научитесь применять стили шрифтов в HTML и добавлять полужирное + начертание к элементам 

всего за несколько шагов. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: ru +og_description: Быстро преобразуйте HTML в PNG. В этом руководстве показано, как отобразить + HTML как изображение, сохранить HTML в ZIP, применить стиль шрифта к HTML и добавить + полужирный шрифт к элементам p. +og_title: Конвертировать HTML в PNG – Полный учебник по C# +tags: +- Aspose +- C# +title: Преобразовать HTML в PNG – Полное руководство по C# с экспортом в ZIP +url: /ru/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convert HTML to PNG – Full C# Guide with ZIP Export + +Когда‑то вам нужно было **преобразовать HTML в PNG**, но вы не знали, какая библиотека справится без использования безголового браузера? Вы не одиноки. Во многих проектах — миниатюры писем, превью документации или быстрые изображения — превращение веб‑страницы в статическое изображение является реальной потребностью. + +Хорошие новости? С Aspose.HTML вы можете **рендерить HTML как изображение**, изменять разметку «на лету» и даже **сохранять HTML в ZIP** для последующего распространения. В этом руководстве мы пройдём полный, готовый к запуску пример, который **применяет стили шрифтов к HTML**, а именно **добавляет жирный шрифт к элементам p**, перед тем как создать PNG‑файл. К концу вы получите один класс C#, который делает всё: от загрузки страницы до архивации её ресурсов. + +## Что понадобится + +- .NET 6.0 или новее (API работает и на .NET Core) +- Aspose.HTML для .NET 6+ (NuGet‑пакет `Aspose.Html`) +- Базовое понимание синтаксиса C# (никаких продвинутых концепций) + +Вот и всё. Никаких внешних браузеров, ни phantomjs, только чистый управляемый код. + +## Шаг 1 – Загрузка HTML‑документа + +Сначала мы загружаем исходный файл (или URL) в объект `HTMLDocument`. Этот шаг является основой как для **render html as image**, так и для **save html to zip** позже. + +```csharp +using Aspose.Html; +using System.IO; + +///

+/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Почему это важно:* Класс `HTMLDocument` разбирает разметку, строит DOM и разрешает связанные ресурсы (CSS, изображения, шрифты). Без корректного объекта документа вы не сможете менять стили или выполнять рендеринг. + +## Шаг 2 – Применить стили шрифтов к HTML (Добавить жирный к p) + +Теперь мы **применяем стили шрифтов к HTML**, проходя по каждому элементу `

` и устанавливая его `font-weight` в значение bold. Это программный способ **add bold to p** без изменения оригинального файла. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Совет:* Если нужно сделать жирным только часть абзацев, измените селектор на более специфичный, например, `"p.intro"`. + +## Шаг 3 – Рендеринг HTML в изображение (Convert HTML to PNG) + +Когда DOM готов, мы настраиваем `ImageRenderingOptions` и вызываем `RenderToImage`. Здесь происходит магия **convert html to png**. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Почему параметры важны:* Установка фиксированной ширины/высоты предотвращает слишком большой вывод, а сглаживание (antialiasing) делает изображение визуально более плавным. При желании можно переключить `options` на `ImageFormat.Jpeg`, если нужен меньший размер файла. + +## Шаг 4 – Сохранить HTML в ZIP (Bundle Resources) + +Часто требуется отправить оригинальный HTML вместе с его CSS, изображениями и шрифтами. `ZipArchiveSaveOptions` от Aspose.HTML делает именно это. Мы также подключаем пользовательский `ResourceHandler`, чтобы все внешние ресурсы записывались в ту же папку, что и архив. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Особый случай:* Если ваш HTML ссылается на удалённые изображения, требующие аутентификации, стандартный обработчик не справится. В таком случае можно расширить `MyResourceHandler`, чтобы добавить HTTP‑заголовки. + +## Шаг 5 – Связать всё в одном классе‑конвертере + +Ниже представлен полный, готовый к запуску класс, который объединяет все предыдущие шаги. Скопируйте‑вставьте его в консольное приложение, вызовите `Convert` и наблюдайте, как появляются файлы. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Ожидаемый результат + +После выполнения фрагмента кода выше вы найдёте два файла в `outputDirectory`: + +| File | Description | +|------|-------------| +| `page.png` | PNG‑изображение 1200 × 800, полученное из исходного HTML, где каждый абзац отображён **жирным**. | +| `archive.zip` | ZIP‑пакет, содержащий оригинальный `input.html`, его CSS, изображения и любые веб‑шрифты — идеально для офлайн‑распространения. | + +Откройте `page.png` в любом просмотрщике изображений, чтобы убедиться, что стиль жирного шрифта применён, и извлеките `archive.zip`, чтобы увидеть неизменённый HTML вместе с его ресурсами. + +## Часто задаваемые вопросы и подводные камни + +- **Что если HTML содержит JavaScript?** + Aspose.HTML **не** исполняет скрипты во время рендеринга, поэтому динамический контент не будет отображён. Для полностью отрендеренных страниц нужен безголовый браузер, но для статических шаблонов такой подход быстрее и легче. + +- **Можно ли изменить формат вывода на JPEG или BMP?** + Да — замените свойство `ImageFormat` в `ImageRenderingOptions`, например, `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Нужно ли вручную освобождать `HTMLDocument`?** + Класс реализует `IDisposable`. В длительно работающем сервисе оберните его в блок `using` или вызовите `document.Dispose()` после завершения работы. + +- **Как работает пользовательский `MyResourceHandler`?** + Он получает каждый внешний ресурс (CSS, изображения, шрифты) и записывает его в указанную папку. Это гарантирует, что ZIP содержит точную копию всех ресурсов, на которые ссылается HTML. + +## Заключение + +Теперь у вас есть компактное, готовое к продакшену решение, которое **convert html to png**, **render html as image**, **save html to zip**, **apply font style html** и **add bold to p** — всё в нескольких строках C#. Код автономный, работает с .NET 6+ и может быть внедрён в любой бекенд‑сервис, нуждающийся в быстрых визуальных снимках веб‑контента. + +Готовы к следующему шагу? Попробуйте изменить размер рендеринга, поэкспериментировать с другими CSS‑свойствами (например, `font-family` или `color`) или интегрировать этот конвертер в endpoint ASP.NET Core, который будет возвращать PNG по запросу. Возможностей бесконечно много, а с Aspose.HTML вы обходите тяжёлые зависимости браузеров. + +Если столкнулись с проблемами или есть идеи для расширения, оставляйте комментарий ниже. Счастливого кодинга! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/russian/net/html-document-manipulation/_index.md index cf442f62c..de7cbd7fb 100644 --- a/html/russian/net/html-document-manipulation/_index.md +++ b/html/russian/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aspose.HTML для .NET выделяется своей простотой и м Раскройте потенциал веб-разработки с Aspose.HTML для .NET. Создавайте, конвертируйте и обрабатывайте HTML-документы легко. ### [Создание HTML из строки в C# – Руководство по пользовательскому обработчику ресурсов](./create-html-from-string-in-c-custom-resource-handler-guide/) Узнайте, как создавать HTML из строки в C# с помощью пользовательского обработчика ресурсов в Aspose.HTML. +### [Создание HTML‑документа C# – пошаговое руководство](./create-html-document-c-step-by-step-guide/) +Узнайте, как создавать HTML‑документы в C# с помощью Aspose.HTML, следуя пошаговым инструкциям и примерам. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/russian/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/russian/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..42b910208 --- /dev/null +++ b/html/russian/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: Создайте HTML‑документ на C# и изучите, как получить элемент по id, найти + элемент по id, изменить стиль HTML‑элемента и добавить полужирный курсив с помощью + Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: ru +og_description: Создайте HTML‑документ на C# и мгновенно научитесь получать элемент + по id, находить элемент по id, изменять стиль HTML‑элемента и добавлять полужирный + курсив с понятными примерами кода. +og_title: Создание HTML‑документа C# – Полное руководство по программированию +tags: +- Aspose.Html +- C# +- DOM manipulation +title: Создание HTML‑документа C# – пошаговое руководство +url: /ru/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание HTML‑документа C# – Пошаговое руководство + +Когда‑нибудь нужно было **создать HTML‑документ C#** с нуля и затем изменить внешний вид одного абзаца? Вы не одиноки. Во многих проектах веб‑автоматизации вы генерируете HTML‑файл, ищете тег по его ID и применяете стили — часто жирный + курсив — без обращения к браузеру. + +В этом руководстве мы пройдём именно через это: создадим HTML‑документ в C#, **получим элемент по id**, **найдём элемент по id**, **изменим стиль HTML‑элемента** и, наконец, **добавим жирный курсив** с помощью библиотеки Aspose.Html. К концу вы получите полностью рабочий фрагмент кода, который можно вставить в любой .NET‑проект. + +## Что понадобится + +- .NET 6 или новее (код также работает на .NET Framework 4.7+) +- Visual Studio 2022 (или любой другой редактор) +- NuGet‑пакет **Aspose.Html** (`Install-Package Aspose.Html`) + +И всё—никаких дополнительных HTML‑файлов, веб‑сервера, только несколько строк C#. + +## Создание HTML‑документа C# – Инициализация документа + +Первым делом нужен живой объект `HTMLDocument`, с которым может работать движок Aspose.Html. Представьте это как открытие чистой тетради, в которой вы будете писать разметку. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Почему это важно:** Передавая сырую строку в `HTMLDocument`, вы избегаете работы с файловой системой и держите всё в памяти — идеально для модульных тестов или генерации «на лету». + +## Получить элемент по ID – Поиск абзаца + +Теперь, когда документ существует, нам нужно **получить элемент по id**. API DOM предоставляет `GetElementById`, который возвращает ссылку `IElement` или `null`, если указанный ID отсутствует. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Совет:** Даже если разметка небольшая, проверка на `null` спасёт от головной боли, когда тот же код будет использоваться на больших динамических страницах. + +## Найти элемент по ID – Альтернативный подход + +Иногда у вас уже есть ссылка на корень документа, и удобнее выполнить поиск в стиле запроса. CSS‑селекторы (`QuerySelector`) — ещё один способ **найти элемент по id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **Когда использовать какой метод?** `GetElementById` немного быстрее, так как это прямой поиск по хешу. `QuerySelector` полезен, когда нужны сложные селекторы (например, `div > p.highlight`). + +## Изменить стиль HTML‑элемента – Добавление жирного курсива + +Получив элемент, следующий шаг — **изменить стиль HTML‑элемента**. Aspose.Html предоставляет объект `Style`, где можно менять свойства CSS или воспользоваться перечислением `WebFontStyle` для одновременного применения нескольких шрифтовых атрибутов. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Эта единственная строка задаёт `font-weight` = `bold` и `font-style` = `italic`. Под капотом Aspose.Html преобразует перечисление в соответствующую строку CSS. + +### Полный рабочий пример + +Собрав все части вместе, получаем компактную, автономную программу, которую можно сразу скомпилировать и запустить: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Ожидаемый вывод** + +``` +Rendered HTML: +

Hello world

+``` + +Тег `

` теперь содержит встроенный атрибут `style`, делающий текст одновременно жирным и курсивным — именно то, что требовалось. + +## Пограничные случаи и распространённые подводные камни + +| Ситуация | На что обратить внимание | Как решить | +|-----------|--------------------------|------------| +| **ID не существует** | `GetElementById` возвращает `null`. | Выбросить исключение или перейти к элементу по умолчанию. | +| **Несколько элементов с одинаковым ID** | По спецификации HTML ID должны быть уникальны, но в реальном мире иногда правило нарушается. | `GetElementById` возвращает первое совпадение; при необходимости используйте `QuerySelectorAll` для обработки дубликатов. | +| **Конфликты стилей** | Существующие inline‑стили могут быть перезаписаны. | Добавляйте свойства к объекту `Style`, а не заменяйте всю строку: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Отображение в браузере** | Некоторые браузеры игнорируют `WebFontStyle`, если у элемента уже есть CSS‑класс с более высокой специфичностью. | При необходимости используйте `!important` через `paragraph.Style.SetProperty("font-weight", "bold", "important");` | + +## Профессиональные советы для реальных проектов + +- **Кешируйте документ**, если обрабатываете множество элементов; создание нового `HTMLDocument` для каждой крошечной части может снизить производительность. +- **Объединяйте изменения стилей** в одну транзакцию `Style`, чтобы избежать множественных перерасчётов DOM. +- **Используйте движок рендеринга Aspose.Html** для экспорта готового документа в PDF или изображение — полезно для отчётных систем. + +## Визуальная проверка (по желанию) + +Если хотите увидеть результат в браузере, сохраните полученную строку в файл `.html`: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Откройте `output.html`, и вы увидите **Hello world**, отображённый жирным + курсивом. + +![Пример создания HTML‑документа C# с жирным курсивом](/images/create-html-document-csharp.png "Создание HTML‑документа C# – отрисованный результат") + +*Alt text: Создание HTML‑документа C# – отрисованный результат с жирным курсивным текстом.* + +## Заключение + +Мы только что **создали HTML‑документ C#**, **получили элемент по id**, **нашли элемент по id**, **изменили стиль HTML‑элемента** и, наконец, **добавили жирный курсив** — всё это несколькими строками кода с помощью Aspose.Html. Подход прост, работает в любой среде .NET и масштабируется до более сложных манипуляций с DOM. + +Готовы к следующему шагу? Попробуйте заменить `WebFontStyle` на другие перечисления, например `Underline`, или комбинировать несколько стилей вручную. Или загрузите внешний HTML‑файл и примените ту же технику к сотням элементов. Возможности безграничны, а теперь у вас есть надёжная основа для дальнейшего развития. + +Счастливого кодинга! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/russian/net/html-extensions-and-conversions/_index.md b/html/russian/net/html-extensions-and-conversions/_index.md index 00354e673..e8ed288a3 100644 --- a/html/russian/net/html-extensions-and-conversions/_index.md +++ b/html/russian/net/html-extensions-and-conversions/_index.md @@ -41,6 +41,8 @@ Aspose.HTML для .NET — это не просто библиотека; эт Конвертируйте HTML в PDF без усилий с Aspose.HTML для .NET. Следуйте нашему пошаговому руководству и раскройте всю мощь преобразования HTML в PDF. ### [Создайте PDF из HTML – пошаговое руководство C#](./create-pdf-from-html-c-step-by-step-guide/) Пошаговое руководство по созданию PDF из HTML с помощью Aspose.HTML в C#. +### [Создайте PDF из HTML с Aspose – пошаговое руководство C#](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Пошаговое руководство по созданию PDF из HTML с помощью Aspose в C#. ### [Конвертируйте EPUB в изображение в .NET с помощью Aspose.HTML](./convert-epub-to-image/) Узнайте, как конвертировать EPUB в изображения с помощью Aspose.HTML для .NET. Пошаговое руководство с примерами кода и настраиваемыми параметрами. ### [Конвертируйте EPUB в PDF в .NET с помощью Aspose.HTML](./convert-epub-to-pdf/) @@ -65,6 +67,8 @@ Aspose.HTML для .NET — это не просто библиотека; эт Узнайте, как преобразовать HTML в TIFF с помощью Aspose.HTML для .NET. Следуйте нашему пошаговому руководству для эффективной оптимизации веб-контента. ### [Конвертируйте HTML в XPS в .NET с помощью Aspose.HTML](./convert-html-to-xps/) Откройте для себя мощь Aspose.HTML для .NET: конвертируйте HTML в XPS без усилий. Предварительные условия, пошаговое руководство и часто задаваемые вопросы включены. +### [Конвертировать HTML в изображение в C# – Полное руководство](./convert-html-to-image-in-c-complete-guide/) +Полное руководство по преобразованию HTML в изображение с помощью Aspose.HTML в C#. ### [Как заархивировать HTML в C# – Сохранить HTML в Zip](./how-to-zip-html-in-c-save-html-to-zip/) Узнайте, как упаковать HTML‑файлы в архив ZIP с помощью C# и Aspose.HTML, используя простой пошаговый пример. ### [Создайте HTML‑документ со стилизованным текстом и экспортируйте в PDF – Полное руководство](./create-html-document-with-styled-text-and-export-to-pdf-full/) @@ -73,6 +77,10 @@ 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 в C# – Полное руководство с пользовательским хранилищем](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Узнайте, как сохранить HTML‑страницу в архив ZIP в C# с Aspose.HTML, используя пользовательское хранилище. +### [Как заархивировать HTML с Aspose.HTML – Полное руководство](./how-to-zip-html-with-aspose-html-complete-guide/) +Полное руководство по упаковке HTML‑файлов в ZIP‑архив с помощью Aspose.HTML, включая примеры кода и подробные шаги. ## Заключение diff --git a/html/russian/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/russian/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..a97147064 --- /dev/null +++ b/html/russian/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Конвертируйте HTML в изображение с помощью Aspose.HTML в C#. Узнайте, + как сохранить HTML в PNG, задать размер рендеринга изображения и записать изображение + в файл за несколько шагов. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: ru +og_description: Быстро преобразуйте HTML в изображение. Это руководство показывает, + как сохранить HTML в PNG, задать размер рендеринга изображения и записать его в + файл с помощью Aspose.HTML. +og_title: Преобразование HTML в изображение на C# – пошаговое руководство +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Преобразование HTML в изображение в C# – Полное руководство +url: /ru/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Преобразование HTML в изображение на C# – Полное руководство + +Когда‑нибудь нужно было **преобразовать HTML в изображение** для миниатюры дашборда, превью письма или PDF‑отчёта? Такая ситуация встречается гораздо чаще, чем кажется, особенно когда нужно встроить динамический веб‑контент в другое место. + +Хорошие новости? С Aspose.HTML вы можете **преобразовать HTML в изображение** всего в несколько строк кода, а также узнать, как *сохранить HTML как PNG*, управлять размерами вывода и *записать изображение в файл* без лишних усилий. + +В этом руководстве мы пройдём всё, что нужно знать: от загрузки удалённой страницы до настройки размеров рендеринга и, наконец, сохранения результата в PNG‑файл на диске. Никаких внешних инструментов, никаких хитрых командных строк — только чистый C# код, который можно вставить в любой .NET‑проект. + +## Что вы узнаете + +- Как **рендерить веб‑страницу в PNG** с помощью класса `HTMLDocument` из Aspose.HTML. +- Точные шаги для **установки размеров изображения при рендеринге**, чтобы вывод соответствовал требованиям вашего макета. +- Способы **записать изображение в файл** безопасно, работая со стримами и путями к файлам. +- Советы по устранению распространённых проблем, таких как отсутствие шрифтов или тайм‑ауты сети. + +### Предварительные требования + +- .NET 6.0 или новее (API также работает с .NET Framework, но рекомендуется .NET 6+). +- Ссылка на NuGet‑пакет Aspose.HTML for .NET (`Aspose.Html`). +- Базовое знакомство с C# и async/await (необязательно, но полезно). + +Если всё это уже есть, вы готовы сразу приступить к преобразованию HTML в изображение. + +## Шаг 1: Загрузка веб‑страницы – Основы преобразования HTML в изображение + +Прежде чем начнётся рендеринг, нужен экземпляр `HTMLDocument`, представляющий страницу, которую нужно захватить. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Почему это важно:* `HTMLDocument` парсит HTML, обрабатывает CSS и строит DOM. Если документ не загрузится (например, из‑за проблем с сетью), последующий рендеринг выдаст пустое изображение. Всегда проверяйте, доступен ли URL, перед тем как продолжать. + +## Шаг 2: Установка размеров изображения при рендеринге – Управление шириной, высотой и качеством + +Aspose.HTML позволяет точно настроить размеры вывода с помощью `ImageRenderingOptions`. Здесь вы **устанавливаете размеры изображения при рендеринге**, чтобы они соответствовали целевому макету. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Совет профессионала:* Если не указать `Width` и `Height`, Aspose.HTML использует внутренний размер страницы, который может быть непредсказуемым для адаптивных дизайнов. Явное указание размеров гарантирует, что ваш вывод **save HTML as PNG** будет выглядеть точно так, как вы ожидаете. + +## Шаг 3: Запись изображения в файл – Сохранение отрендеренного PNG + +Теперь, когда документ готов и параметры рендеринга заданы, можно наконец **записать изображение в файл**. Использование `FileStream` гарантирует безопасное создание файла, даже если папка ещё не существует. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +После выполнения этого блока вы найдёте `page.png` в указанном месте. Вы только что **рендерили веб‑страницу в PNG** и записали её на диск в одной простой операции. + +### Ожидаемый результат + +Откройте `C:\Temp\page.png` в любой программе для просмотра изображений. Вы должны увидеть точную копию `https://example.com`, отрендеренную с разрешением 1024 × 768 пикселей и сглаженными краями благодаря антиалиасингу. Если страница содержит динамический контент (например, элементы, генерируемые JavaScript), они будут захвачены, при условии, что DOM полностью загрузился до рендеринга. + +## Шаг 4: Обработка особых случаев – Шрифты, аутентификация и большие страницы + +Базовый процесс подходит для большинства публичных сайтов, но в реальных условиях часто возникают сложности: + +| Ситуация | Что делать | +|-----------|------------| +| **Не загружаются пользовательские шрифты** | Встроите файлы шрифтов локально и добавьте их через `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Страницы за аутентификацией** | Используйте перегрузку `HTMLDocument`, принимающую `HttpWebRequest` с cookie или токенами. | +| **Очень длинные страницы** | Увеличьте `Height` или включите `PageScaling` в `ImageRenderingOptions`, чтобы избежать обрезки. | +| **Резкие скачки потребления памяти** | Рендерите частями, используя перегрузку `RenderToImage`, принимающую регион `Rectangle`. | + +Учитывая эти нюансы при **записи изображения в файл**, ваш конвейер **convert html to image** будет надёжным в продакшене. + +## Шаг 5: Полный рабочий пример – Готовый к копированию + +Ниже представлен весь код программы, готовый к компиляции. В нём собраны все шаги, обработка ошибок и комментарии, которые вам понадобятся. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Запустите программу, и в консоли появится сообщение‑подтверждение. PNG‑файл будет точно таким, каким вы бы ожидали, если бы **рендерили веб‑страницу в PNG** вручную в браузере и сделали скриншот — только быстрее и полностью автоматизировано. + +## Часто задаваемые вопросы + +**В: Можно ли преобразовать локальный HTML‑файл вместо URL?** +Конечно. Просто замените URL на путь к файлу: `new HTMLDocument(@"C:\myPage.html")`. + +**В: Нужна ли лицензия для Aspose.HTML?** +Для разработки и тестирования достаточно бесплатной оценочной лицензии. Для продакшена приобретите полную лицензию, чтобы убрать водяной знак оценки. + +**В: Что делать, если страница загружает контент через JavaScript после начальной загрузки?** +Aspose.HTML синхронно исполняет JavaScript во время парсинга, но длительные скрипты могут потребовать ручной задержки. Вы можете вызвать `HTMLDocument.WaitForReadyState` перед рендерингом. + +## Заключение + +Теперь у вас есть надёжное сквозное решение для **преобразования HTML в изображение** на C#. Следуя описанным шагам, вы сможете **сохранить HTML как PNG**, точно **установить размеры изображения при рендеринге** и уверенно **записать изображение в файл** в любой среде Windows или Linux. + +От простых скриншотов до автоматической генерации отчётов — эта техника масштабируется без проблем. Далее попробуйте другие форматы вывода, такие как JPEG или BMP, или интегрируйте код в ASP.NET Core API, который будет возвращать PNG напрямую клиенту. Возможностей практически бесконечно. + +Удачной разработки, и пусть ваши отрендеренные изображения всегда выглядят пиксельно‑идеально! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/russian/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/russian/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..d6bb08dce --- /dev/null +++ b/html/russian/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-03-21 +description: Быстро создавайте PDF из HTML с помощью Aspose HTML. Узнайте, как отрисовать + HTML в PDF, конвертировать HTML в PDF и как использовать Aspose в кратком руководстве. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: ru +og_description: Создайте PDF из HTML с помощью Aspose в C#. Это руководство показывает, + как преобразовать HTML в PDF, конвертировать HTML в PDF и как эффективно использовать + Aspose. +og_title: Создание PDF из HTML – Полный учебник Aspose C# +tags: +- Aspose +- C# +- PDF generation +title: Создание PDF из HTML с помощью Aspose – пошаговое руководство на C# +url: /ru/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание PDF из HTML с Aspose – Пошаговое руководство на C# + +Когда‑нибудь вам нужно было **create PDF from HTML**, но вы не были уверены, какая библиотека даст вам пиксель‑идеальные результаты? Вы не одиноки. Многие разработчики сталкиваются с проблемой, когда пытаются превратить веб‑фрагмент в печатный документ, и в итоге получают размытый текст или сломанные макеты. + +Хорошая новость в том, что Aspose HTML делает весь процесс безболезненным. В этом руководстве мы пройдемся по точному коду, который вам нужен для **render HTML to PDF**, разберём, почему каждый параметр важен, и покажем, как **convert HTML to PDF** без скрытых трюков. К концу вы узнаете **how to use Aspose** для надёжного создания PDF в любом проекте .NET. + +## Требования – Что вам понадобится перед началом + +- **.NET 6.0 or later** (пример работает также на .NET Framework 4.7+) +- **Visual Studio 2022** или любой IDE, поддерживающий C# +- **Aspose.HTML for .NET** пакет NuGet (бесплатная пробная версия или лицензированная) +- Базовое понимание синтаксиса C# (глубокие знания PDF не требуются) + +Если у вас есть всё это, вы готовы начинать. В противном случае скачайте последнюю .NET SDK и установите пакет NuGet с помощью: + +```bash +dotnet add package Aspose.HTML +``` + +Эта единственная строка подтягивает всё, что нужно для конвертации **aspose html to pdf**. + +## Шаг 1: Настройте проект для создания PDF из HTML + +Первое, что нужно сделать, — создать новое консольное приложение (или интегрировать код в существующий сервис). Ниже минимальный скелет `Program.cs`: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** Если вы видите `Aspise.Html.Rendering.Text` в старых примерах, замените его на `Aspose.Html.Rendering.Text`. Ошибка в написании вызовет ошибку компиляции. + +Использование правильных пространств имён гарантирует, что компилятор сможет найти класс **TextOptions**, который нам понадобится позже. + +## Шаг 2: Создайте HTML‑документ (Render HTML to PDF) + +Теперь мы создаём исходный HTML. Aspose позволяет передать необработанную строку, путь к файлу или даже URL. Для этой демонстрации мы упростим задачу: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Зачем передавать строку? Это избегает ввода‑вывода файловой системы, ускоряет конвертацию и гарантирует, что HTML, который вы видите в коде, точно такой же будет отрендерен. Если вы предпочитаете загрузку из файла, просто замените аргумент конструктора на URI файла. + +## Шаг 3: Тонкая настройка рендеринга текста (Convert HTML to PDF с лучшим качеством) + +Рендеринг текста часто определяет, будет ли ваш PDF выглядеть чётко или размыто. Aspose предоставляет класс `TextOptions`, который позволяет включить субпиксельное хинтинг — необходимо для вывода с высоким DPI. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Включение `UseHinting` особенно полезно, когда ваш исходный HTML содержит пользовательские шрифты или мелкие размеры шрифта. Без этого вы можете заметить зубчатые края в финальном PDF. + +## Шаг 4: Привяжите параметры текста к конфигурации рендеринга PDF (How to Use Aspose) + +Далее мы привязываем эти параметры текста к PDF‑рендереру. Здесь **aspose html to pdf** действительно проявляет себя — можно настроить всё, от размера страницы до сжатия. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Вы можете опустить `PageSetup`, если вас устраивает размер по умолчанию A4. Главное, что объект `TextOptions` находится внутри `PdfRenderingOptions`, и так вы сообщаете Aspose *как* рендерить текст. + +## Шаг 5: Рендеринг HTML и сохранение PDF (Convert HTML to PDF) + +Наконец, мы выводим результат в файл. Использование блока `using` гарантирует, что дескриптор файла будет закрыт корректно, даже если произойдёт исключение. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Когда вы запустите программу, файл `output.pdf` появится рядом с исполняемым файлом. Откройте его, и вы увидите чистый заголовок и абзац — точно такие, как определены в строке HTML. + +### Ожидаемый результат + +![пример вывода pdf из html](https://example.com/images/pdf-output.png "пример вывода pdf из html") + +*Снимок экрана показывает сгенерированный PDF с заголовком “Hello, Aspose!” чётко отрисованным благодаря хинтингу текста.* + +## Часто задаваемые вопросы и особые случаи + +### 1. Что если мой HTML ссылается на внешние ресурсы (изображения, CSS)? + +Aspose разрешает относительные URL‑адреса на основе базового URI документа. Если вы передаёте необработанную строку, задайте базовый URI вручную: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Теперь любой `` будет искаться относительно `C:/MyProject/`. + +### 2. Как встроить шрифты, которые не установлены на сервере? + +Добавьте блок ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Шаг 4: Настройте параметры сохранения для использования пользовательского хранилища + +`HtmlSaveOptions` позволяет нам указать Aspose упаковать всё в ZIP‑файл. Свойство `OutputStorage` (устаревшее) получает наш экземпляр `MyStorage`. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Примечание:** В Aspose HTML 23.9+ свойство называется `OutputStorage`, но помечено как устаревшее. Современная альтернатива — `ZipOutputStorage`. Приведённый ниже код работает с обоими, так как интерфейс одинаков. + +### Шаг 5: Сохраните документ как ZIP‑архив + +Выберите целевую папку (или поток) и позвольте Aspose выполнить тяжёлую работу. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Когда программа завершится, вы найдёте `output.zip`, содержащий: + +* `index.html` — основной документ. +* Любые встроенные изображения, CSS‑файлы или скрипты (если ваш HTML ссылался на них). + +Вы можете открыть ZIP любым архиватором, чтобы проверить структуру. + +--- + +## Проверка результата (необязательно) + +Если вы хотите программно проверить архив без извлечения его на диск: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Типичный вывод: + +``` +- index.html (452 bytes) +``` + +Если бы у вас были изображения или CSS, они появились бы как дополнительные записи. Эта быстрая проверка подтверждает, что **create html zip archive** сработал как ожидалось. + +--- + +## Часто задаваемые вопросы и особые случаи + +| Вопрос | Ответ | +|----------|--------| +| **Что если мне нужно записать ZIP напрямую в поток ответа?** | Верните `MemoryStream`, полученный из `MyStorage` после `document.Save`. Преобразуйте его в `byte[]` и запишите в `HttpResponse.Body`. | +| **Мой HTML ссылается на внешние URL—будут ли они загружены?** | Нет. Aspose упаковывает только ресурсы, которые *встроены* (например, `` или локальные файлы). Для удалённых ресурсов их необходимо сначала загрузить и скорректировать разметку. | +| **Свойство `OutputStorage` помечено как устаревшее — игнорировать его?** | Оно всё ещё работает, но более новое `ZipOutputStorage` предоставляет тот же API под другим именем. Замените `OutputStorage` на `ZipOutputStorage`, если хотите избавиться от предупреждений. | +| **Можно ли зашифровать ZIP?** | Да. После сохранения откройте файл с помощью `System.IO.Compression.ZipArchive` и задайте пароль, используя сторонние библиотеки, такие как `SharpZipLib`. Aspose сам по себе шифрование не предоставляет. | + +## Полный рабочий пример (копировать‑вставить) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Запустите программу, откройте `output.zip`, и вы увидите единственный файл `index.html`, который отображает заголовок «Hello from ZIP!», когда открывается в браузере. + +## Заключение + +Теперь вы знаете, **как сохранить HTML как ZIP** в C# с использованием класса **custom storage**, как **экспортировать HTML в ZIP** и как **создать HTML‑zip‑архив**, готовый к распространению. Этот шаблон гибок — замените `MemoryStream` на поток облака, добавьте шифрование или интегрируйте его в веб‑API, который будет возвращать ZIP по запросу. + +Готовы к следующему шагу? Попробуйте передать полностью оформленную веб‑страницу с изображениями и стилями, либо подключите хранилище к Azure Blob Storage, чтобы полностью обойти локальную файловую систему. Возможности безграничны, когда вы комбинируете возможности ZIP в Aspose.HTML со своей логикой хранения. + +Удачной разработки, и пусть ваши архивы всегда будут аккуратными! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/spanish/net/generate-jpg-and-png-images/_index.md b/html/spanish/net/generate-jpg-and-png-images/_index.md index 4323c4591..882fcec2e 100644 --- a/html/spanish/net/generate-jpg-and-png-images/_index.md +++ b/html/spanish/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aprenda a utilizar Aspose.HTML para .NET para manipular documentos HTML, convert Aprenda a activar el antialiasing al convertir documentos DOCX a imágenes PNG o JPG usando Aspose.HTML para .NET. ### [Convertir docx a PNG – crear archivo ZIP con C# tutorial](./convert-docx-to-png-create-zip-archive-c-tutorial/) Aprenda a convertir documentos DOCX a imágenes PNG y empaquetarlos en un archivo ZIP usando C#. +### [Convertir HTML a PNG – Guía completa en C# con exportación ZIP](./convert-html-to-png-full-c-guide-with-zip-export/) +Aprenda a convertir HTML a imágenes PNG en C#, generar archivos ZIP y exportar los resultados fácilmente. ## Conclusión diff --git a/html/spanish/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/spanish/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..57a3771bd --- /dev/null +++ b/html/spanish/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Convierte HTML a PNG y renderiza HTML como imagen mientras guardas el + HTML en un ZIP. Aprende a aplicar estilos de fuente en HTML y a añadir negrita a + los elementos p en solo unos pocos pasos. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: es +og_description: Convierte HTML a PNG rápidamente. Esta guía muestra cómo renderizar + HTML como imagen, guardar HTML en ZIP, aplicar estilo de fuente al HTML y añadir + negrita a los elementos p. +og_title: Convertir HTML a PNG – Tutorial completo de C# +tags: +- Aspose +- C# +title: Convertir HTML a PNG – Guía completa de C# con exportación ZIP +url: /es/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir HTML a PNG – Guía completa en C# con exportación ZIP + +¿Alguna vez necesitaste **convertir HTML a PNG** pero no estabas seguro de qué biblioteca podía hacerlo sin incorporar un navegador sin cabeza? No estás solo. En muchos proyectos—miniaturas de correos electrónicos, vistas previas de documentación o imágenes de vista rápida—convertir una página web en una imagen estática es una necesidad real. + +¿La buena noticia? Con Aspose.HTML puedes **renderizar HTML como imagen**, ajustar el marcado al vuelo e incluso **guardar HTML en ZIP** para su distribución posterior. En este tutorial recorreremos un ejemplo completo y ejecutable que **aplica estilo de fuente HTML**, específicamente **añadir negrita a los elementos p**, antes de generar un archivo PNG. Al final tendrás una única clase C# que hace todo, desde cargar una página hasta archivar sus recursos. + +## Lo que necesitarás + +- .NET 6.0 o posterior (la API funciona también en .NET Core) +- Aspose.HTML para .NET 6+ (paquete NuGet `Aspose.Html`) +- Un conocimiento básico de la sintaxis de C# (no se requieren conceptos avanzados) + +Eso es todo. Sin navegadores externos, sin phantomjs, solo código administrado puro. + +## Paso 1 – Cargar el documento HTML + +Primero traemos el archivo fuente (o URL) a un objeto `HTMLDocument`. Este paso es la base tanto para **render html as image** como para **save html to zip** más adelante. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Por qué es importante:* La clase `HTMLDocument` analiza el marcado, construye un DOM y resuelve los recursos vinculados (CSS, imágenes, fuentes). Sin un objeto de documento adecuado no puedes manipular estilos ni renderizar nada. + +## Paso 2 – Aplicar estilo de fuente HTML (Añadir negrita a p) + +Ahora **aplicaremos estilo de fuente HTML** iterando sobre cada elemento `

` y estableciendo su `font-weight` a bold. Esta es la forma programática de **add bold to p** sin tocar el archivo original. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Consejo profesional:* Si solo necesitas poner en negrita un subconjunto, cambia el selector a algo más específico, por ejemplo, `"p.intro"`. + +## Paso 3 – Renderizar HTML como Imagen (Convertir HTML a PNG) + +Con el DOM listo, configuramos `ImageRenderingOptions` y llamamos a `RenderToImage`. Aquí es donde ocurre la magia del **convert html to png**. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Por qué importan las opciones:* Establecer un ancho/alto fijo evita que la salida sea demasiado grande, mientras que el antialiasing brinda un resultado visual más suave. También puedes cambiar `options` a `ImageFormat.Jpeg` si prefieres un tamaño de archivo menor. + +## Paso 4 – Guardar HTML en ZIP (Agrupar recursos) + +A menudo necesitas distribuir el HTML original junto con su CSS, imágenes y fuentes. `ZipArchiveSaveOptions` de Aspose.HTML hace exactamente eso. También incorporamos un `ResourceHandler` personalizado para que todos los recursos externos se escriban en la misma carpeta que el archivo ZIP. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Caso límite:* Si tu HTML hace referencia a imágenes remotas que requieren autenticación, el manejador predeterminado fallará. En ese caso puedes extender `MyResourceHandler` para inyectar encabezados HTTP. + +## Paso 5 – Conectar todo en una única clase Convertidora + +A continuación se muestra la clase completa, lista para ejecutar, que une todos los pasos anteriores. Puedes copiar‑pegarla en una aplicación de consola, llamar a `Convert` y observar cómo aparecen los archivos. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Resultado esperado + +Después de ejecutar el fragmento anterior encontrarás dos archivos en `outputDirectory`: + +| File | Description | +|------|-------------| +| `page.png` | Una renderización PNG de 1200 × 800 del HTML fuente, con cada párrafo mostrado en **negrita**. | +| `archive.zip` | Un paquete ZIP que contiene el `input.html` original, su CSS, imágenes y cualquier fuente web, perfecto para distribución offline. | + +Puedes abrir `page.png` en cualquier visor de imágenes para verificar que se aplicó el estilo en negrita, y extraer `archive.zip` para ver el HTML sin modificar junto con sus recursos. + +## Preguntas frecuentes y problemas comunes + +- **What if the HTML contains JavaScript?** + Aspose.HTML **no** ejecuta scripts durante el renderizado, por lo que el contenido dinámico no aparecerá. Para páginas completamente renderizadas necesitarías un navegador sin cabeza, pero para plantillas estáticas este enfoque es más rápido y ligero. + +- **Can I change the output format to JPEG or BMP?** + Sí—cambia la propiedad `ImageFormat` de `ImageRenderingOptions`, por ejemplo, `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Do I need to dispose of the `HTMLDocument` manually?** + La clase implementa `IDisposable`. En un servicio de larga duración envuélvelo en un bloque `using` o llama a `document.Dispose()` después de terminar. + +- **How does the custom `MyResourceHandler` work?** + Recibe cada recurso externo (CSS, imágenes, fuentes) y lo escribe en la carpeta que especificas. Esto garantiza que el ZIP contenga una copia fiel de todo lo que el HTML referencia. + +## Conclusión + +Ahora tienes una solución compacta y lista para producción que **convert html to png**, **render html as image**, **save html to zip**, **apply font style html**, y **add bold to p**—todo en unas pocas líneas de C#. El código es autónomo, funciona con .NET 6+ y puede integrarse en cualquier servicio backend que necesite instantáneas visuales rápidas del contenido web. + +¿Listo para el siguiente paso? Prueba cambiar el tamaño de renderizado, experimenta con otras propiedades CSS (como `font-family` o `color`), o integra este convertidor en un endpoint ASP.NET Core que devuelva el PNG bajo demanda. Las posibilidades son infinitas, y con Aspose.HTML evitas dependencias de navegadores pesados. + +Si encontraste algún problema o tienes ideas para extensiones, deja un comentario abajo. ¡Feliz codificación! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/spanish/net/html-document-manipulation/_index.md index 84acbc5a9..6d6aa1147 100644 --- a/html/spanish/net/html-document-manipulation/_index.md +++ b/html/spanish/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aprenda a utilizar Aspose.HTML para .NET. Importe espacios de nombres, combine H Descubra el potencial del desarrollo web con Aspose.HTML para .NET. Cree, convierta y manipule documentos HTML fácilmente. ### [Crear HTML a partir de una cadena en C# – Guía del controlador de recursos personalizado](./create-html-from-string-in-c-custom-resource-handler-guide/) Aprenda a generar contenido HTML a partir de una cadena en C# utilizando un controlador de recursos personalizado con Aspose.HTML. +### [Crear documento HTML en C# – Guía paso a paso](./create-html-document-c-step-by-step-guide/) +Aprenda a crear documentos HTML en C# con Aspose.HTML mediante una guía paso a paso con ejemplos claros. ## Conclusión diff --git a/html/spanish/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/spanish/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..c4e78cc14 --- /dev/null +++ b/html/spanish/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: Crear documento HTML en C# y aprender cómo obtener un elemento por id, + localizar un elemento por id, cambiar el estilo del elemento HTML y agregar negrita + cursiva usando Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: es +og_description: Crea un documento HTML en C# y aprende al instante a obtener un elemento + por id, localizar un elemento por id, cambiar el estilo de un elemento HTML y agregar + negrita y cursiva con ejemplos de código claros. +og_title: Crear documento HTML C# – Guía completa de programación +tags: +- Aspose.Html +- C# +- DOM manipulation +title: Crear documento HTML en C# – Guía paso a paso +url: /es/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear documento HTML C# – Guía paso a paso + +¿Alguna vez necesitaste **crear documento HTML C#** desde cero y luego ajustar el aspecto de un solo párrafo? No eres el único. En muchos proyectos de automatización web crearás un archivo HTML, buscarás una etiqueta por su ID y luego aplicarás un estilo—a menudo negrita + cursiva—sin tocar nunca un navegador. + +En este tutorial recorreremos exactamente eso: crearemos un documento HTML en C#, **obtener elemento por id**, **localizar elemento por id**, **cambiar estilo del elemento HTML**, y finalmente **añadir negrita cursiva** usando la biblioteca Aspose.Html. Al final tendrás un fragmento completamente ejecutable que puedes insertar en cualquier proyecto .NET. + +## Qué necesitarás + +- .NET 6 o posterior (el código también funciona en .NET Framework 4.7+) +- Visual Studio 2022 (o cualquier editor que prefieras) +- El paquete NuGet **Aspose.Html** (`Install-Package Aspose.Html`) + +Eso es todo—sin archivos HTML adicionales, sin servidor web, solo unas pocas líneas de C#. + +## Crear documento HTML C# – Inicializar el documento + +Lo primero: necesitas un objeto `HTMLDocument` activo con el que el motor Aspose.Html pueda trabajar. Piensa en ello como abrir un cuaderno nuevo donde escribirás tu marcado. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Por qué es importante:** Al pasar la cadena cruda a `HTMLDocument`, evitas manejar I/O de archivos y mantienes todo en memoria—perfecto para pruebas unitarias o generación en tiempo real. + +## Obtener elemento por ID – Encontrar el párrafo + +Ahora que el documento existe, necesitamos **obtener elemento por id**. La API DOM nos brinda `GetElementById`, que devuelve una referencia `IElement` o `null` si el ID no está presente. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Consejo profesional:** Aunque nuestro marcado es pequeño, agregar una verificación de null evita dolores de cabeza cuando la misma lógica se reutiliza en páginas más grandes y dinámicas. + +## Localizar elemento por ID – Enfoque alternativo + +A veces ya puedes tener una referencia a la raíz del documento y prefieres una búsqueda estilo consulta. Usar selectores CSS (`QuerySelector`) es otra forma de **localizar elemento por id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **¿Cuándo usar cada uno?** `GetElementById` es ligeramente más rápido porque es una búsqueda directa en hash. `QuerySelector` destaca cuando necesitas selectores complejos (p. ej., `div > p.highlight`). + +## Cambiar estilo del elemento HTML – Añadiendo negrita cursiva + +Con el elemento en mano, el siguiente paso es **cambiar el estilo del elemento HTML**. Aspose.Html expone un objeto `Style` donde puedes ajustar propiedades CSS o usar la práctica enumeración `WebFontStyle` para aplicar varios rasgos de fuente a la vez. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Esa única línea establece el `font-weight` del elemento a `bold` y el `font-style` a `italic`. Internamente Aspose.Html traduce la enumeración a la cadena CSS correspondiente. + +### Ejemplo completo funcional + +Unir todas las piezas produce un programa compacto y autónomo que puedes compilar y ejecutar de inmediato: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Salida esperada** + +``` +Rendered HTML: +

Hello world

+``` + +La etiqueta `

` ahora lleva un atributo `style` en línea que hace que el texto sea tanto negrita como cursiva—exactamente lo que queríamos. + +## Casos límite y errores comunes + +| Situación | Qué observar | Cómo manejar | +|-----------|--------------|--------------| +| **El ID no existe** | `GetElementById` devuelve `null`. | Lanzar una excepción o recurrir a un elemento predeterminado. | +| **Varios elementos comparten el mismo ID** | La especificación HTML indica que los IDs deben ser únicos, pero en páginas reales a veces se rompe la regla. | `GetElementById` devuelve la primera coincidencia; considera usar `QuerySelectorAll` si necesitas manejar duplicados. | +| **Conflictos de estilo** | Los estilos en línea existentes pueden ser sobrescritos. | Añade al objeto `Style` en lugar de establecer toda la cadena `style`: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Renderizado en un navegador** | Algunos navegadores ignoran `WebFontStyle` si el elemento ya tiene una clase CSS con mayor especificidad. | Usa `!important` mediante `paragraph.Style.SetProperty("font-weight", "bold", "important");` si es necesario. | + +## Consejos profesionales para proyectos reales + +- **Cachea el documento** si estás procesando muchos elementos; crear un nuevo `HTMLDocument` para cada fragmento pequeño puede afectar el rendimiento. +- **Combina cambios de estilo** en una sola transacción `Style` para evitar múltiples reflujo del DOM. +- **Aprovecha el motor de renderizado de Aspose.Html** para exportar el documento final como PDF o imagen—ideal para herramientas de informes. + +## Confirmación visual (opcional) + +Si prefieres ver el resultado en un navegador, puedes guardar la cadena renderizada en un archivo `.html`: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Abre `output.html` y verás **Hello world** mostrado en negrita + cursiva. + +![Ejemplo de crear documento HTML C# que muestra párrafo en negrita y cursiva](/images/create-html-document-csharp.png "Crear documento HTML C# – salida renderizada") + +*Texto alternativo: Crear documento HTML C# – salida renderizada con texto en negrita y cursiva.* + +## Conclusión + +Acabamos de **crear un documento HTML C#**, **obtener elemento por id**, **localizar elemento por id**, **cambiar el estilo del elemento HTML**, y finalmente **añadir negrita cursiva**—todo con un puñado de líneas usando Aspose.Html. El enfoque es sencillo, funciona en cualquier entorno .NET y escala a manipulaciones DOM más grandes. + +¿Listo para el siguiente paso? Prueba cambiar `WebFontStyle` por otras enumeraciones como `Underline` o combina varios estilos manualmente. O experimenta cargando un archivo HTML externo y aplicando la misma técnica a cientos de elementos. El cielo es el límite, y ahora tienes una base sólida sobre la que construir. + +¡Feliz codificación! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/spanish/net/html-extensions-and-conversions/_index.md b/html/spanish/net/html-extensions-and-conversions/_index.md index 58e38eec4..1d46aa1f5 100644 --- a/html/spanish/net/html-extensions-and-conversions/_index.md +++ b/html/spanish/net/html-extensions-and-conversions/_index.md @@ -41,6 +41,8 @@ Aspose.HTML para .NET no es solo una biblioteca, es un punto de inflexión en el Convierta HTML a PDF sin esfuerzo con Aspose.HTML para .NET. Siga nuestra guía paso a paso y aproveche el poder de la conversión de HTML a PDF. ### [Crear PDF a partir de HTML – Guía paso a paso en C#](./create-pdf-from-html-c-step-by-step-guide/) Aprenda a generar un PDF desde HTML usando C# y Aspose.HTML con esta guía paso a paso. +### [Crear PDF a partir de HTML con Aspose – Guía paso a paso en C#](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Aprenda a crear un PDF a partir de HTML usando Aspose y C# con esta guía paso a paso. ### [Crear documento HTML con texto con estilo y exportarlo a PDF – Guía completa](./create-html-document-with-styled-text-and-export-to-pdf-full/) Aprenda a generar un documento HTML con texto formateado y convertirlo a PDF usando Aspose.HTML para .NET paso a paso. ### [Convertir EPUB a imagen en .NET con Aspose.HTML](./convert-epub-to-image/) @@ -63,6 +65,10 @@ Aprenda a convertir HTML a Markdown en .NET con Aspose.HTML para manipular conte Convierta HTML a MHTML en .NET con Aspose.HTML: una guía paso a paso para archivar contenido web de manera eficiente. Aprenda a usar Aspose.HTML para .NET para crear archivos MHTML. ### [Convierte HTML a PNG en .NET con Aspose.HTML](./convert-html-to-png/) Descubra cómo utilizar Aspose.HTML para .NET para manipular y convertir documentos HTML. Guía paso a paso para un desarrollo .NET eficaz. + +### [Convertir HTML a imagen en C# – Guía completa](./convert-html-to-image-in-c-complete-guide/) +Aprenda a convertir HTML a imagen en C# con Aspose.HTML para .NET. Guía paso a paso para generar imágenes de alta calidad a partir de contenido HTML. + ### [Guardar HTML como ZIP – Tutorial completo en C#](./save-html-as-zip-complete-c-tutorial/) Aprenda a guardar documentos HTML como archivos ZIP usando Aspose.HTML para .NET con este tutorial paso a paso en C#. ### [Convierte HTML a TIFF en .NET con Aspose.HTML](./convert-html-to-tiff/) @@ -73,6 +79,10 @@ 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 como ZIP en C# – Guía completa con almacenamiento personalizado](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Aprenda a guardar HTML en un archivo ZIP usando C# con almacenamiento personalizado paso a paso. +### [Cómo comprimir HTML con Aspose.HTML – Guía completa](./how-to-zip-html-with-aspose-html-complete-guide/) +Aprenda a comprimir archivos HTML en un archivo ZIP usando Aspose.HTML con esta guía paso a paso y ejemplos de código. ## Conclusión diff --git a/html/spanish/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/spanish/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..07e1395c7 --- /dev/null +++ b/html/spanish/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Convertir HTML a imagen usando Aspose.HTML en C#. Aprende cómo guardar + HTML como PNG, establecer el tamaño de renderizado de la imagen y escribir la imagen + en un archivo en solo unos pocos pasos. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: es +og_description: Convierte HTML a imagen rápidamente. Esta guía muestra cómo guardar + HTML como PNG, establecer el tamaño de renderizado de la imagen y escribir la imagen + en un archivo con Aspose.HTML. +og_title: Convertir HTML a Imagen en C# – Guía paso a paso +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Convertir HTML a Imagen en C# – Guía Completa +url: /es/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir HTML a Imagen en C# – Guía Completa + +¿Alguna vez necesitaste **convert HTML to image** para una miniatura de panel, una vista previa de correo electrónico o un informe PDF? Es un escenario que aparece más a menudo de lo que esperas, sobre todo cuando trabajas con contenido web dinámico que debe incrustarse en otro lugar. + +¿La buena noticia? Con Aspose.HTML puedes **convert HTML to image** en unas pocas líneas, y también aprenderás a *save HTML as PNG*, controlar las dimensiones de salida y *write image to file* sin complicaciones. + +En este tutorial repasaremos todo lo que necesitas saber: desde cargar una página remota hasta ajustar el tamaño de renderizado, y finalmente persistir el resultado como un archivo PNG en disco. Sin herramientas externas, sin trucos complicados de línea de comandos—solo código puro de C# que puedes insertar en cualquier proyecto .NET. + +## Lo que aprenderás + +- Cómo **render webpage to PNG** usando la clase `HTMLDocument` de Aspose.HTML. +- Los pasos exactos para **set image size rendering** de modo que la salida coincida con los requisitos de tu diseño. +- Formas de **write image to file** de manera segura, manejando streams y rutas de archivo. +- Consejos para solucionar problemas comunes como fuentes faltantes o tiempos de espera de red. + +### Requisitos previos + +- .NET 6.0 o superior (la API también funciona con .NET Framework, pero se recomienda .NET 6+). +- Una referencia al paquete NuGet Aspose.HTML for .NET (`Aspose.Html`). +- Familiaridad básica con C# y async/await (opcional pero útil). + +Si ya cuentas con eso, estás listo para comenzar a **convert HTML to image** de inmediato. + +## Paso 1: Cargar la página web – La base de la conversión de HTML a Imagen + +Antes de que pueda ocurrir cualquier renderizado, necesitas una instancia de `HTMLDocument` que represente la página que deseas capturar. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Por qué esto importa:* El `HTMLDocument` analiza el HTML, resuelve CSS y construye el DOM. Si el documento no puede cargarse (p. ej., problema de red), el renderizado posterior producirá una imagen en blanco. Verifica siempre que la URL sea accesible antes de continuar. + +## Paso 2: Configurar el renderizado del tamaño de la imagen – Controlando ancho, alto y calidad + +Aspose.HTML te permite afinar las dimensiones de salida con `ImageRenderingOptions`. Aquí es donde **set image size rendering** se ajusta para coincidir con el diseño objetivo. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Consejo profesional:* Si omites `Width` y `Height`, Aspose.HTML usará el tamaño intrínseco de la página, lo que puede ser impredecible en diseños responsivos. Especificar dimensiones explícitas garantiza que tu salida **save HTML as PNG** se vea exactamente como esperas. + +## Paso 3: Guardar la imagen en archivo – Persistiendo el PNG renderizado + +Ahora que el documento está listo y las opciones de renderizado están configuradas, finalmente puedes **write image to file**. Usar un `FileStream` asegura que el archivo se cree de forma segura, incluso si la carpeta aún no existe. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +Después de ejecutar este bloque, encontrarás `page.png` en la ubicación que especificaste. Acabas de **render webpage to PNG** y guardarlo en disco en una única operación sencilla. + +### Resultado esperado + +Abre `C:\Temp\page.png` con cualquier visor de imágenes. Deberías ver una captura fiel de `https://example.com`, renderizada a 1024 × 768 píxeles con bordes suaves gracias al antialiasing. Si la página contiene contenido dinámico (p. ej., elementos generados por JavaScript), se capturará siempre que el DOM esté completamente cargado antes del renderizado. + +## Paso 4: Manejo de casos especiales – Fuentes, autenticación y páginas extensas + +Aunque el flujo básico funciona para la mayoría de los sitios públicos, los escenarios del mundo real a menudo presentan sorpresas: + +| Situación | Qué hacer | +|-----------|-----------| +| **Custom fonts not loading** | Inserta los archivos de fuente localmente y establece `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Pages behind authentication** | Usa la sobrecarga de `HTMLDocument` que acepta `HttpWebRequest` con cookies o tokens. | +| **Very tall pages** | Incrementa `Height` o habilita `PageScaling` en `ImageRenderingOptions` para evitar truncamientos. | +| **Memory usage spikes** | Renderiza en fragmentos usando la sobrecarga `RenderToImage` que acepta una región `Rectangle`. | + +Abordar estos matices de *write image to file* garantiza que tu pipeline de `convert html to image` se mantenga robusto en producción. + +## Paso 5: Ejemplo completo listo para copiar y pegar + +A continuación tienes el programa completo, listo para compilar. Incluye todos los pasos, manejo de errores y comentarios necesarios. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Ejecuta este programa y verás el mensaje de confirmación en la consola. El archivo PNG será exactamente lo que esperarías al **render webpage to PNG** manualmente en un navegador y tomar una captura de pantalla—solo que más rápido y totalmente automatizado. + +## Preguntas frecuentes + +**Q: ¿Puedo convertir un archivo HTML local en lugar de una URL?** +Claro. Simplemente reemplaza la URL por una ruta de archivo: `new HTMLDocument(@"C:\myPage.html")`. + +**Q: ¿Necesito una licencia para Aspose.HTML?** +Una licencia de evaluación gratuita funciona para desarrollo y pruebas. Para producción, adquiere una licencia para eliminar la marca de agua de evaluación. + +**Q: ¿Qué pasa si la página usa JavaScript para cargar contenido después de la carga inicial?** +Aspose.HTML ejecuta JavaScript de forma síncrona durante el análisis, pero los scripts de larga duración pueden requerir una demora manual. Puedes usar `HTMLDocument.WaitForReadyState` antes de renderizar. + +## Conclusión + +Ahora dispones de una solución sólida de extremo a extremo para **convert HTML to image** en C#. Siguiendo los pasos anteriores puedes **save HTML as PNG**, **set image size rendering** con precisión y **write image to file** con confianza en cualquier entorno Windows o Linux. + +Desde capturas de pantalla simples hasta generación automatizada de informes, esta técnica escala sin problemas. A continuación, prueba con otros formatos de salida como JPEG o BMP, o integra el código en una API ASP.NET Core que devuelva el PNG directamente a los llamadores. Las posibilidades son prácticamente infinitas. + +¡Feliz codificación, y que tus imágenes renderizadas siempre se vean pixel‑perfectas! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/spanish/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..f9d6937d8 --- /dev/null +++ b/html/spanish/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-03-21 +description: Crea PDF a partir de HTML rápidamente usando Aspose HTML. Aprende a renderizar + HTML a PDF, convertir HTML a PDF y cómo usar Aspose en un tutorial conciso. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: es +og_description: Crea PDF a partir de HTML con Aspose en C#. Esta guía muestra cómo + renderizar HTML a PDF, convertir HTML a PDF y cómo usar Aspose de manera eficaz. +og_title: Crear PDF a partir de HTML – Tutorial completo de Aspose C# +tags: +- Aspose +- C# +- PDF generation +title: Crear PDF a partir de HTML con Aspose – Guía paso a paso en C# +url: /es/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear PDF a partir de HTML con Aspose – Guía paso a paso en C# + +¿Alguna vez necesitaste **crear PDF a partir de HTML** pero no estabas seguro de qué biblioteca te daría resultados perfectos a nivel de píxel? No estás solo. Muchos desarrolladores tropiezan cuando intentan convertir un fragmento web en un documento imprimible, solo para terminar con texto borroso o diseños rotos. + +La buena noticia es que Aspose HTML hace que todo el proceso sea sencillo. En este tutorial recorreremos el código exacto que necesitas para **renderizar HTML a PDF**, exploraremos por qué cada configuración es importante y te mostraremos cómo **convertir HTML a PDF** sin trucos ocultos. Al final, sabrás **cómo usar Aspose** para generar PDFs confiables en cualquier proyecto .NET. + +## Requisitos previos – Lo que necesitarás antes de comenzar + +- **.NET 6.0 o posterior** (el ejemplo también funciona en .NET Framework 4.7+) +- **Visual Studio 2022** o cualquier IDE que soporte C# +- **Aspose.HTML for .NET** paquete NuGet (prueba gratuita o versión con licencia) +- Un entendimiento básico de la sintaxis de C# (no se requiere conocimiento profundo de PDF) + +Si ya los tienes, estás listo para comenzar. De lo contrario, descarga el SDK más reciente de .NET e instala el paquete NuGet con: + +```bash +dotnet add package Aspose.HTML +``` + +Esa única línea incluye todo lo necesario para la conversión **aspose html to pdf**. + +--- + +## Paso 1: Configura tu proyecto para crear PDF a partir de HTML + +Lo primero que haces es crear una nueva aplicación de consola (o integrar el código en un servicio existente). Aquí tienes un esqueleto mínimo de `Program.cs`: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Consejo profesional:** Si ves `Aspise.Html.Rendering.Text` en ejemplos antiguos, reemplázalo por `Aspose.Html.Rendering.Text`. El error tipográfico provocará un error de compilación. + +Tener los espacios de nombres correctos asegura que el compilador pueda localizar la clase **TextOptions** que necesitaremos más adelante. + +## Paso 2: Construye el documento HTML (Renderizar HTML a PDF) + +Ahora creamos el HTML de origen. Aspose te permite pasar una cadena cruda, una ruta de archivo o incluso una URL. Para esta demo lo mantendremos simple: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +¿Por qué pasar una cadena? Evita operaciones de E/S en el sistema de archivos, acelera la conversión y garantiza que el HTML que ves en el código sea exactamente lo que se renderiza. Si prefieres cargar desde un archivo, simplemente reemplaza el argumento del constructor por una URI de archivo. + +## Paso 3: Ajusta la renderización de texto (Convertir HTML a PDF con mejor calidad) + +La renderización del texto a menudo determina si tu PDF se ve nítido o borroso. Aspose ofrece una clase `TextOptions` que permite habilitar el hinting sub‑pixel — esencial para salidas de alta DPI. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Habilitar `UseHinting` es especialmente útil cuando el HTML de origen contiene fuentes personalizadas o tamaños de fuente pequeños. Sin ello, podrías notar bordes dentados en el PDF final. + +## Paso 4: Adjunta las opciones de texto a la configuración de renderizado PDF (Cómo usar Aspose) + +A continuación, vinculamos esas opciones de texto al renderizador PDF. Aquí es donde **aspose html to pdf** realmente brilla — todo, desde el tamaño de página hasta la compresión, se puede ajustar. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Puedes omitir `PageSetup` si te conformas con el tamaño A4 predeterminado. La idea clave es que el objeto `TextOptions` vive dentro de `PdfRenderingOptions`, y así le indicas a Aspose *cómo* renderizar el texto. + +## Paso 5: Renderiza el HTML y guarda el PDF (Convertir HTML a PDF) + +Finalmente, transmitimos la salida a un archivo. Usar un bloque `using` garantiza que el manejador del archivo se cierre correctamente, incluso si ocurre una excepción. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Al ejecutar el programa, encontrarás `output.pdf` junto al ejecutable. Ábrelo y deberías ver un encabezado y un párrafo limpios, exactamente como se definieron en la cadena HTML. + +### Resultado esperado + +![ejemplo de salida de crear pdf desde html](https://example.com/images/pdf-output.png "ejemplo de salida de crear pdf desde html") + +*La captura de pantalla muestra el PDF generado con el encabezado “Hello, Aspose!” renderizado nítidamente gracias al hinting de texto.* + +--- + +## Preguntas comunes y casos límite + +### 1. ¿Qué pasa si mi HTML hace referencia a recursos externos (imágenes, CSS)? + +Aspose resuelve URLs relativas basándose en el URI base del documento. Si estás proporcionando una cadena cruda, establece el URI base manualmente: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Ahora cualquier `` se buscará de forma relativa a `C:/MyProject/`. + +### 2. ¿Cómo incrusto fuentes que no están instaladas en el servidor? + +Agrega un bloque ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Paso 4: Configurar las opciones de guardado para usar el almacenamiento personalizado + +`HtmlSaveOptions` nos permite indicar a Aspose que empaquete todo en un archivo ZIP. La propiedad `OutputStorage` (heredada) recibe nuestra instancia `MyStorage`. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Nota:** En Aspose HTML 23.9+ la propiedad se llama `OutputStorage` pero está marcada como obsoleta. La alternativa moderna es `ZipOutputStorage`. El código a continuación funciona con ambas porque la interfaz es la misma. + +### Paso 5: Guardar el documento como un archivo ZIP + +Elige una carpeta de destino (o stream) y deja que Aspose haga el trabajo pesado. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Cuando el programa termine encontrarás `output.zip` que contiene: + +* `index.html` – el documento principal. +* Cualquier imagen, archivo CSS o script incrustado (si tu HTML los referenciaba). + +Puedes abrir el ZIP con cualquier gestor de archivos para verificar la estructura. + +--- + +## Verificando el resultado (opcional) + +Si quieres inspeccionar programáticamente el archivo sin extraerlo al disco: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Salida típica: + +``` +- index.html (452 bytes) +``` + +Si tenías imágenes o CSS, aparecerían como entradas adicionales. Esta verificación rápida confirma que **create html zip archive** funcionó como se esperaba. + +--- + +## Preguntas frecuentes y casos límite + +| Pregunta | Respuesta | +|----------|-----------| +| **¿Qué pasa si necesito escribir el ZIP directamente a un stream de respuesta?** | Devuelve el `MemoryStream` que obtienes de `MyStorage` después de `document.Save`. Conviértelo a `byte[]` y escríbelo en `HttpResponse.Body`. | +| **Mi HTML referencia URLs externas—¿se descargarán?** | No. Aspose solo empaqueta los recursos que están *incrustados* (p.ej., `` o archivos locales). Para recursos remotos debes descargarlos primero y ajustar el marcado. | +| **La propiedad `OutputStorage` está marcada como obsoleta—¿debería ignorarla?** | Aún funciona, pero la nueva `ZipOutputStorage` ofrece la misma API con un nombre diferente. Reemplaza `OutputStorage` por `ZipOutputStorage` si deseas una compilación sin advertencias. | +| **¿Puedo encriptar el ZIP?** | Sí. Después de guardar, abre el archivo con `System.IO.Compression.ZipArchive` y establece una contraseña usando bibliotecas de terceros como `SharpZipLib`. Aspose en sí no proporciona encriptación. | + +## Ejemplo completo funcional (Copiar‑Pegar) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Ejecuta el programa, abre `output.zip`, y verás un único archivo `index.html` que muestra el encabezado “Hello from ZIP!” al abrirse en un navegador. + +## Conclusión + +Ahora sabes **cómo guardar HTML como ZIP** en C# usando una clase de **almacenamiento personalizado**, cómo **exportar HTML a ZIP**, y cómo **crear un archivo zip HTML** listo para distribución. El patrón es flexible—sustituye `MemoryStream` por un stream en la nube, añade encriptación, o intégralo en una API web que devuelva el ZIP bajo demanda. El cielo es el límite cuando combinas las capacidades ZIP de Aspose.HTML con tu propia lógica de almacenamiento. + +¿Listo para el siguiente paso? Prueba alimentando una página web completa con imágenes y estilos, o conecta el almacenamiento a Azure Blob Storage para evitar por completo el sistema de archivos local. El cielo es el límite cuando combinas las capacidades ZIP de Aspose.HTML con tu propia lógica de almacenamiento. + +¡Feliz codificación, y que tus archivos siempre estén ordenados! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/swedish/net/generate-jpg-and-png-images/_index.md b/html/swedish/net/generate-jpg-and-png-images/_index.md index 39785fb46..929740d62 100644 --- a/html/swedish/net/generate-jpg-and-png-images/_index.md +++ b/html/swedish/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Lär dig att använda Aspose.HTML för .NET för att manipulera HTML-dokument, k Lär dig hur du aktiverar kantutjämning för att förbättra bildkvaliteten när du konverterar DOCX-dokument till PNG eller JPG med Aspose.HTML. ### [Konvertera DOCX till PNG – skapa zip‑arkiv C#‑handledning](./convert-docx-to-png-create-zip-archive-c-tutorial/) Lär dig hur du konverterar DOCX-filer till PNG-bilder och packar dem i ett zip‑arkiv med C# och Aspose.HTML. +### [Konvertera HTML till PNG – Fullständig C#-guide med ZIP‑export](./convert-html-to-png-full-c-guide-with-zip-export/) +Lär dig hur du konverterar HTML till PNG i C#, exporterar bilder till ett ZIP‑arkiv och optimerar processen med Aspose.HTML. ## Slutsats diff --git a/html/swedish/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/swedish/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..59e4a02e8 --- /dev/null +++ b/html/swedish/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Konvertera HTML till PNG och rendera HTML som bild samtidigt som du sparar + HTML i en ZIP. Lär dig att tillämpa teckensnittsstil i HTML och lägga till fetstil + på p‑element på bara några få steg. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: sv +og_description: Konvertera HTML till PNG snabbt. Den här guiden visar hur du renderar + HTML som bild, sparar HTML till ZIP, tillämpar teckensnittsstil på HTML och lägger + till fetstil på p‑element. +og_title: Konvertera HTML till PNG – Komplett C#‑handledning +tags: +- Aspose +- C# +title: Konvertera HTML till PNG – Fullständig C#‑guide med ZIP‑export +url: /sv/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konvertera HTML till PNG – Fullständig C#-guide med ZIP-export + +Har du någonsin behövt **convert HTML to PNG** men varit osäker på vilket bibliotek som kan göra det utan att dra in en headless‑browser? Du är inte ensam. I många projekt—e‑post‑miniatyrer, dokumentations‑förhandsvisningar eller snabbbilder—är det ett verkligt behov att omvandla en webbsida till en statisk bild. + +Den goda nyheten? Med Aspose.HTML kan du **render HTML as image**, justera markupen i farten och till och med **save HTML to ZIP** för senare distribution. I den här handledningen går vi igenom ett komplett, körbart exempel som **applies font style HTML**, specifikt **add bold to p**‑element, innan vi skapar en PNG‑fil. I slutet har du en enda C#‑klass som gör allt från att ladda en sida till att arkivera dess resurser. + +## Vad du behöver + +- .NET 6.0 eller senare (API:et fungerar även på .NET Core) +- Aspose.HTML för .NET 6+ (NuGet‑paketet `Aspose.Html`) +- Grundläggande förståelse för C#‑syntax (inga avancerade koncept krävs) + +Det är allt. Inga externa webbläsare, ingen phantomjs, bara ren hanterad kod. + +## Steg 1 – Ladda HTML‑dokumentet + +Först tar vi in källfilen (eller URL) i ett `HTMLDocument`‑objekt. Detta steg är grunden för både **render html as image** och **save html to zip** senare. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Varför detta är viktigt:* `HTMLDocument`‑klassen parsar markupen, bygger ett DOM och löser upp länkade resurser (CSS, bilder, typsnitt). Utan ett korrekt dokumentobjekt kan du inte manipulera stilar eller rendera någonting. + +## Steg 2 – Tillämpa fontstil‑HTML (lägg till fetstil för p) + +Nu kommer vi att **apply font style HTML** genom att iterera över varje `

`‑element och sätta dess `font-weight` till bold. Detta är det programatiska sättet att **add bold to p**‑taggar utan att röra den ursprungliga filen. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Proffstips:* Om du bara behöver fetstila ett delmängd, ändra selektorn till något mer specifikt, t.ex. `"p.intro"`. + +## Steg 3 – Rendera HTML som bild (Convert HTML to PNG) + +När DOM‑en är klar konfigurerar vi `ImageRenderingOptions` och anropar `RenderToImage`. Här sker magin med **convert html to png**. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Varför alternativen är viktiga:* Att sätta en fast bredd/höjd förhindrar att utskriften blir för stor, medan antialiasing ger ett mjukare visuellt resultat. Du kan också byta `options` till `ImageFormat.Jpeg` om du föredrar en mindre filstorlek. + +## Steg 4 – Spara HTML till ZIP (paketera resurser) + +Ofta behöver du leverera den ursprungliga HTML‑filen tillsammans med dess CSS, bilder och typsnitt. Aspose.HTML:s `ZipArchiveSaveOptions` gör exakt det. Vi kopplar också in en anpassad `ResourceHandler` så att alla externa resurser skrivs till samma mapp som arkivet. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Edge case:* Om din HTML refererar till fjärrbilder som kräver autentisering, kommer standard‑handlaren att misslyckas. I det scenariot kan du utöka `MyResourceHandler` för att injicera HTTP‑rubriker. + +## Steg 5 – Koppla ihop allt i en enda konverteringsklass + +Nedan är den kompletta, färdiga att köra‑klassen som binder ihop alla föregående steg. Du kan kopiera‑klistra in den i en konsolapp, anropa `Convert` och se filerna dyka upp. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Förväntad utdata + +Efter att ha kört kodsnutten ovan hittar du två filer i `outputDirectory`: + +| Fil | Beskrivning | +|------|-------------| +| `page.png` | En 1200 × 800 PNG‑rendering av käll‑HTML, med varje stycke visat i **bold**. | +| `archive.zip` | Ett ZIP‑paket som innehåller den ursprungliga `input.html`, dess CSS, bilder och eventuella web‑fonts – perfekt för offline‑distribution. | + +Du kan öppna `page.png` i någon bildvisare för att verifiera att fetstil‑formatet har tillämpats, och extrahera `archive.zip` för att se den orörda HTML‑filen tillsammans med dess resurser. + +## Vanliga frågor & fallgropar + +- **Vad händer om HTML‑filen innehåller JavaScript?** + Aspose.HTML **utför inte** skript under rendering, så dynamiskt innehåll visas inte. För fullt renderade sidor skulle du behöva en headless‑browser, men för statiska mallar är detta tillvägagångssätt snabbare och lättare. + +- **Kan jag ändra utdataformatet till JPEG eller BMP?** + Ja—byt `ImageRenderingOptions`‑egenskapen `ImageFormat`, t.ex. `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Behöver jag manuellt disponera `HTMLDocument`?** + Klassen implementerar `IDisposable`. I en långlivad tjänst omsluter du den i ett `using`‑block eller anropar `document.Dispose()` när du är klar. + +- **Hur fungerar den anpassade `MyResourceHandler`?** + Den tar emot varje extern resurs (CSS, bilder, typsnitt) och skriver den till den mapp du anger. Detta säkerställer att ZIP‑filen innehåller en trogen kopia av allt som HTML‑filen refererar till. + +## Slutsats + +Du har nu en kompakt, produktionsklar lösning som **convert html to png**, **render html as image**, **save html to zip**, **apply font style html** och **add bold to p**—allt i ett fåtal C#‑rader. Koden är självständig, fungerar med .NET 6+ och kan släppas in i vilken backend‑tjänst som helst som behöver snabba visuella ögonblicksbilder av webbinnehåll. + +Redo för nästa steg? Prova att byta renderingsstorlek, experimentera med andra CSS‑egenskaper (som `font-family` eller `color`), eller integrera denna konverterare i en ASP.NET Core‑endpoint som returnerar PNG‑filen på begäran. Möjligheterna är oändliga, och med Aspose.HTML undviker du tunga webbläsardependenser. + +Om du stötte på problem eller har idéer för utökningar, lämna en kommentar nedan. Lycka till med kodandet! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/swedish/net/html-document-manipulation/_index.md index b766c5742..e4ce46182 100644 --- a/html/swedish/net/html-document-manipulation/_index.md +++ b/html/swedish/net/html-document-manipulation/_index.md @@ -72,9 +72,9 @@ Lås upp potentialen för webbutveckling med Aspose.HTML för .NET. Skapa, konve ### [Skapa HTML från sträng i C# – Anpassad resurs‑hanterare guide](./create-html-from-string-in-c-custom-resource-handler-guide/) Lär dig hur du skapar HTML från en sträng i C# med en anpassad resurs‑hanterare i Aspose.HTML för .NET. -## Slutsats +### [Skapa HTML-dokument C# – Steg‑för‑steg‑guide](./create-html-document-c-step-by-step-guide/) +Lär dig att skapa ett HTML‑dokument i C# med Aspose.HTML. En steg‑för‑steg‑guide för utvecklare. -Sammanfattningsvis, om du vill behärska HTML-dokumentmanipulation med Aspose.HTML för .NET, är du på rätt plats. Våra tutorials är din färdplan till framgång. Gör dig redo att utforska möjligheterna, lås upp din kreativitet och effektivisera din .NET-utveckling. Börja din resa idag och se dina HTML-dokument förvandlas framför dina ögon. Oavsett om du är en utvecklare eller entusiast, har Aspose.HTML för .NET något otroligt i beredskap för dig. Så vad väntar du på? Låt oss ge oss ut på detta spännande äventyr tillsammans! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/html/swedish/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/swedish/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..82ddf7b51 --- /dev/null +++ b/html/swedish/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: Skapa ett HTML‑dokument i C# och lär dig hur du hämtar ett element med + id, lokalisera ett element med id, ändra HTML‑elementets stil och lägga till fet + och kursiv med Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: sv +og_description: Skapa HTML-dokument i C# och lär dig omedelbart att hämta element + efter id, lokalisera element efter id, ändra HTML-elementets stil och lägga till + fet och kursiv med tydliga kodexempel. +og_title: Skapa HTML-dokument C# – Komplett programmeringsguide +tags: +- Aspose.Html +- C# +- DOM manipulation +title: Skapa HTML-dokument C# – Steg‑för‑steg guide +url: /sv/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa HTML-dokument C# – Steg‑för‑steg‑guide + +Ever needed to **create HTML document C#** from scratch and then tweak a single paragraph’s look? You’re not the only one. In many web‑automation projects you’ll spin up an HTML file, hunt down a tag by its ID, and then apply some styling—often bold + italic—without ever touching a browser. + +In this tutorial we’ll walk through exactly that: we’ll create an HTML document in C#, **get element by id**, **locate element by id**, **change HTML element style**, and finally **add bold italic** using the Aspose.Html library. By the end you’ll have a fully runnable snippet you can drop into any .NET project. + +## Vad du behöver + +- .NET 6 eller senare (koden fungerar även på .NET Framework 4.7+) +- Visual Studio 2022 (eller någon annan editor du föredrar) +- NuGet‑paketet **Aspose.Html** (`Install-Package Aspose.Html`) + +Det är allt—inga extra HTML‑filer, ingen webbserver, bara några rader C#. + +## Skapa HTML-dokument C# – Initiera dokumentet + +Först och främst: du behöver ett levande `HTMLDocument`‑objekt som Aspose.Html‑motorn kan arbeta med. Tänk på det som att öppna en ny anteckningsbok där du ska skriva din markup. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Varför detta är viktigt:** Genom att skicka den råa strängen till `HTMLDocument` undviker du fil‑I/O och håller allt i minnet—perfekt för enhetstester eller generering i farten. + +## Hämta element efter ID – Hitta paragrafen + +Nu när dokumentet finns måste vi **get element by id**. DOM‑API‑et ger oss `GetElementById`, som returnerar en `IElement`‑referens eller `null` om ID‑t inte finns. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Proffstips:** Även om vår markup är liten, sparar ett null‑kontroll dig för huvudvärk när samma logik återanvänds på större, dynamiska sidor. + +## Leta upp element efter ID – Ett alternativt tillvägagångssätt + +Ibland kan du redan ha en referens till dokumentets rot och föredra en sökning i query‑stil. Att använda CSS‑väljare (`QuerySelector`) är ett annat sätt att **locate element by id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **När ska man använda vad?** `GetElementById` är marginellt snabbare eftersom det är en direkt hash‑uppslagning. `QuerySelector` briljerar när du behöver komplexa selektorer (t.ex. `div > p.highlight`). + +## Ändra HTML‑elementstil – Lägg till fet kursiv + +När du har elementet i handen är nästa steg att **change HTML element style**. Aspose.Html exponerar ett `Style`‑objekt där du kan justera CSS‑egenskaper eller använda den praktiska `WebFontStyle`‑enumerationen för att applicera flera teckensnittsegenskaper på en gång. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Den enda raden sätter elementets `font-weight` till `bold` och `font-style` till `italic`. Under huven översätter Aspose.Html enum‑värdet till den korrekta CSS‑strängen. + +### Fullt fungerande exempel + +När alla bitar sätts ihop får du ett kompakt, självständigt program som du kan kompilera och köra omedelbart: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Förväntad utskrift** + +``` +Rendered HTML: +

Hello world

+``` + +`

`‑taggen har nu ett inline `style`‑attribut som gör texten både fet och kursiv—precis vad vi ville. + +## Kantfall & vanliga fallgropar + +| Situation | Vad att hålla utkik efter | Hur man hanterar | +|-----------|---------------------------|------------------| +| **ID finns inte** | `GetElementById` returnerar `null`. | Kasta ett undantag eller falla tillbaka på ett standardelement. | +| **Flera element delar samma ID** | HTML‑specen säger att ID:n måste vara unika, men verkliga sidor bryter ibland mot regeln. | `GetElementById` returnerar den första matchen; överväg att använda `QuerySelectorAll` om du behöver hantera dubbletter. | +| **Stilkonflikter** | Existerande inline‑stilar kan bli överskrivna. | Lägg till i `Style`‑objektet istället för att sätta hela `style`‑strängen: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Rendering i en webbläsare** | Vissa webbläsare ignorerar `WebFontStyle` om elementet redan har en CSS‑klass med högre specificitet. | Använd `!important` via `paragraph.Style.SetProperty("font-weight", "bold", "important");` om det behövs. | + +## Proffstips för verkliga projekt + +- **Cachea dokumentet** om du bearbetar många element; att skapa ett nytt `HTMLDocument` för varje litet snippet kan försämra prestandan. +- **Kombinera stiländringar** i en enda `Style`‑transaktion för att undvika flera DOM‑omflöden. +- **Utnyttja Aspose.Html:s renderingsmotor** för att exportera det slutliga dokumentet som PDF eller bild—perfekt för rapporteringsverktyg. + +## Visuell bekräftelse (valfritt) + +Om du föredrar att se resultatet i en webbläsare kan du spara den renderade strängen till en `.html`‑fil: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Öppna `output.html` så ser du **Hello world** visad i fet + kursiv. + +![Exempel på Skapa HTML-dokument C# som visar fet kursiv paragraf](/images/create-html-document-csharp.png "Skapa HTML-dokument C# – renderat resultat") + +*Alt‑text: Skapa HTML-dokument C# – renderat resultat med fet kursiv text.* + +## Slutsats + +Vi har just **skapat ett HTML-dokument C#**, **hämtat element efter id**, **letat upp element efter id**, **ändrat HTML‑elementstil**, och slutligen **lagt till fet kursiv**—allt med ett fåtal rader med Aspose.Html. Metoden är enkel, fungerar i alla .NET‑miljöer och skalar till större DOM‑manipulationer. + +Redo för nästa steg? Prova att byta ut `WebFontStyle` mot andra enum‑värden som `Underline` eller kombinera flera stilar manuellt. Eller experimentera med att ladda en extern HTML‑fil och applicera samma teknik på hundratals element. Himlen är gränsen, och nu har du en solid grund att bygga vidare på. + +Lycka till med kodandet! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/swedish/net/html-extensions-and-conversions/_index.md b/html/swedish/net/html-extensions-and-conversions/_index.md index 6d01c9b96..1092727d6 100644 --- a/html/swedish/net/html-extensions-and-conversions/_index.md +++ b/html/swedish/net/html-extensions-and-conversions/_index.md @@ -59,20 +59,24 @@ Lär dig hur du konverterar HTML till Markdown i .NET med Aspose.HTML för effek Konvertera HTML till MHTML i .NET med Aspose.HTML - En steg-för-steg-guide för effektiv arkivering av webbinnehåll. Lär dig hur du använder Aspose.HTML för .NET för att skapa MHTML-arkiv. ### [Konvertera HTML till PNG i .NET med Aspose.HTML](./convert-html-to-png/) Upptäck hur du använder Aspose.HTML för .NET för att manipulera och konvertera HTML-dokument. Steg-för-steg-guide för effektiv .NET-utveckling. +### [Konvertera HTML till bild i C# – Komplett guide](./convert-html-to-image-in-c-complete-guide/) +Lär dig hur du konverterar HTML till bild i C# med Aspose.HTML för .NET. En komplett steg-för-steg-guide med kodexempel och anpassningsalternativ. ### [Konvertera HTML till TIFF i .NET med Aspose.HTML](./convert-html-to-tiff/) Lär dig hur du konverterar HTML till TIFF med Aspose.HTML för .NET. Följ vår steg-för-steg-guide för effektiv optimering av webbinnehåll. ### [Konvertera HTML till XPS i .NET med Aspose.HTML](./convert-html-to-xps/) Upptäck kraften i Aspose.HTML för .NET: Konvertera HTML till XPS utan ansträngning. Förutsättningar, steg-för-steg-guide och vanliga frågor ingår. ### [Hur du zippar HTML i C# – Spara HTML till zip](./how-to-zip-html-in-c-save-html-to-zip/) Lär dig hur du packar HTML-filer i en zip-arkiv med C# och Aspose.HTML för .NET i en steg-för-steg-guide. -### [Skapa HTML-dokument med formaterad text och exportera till PDF – Fullständig guide](./create-html-document-with-styled-text-and-export-to-pdf-full/) -Lär dig skapa ett HTML-dokument med stiliserad text och konvertera det till PDF med Aspose.HTML för .NET i en komplett steg-för-steg-guide. -### [Skapa PDF från HTML – C# steg‑för‑steg‑guide](./create-pdf-from-html-c-step-by-step-guide/) -Skapa PDF från HTML med C# och Aspose.HTML för .NET. Följ vår steg‑för‑steg‑guide för enkel PDF‑generering. ### [Spara HTML som ZIP – Komplett C#-handledning](./save-html-as-zip-complete-c-tutorial/) 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 som ZIP i C# – Komplett guide med anpassad lagring](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Lär dig hur du sparar HTML som ZIP med anpassad lagring i C# med Aspose.HTML för .NET. +### [Hur du zippar HTML med Aspose.HTML – Komplett guide](./how-to-zip-html-with-aspose-html-complete-guide/) +Lär dig hur du zippar HTML-filer med Aspose.HTML i en komplett guide med kodexempel och steg-för-steg-instruktioner. +### [Skapa PDF från HTML med Aspose – Steg‑för‑steg C#‑guide](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Lär dig hur du skapar PDF från HTML i C# med Aspose i en detaljerad steg‑för‑steg‑guide. ## Slutsats diff --git a/html/swedish/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/swedish/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..c2e08cf98 --- /dev/null +++ b/html/swedish/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Konvertera HTML till bild med Aspose.HTML i C#. Lär dig hur du sparar + HTML som PNG, ställer in bildstorlek vid rendering och skriver bilden till fil på + bara några steg. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: sv +og_description: Konvertera HTML till bild snabbt. Den här guiden visar hur du sparar + HTML som PNG, ställer in bildstorlek vid rendering och skriver bilden till fil med + Aspose.HTML. +og_title: Konvertera HTML till bild i C# – Steg‑för‑steg guide +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Konvertera HTML till bild i C# – Komplett guide +url: /sv/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konvertera HTML till bild i C# – Komplett guide + +Har du någonsin behövt **konvertera HTML till bild** för en dashboard‑miniatyr, en e‑post‑förhandsgranskning eller en PDF‑rapport? Det är ett scenario som dyker upp oftare än man tror, särskilt när du hanterar dynamiskt webb‑innehåll som måste bäddas in någon annanstans. + +Den goda nyheten? Med Aspose.HTML kan du **konvertera HTML till bild** med bara några få rader kod, och du får även lära dig hur du *sparar HTML som PNG*, styr utdata‑dimensionerna och *skriver bild till fil* utan att svettas. + +I den här handledningen går vi igenom allt du behöver veta: från att ladda en fjärrsida till att justera renderingsstorleken, och slutligen spara resultatet som en PNG‑fil på disk. Inga externa verktyg, inga krångliga kommandorads‑trick – bara ren C#‑kod som du kan slänga in i vilket .NET‑projekt som helst. + +## Vad du kommer att lära dig + +- Hur du **renderar en webbsida till PNG** med Aspose.HTML:s `HTMLDocument`‑klass. +- De exakta stegen för att **ställa in bildstorlek vid rendering** så att utdata matchar dina layout‑krav. +- Sätt att **skriva bild till fil** på ett säkert sätt, hantera strömmar och filsökvägar. +- Tips för felsökning av vanliga fallgropar som saknade typsnitt eller nätverkstimeouts. + +### Förutsättningar + +- .NET 6.0 eller senare (API‑et fungerar även med .NET Framework, men .NET 6+ rekommenderas). +- En referens till Aspose.HTML för .NET NuGet‑paketet (`Aspose.Html`). +- Grundläggande kunskap om C# och async/await (valfritt men hjälpsamt). + +Om du redan har detta är du redo att börja konvertera HTML till bild direkt. + +## Steg 1: Ladda webbsidan – Grunden för att konvertera HTML till bild + +Innan någon rendering kan ske behöver du en `HTMLDocument`‑instans som representerar sidan du vill fånga. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Varför detta är viktigt:* `HTMLDocument` parser HTML, löser CSS och bygger DOM‑trädet. Om dokumentet inte kan laddas (t.ex. på grund av nätverksproblem) kommer den efterföljande renderingen att producera en tom bild. Verifiera alltid att URL:en är åtkomlig innan du går vidare. + +## Steg 2: Ställ in bildstorlek vid rendering – Kontroll av bredd, höjd och kvalitet + +Aspose.HTML låter dig finjustera utdata‑dimensionerna med `ImageRenderingOptions`. Här **ställer du in bildstorlek vid rendering** så att den matchar ditt mål‑layout. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Proffstips:* Om du utelämnar `Width` och `Height` kommer Aspose.HTML att använda sidans inneboende storlek, vilket kan vara oförutsägbart för responsiva designer. Att ange explicita dimensioner säkerställer att ditt **spara HTML som PNG**‑utdata ser exakt ut som du förväntar dig. + +## Steg 3: Skriv bild till fil – Spara den renderade PNG‑filen + +Nu när dokumentet är redo och renderingsalternativen är satta kan du äntligen **skriva bild till fil**. Att använda en `FileStream` garanterar att filen skapas på ett säkert sätt, även om mappen ännu inte finns. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +När detta block har körts hittar du `page.png` på den plats du angav. Du har just **renderat en webbsida till PNG** och skrivit den till disk i ett enda, okomplicerat steg. + +### Förväntat resultat + +Öppna `C:\Temp\page.png` i någon bildvisare. Du bör se en trogen avbildning av `https://example.com`, renderad i 1024 × 768 pixlar med mjuka kanter tack vare antialiasing. Om sidan innehåller dynamiskt innehåll (t.ex. JavaScript‑genererade element) kommer de att fångas så länge DOM är fullständigt laddad före renderingen. + +## Steg 4: Hantera kantfall – Typsnitt, autentisering och stora sidor + +Medan det grundläggande flödet fungerar för de flesta offentliga webbplatser, kastar verkliga scenarier ofta kurvbollar: + +| Situation | Vad du ska göra | +|-----------|-----------------| +| **Anpassade typsnitt laddas inte** | Bädda in typsnittsfilerna lokalt och lägg till `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Sidor bakom autentisering** | Använd `HTMLDocument`‑överladdning som accepterar `HttpWebRequest` med cookies eller token. | +| **Mycket långa sidor** | Öka `Height` eller aktivera `PageScaling` i `ImageRenderingOptions` för att undvika avklippning. | +| **Minnesanvändning skjuter i höjden** | Rendera i delar med `RenderToImage`‑överladdning som accepterar ett `Rectangle`‑område. | + +Genom att ta hänsyn till dessa *skriva bild till fil*-detaljer säkerställer du att din *konvertera HTML till bild*-pipeline förblir robust i produktion. + +## Steg 5: Fullt fungerande exempel – Kopiera‑klistra redo + +Nedan är hela programmet, redo att kompileras. Det innehåller alla steg, felhantering och kommentarer du behöver. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Kör programmet så får du ett bekräftelsemeddelande i konsolen. PNG‑filen blir exakt vad du skulle förvänta dig om du **renderar en webbsida till PNG** manuellt i en webbläsare och tar en skärmdump – bara snabbare och helt automatiserat. + +## Vanliga frågor + +**Q: Kan jag konvertera en lokal HTML‑fil istället för en URL?** +Absolut. Byt bara ut URL:en mot en filsökväg: `new HTMLDocument(@"C:\myPage.html")`. + +**Q: Behöver jag en licens för Aspose.HTML?** +En gratis utvärderingslicens fungerar för utveckling och testning. För produktion köper du en licens för att ta bort vattenstämpeln. + +**Q: Vad händer om sidan använder JavaScript för att ladda innehåll efter den initiala laddningen?** +Aspose.HTML kör JavaScript synkront under parsing, men långvariga skript kan kräva en manuell fördröjning. Du kan använda `HTMLDocument.WaitForReadyState` före rendering. + +## Slutsats + +Du har nu en solid, end‑to‑end‑lösning för att **konvertera HTML till bild** i C#. Genom att följa stegen ovan kan du **spara HTML som PNG**, exakt **ställa in bildstorlek vid rendering**, och tryggt **skriva bild till fil** på både Windows‑ och Linux‑miljöer. + +Från enkla skärmdumpar till automatiserad rapportgenerering skalar tekniken smidigt. Prova sedan att experimentera med andra utdataformat som JPEG eller BMP, eller integrera koden i ett ASP.NET Core‑API som returnerar PNG‑filen direkt till anroparna. Möjligheterna är praktiskt taget oändliga. + +Lycka till med kodandet, och må dina renderade bilder alltid vara pixel‑perfekta! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/swedish/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..b25f3544e --- /dev/null +++ b/html/swedish/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-03-21 +description: Skapa PDF från HTML snabbt med Aspose HTML. Lär dig rendera HTML till + PDF, konvertera HTML till PDF och hur du använder Aspose i en kortfattad handledning. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: sv +og_description: Skapa PDF från HTML med Aspose i C#. Denna guide visar hur man renderar + HTML till PDF, konverterar HTML till PDF och hur man använder Aspose effektivt. +og_title: Skapa PDF från HTML – Komplett Aspose C#-handledning +tags: +- Aspose +- C# +- PDF generation +title: Skapa PDF från HTML med Aspose – Steg‑för‑steg C#‑guide +url: /sv/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa PDF från HTML med Aspose – Steg‑för‑steg C#‑guide + +Har du någonsin behövt **skapa PDF från HTML** men varit osäker på vilket bibliotek som ger pixelperfekta resultat? Du är inte ensam. Många utvecklare fastnar när de försöker omvandla ett webbsnutt till ett utskrivbart dokument, bara för att få suddig text eller trasiga layouter. + +Den goda nyheten är att Aspose HTML gör hela processen smärtfri. I den här handledningen går vi igenom exakt den kod du behöver för att **rendera HTML till PDF**, utforskar varför varje inställning är viktig, och visar hur du **konverterar HTML till PDF** utan dolda knep. När du är klar vet du **hur du använder Aspose** för pålitlig PDF‑generering i alla .NET‑projekt. + +## Förutsättningar – Vad du behöver innan du börjar + +- **.NET 6.0 eller senare** (exemplet fungerar även på .NET Framework 4.7+) +- **Visual Studio 2022** eller någon IDE som stödjer C# +- **Aspose.HTML for .NET** NuGet‑paket (gratis provversion eller licensierad version) +- En grundläggande förståelse för C#‑syntax (ingen djup PDF‑kunskap krävs) + +Om du har detta är du redo att köra. Annars, hämta den senaste .NET SDK:n och installera NuGet‑paketet med: + +```bash +dotnet add package Aspose.HTML +``` + +Den enda raden hämtar allt du behöver för **aspose html to pdf**‑konvertering. + +--- + +## Steg 1: Ställ in ditt projekt för att skapa PDF från HTML + +Det första du gör är att skapa en ny konsolapp (eller integrera koden i en befintlig tjänst). Här är ett minimalt `Program.cs`‑skelett: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** Om du ser `Aspise.Html.Rendering.Text` i äldre exempel, ersätt det med `Aspose.Html.Rendering.Text`. Stavfelet kommer att orsaka ett kompileringsfel. + +Att ha rätt namnrymder säkerställer att kompilatorn kan hitta **TextOptions**‑klassen som vi kommer att behöva senare. + +## Steg 2: Bygg HTML-dokumentet (Rendera HTML till PDF) + +Nu skapar vi käll‑HTML‑en. Aspose låter dig skicka en rå sträng, en filsökväg eller till och med en URL. För den här demonstrationen håller vi det enkelt: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Varför skicka en sträng? Det undviker fil‑I/O, snabbar upp konverteringen och garanterar att HTML‑koden du ser i källan är exakt den som renderas. Om du föredrar att läsa från en fil, byt bara konstruktörsargumentet till en fil‑URI. + +## Steg 3: Finjustera textrendering (Konvertera HTML till PDF med bättre kvalitet) + +Textrendering avgör ofta om din PDF ser skarp eller suddig ut. Aspose erbjuder en `TextOptions`‑klass som låter dig aktivera sub‑pixel‑hinting – viktigt för hög‑DPI‑utdata. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Att aktivera `UseHinting` är särskilt användbart när din käll‑HTML innehåller anpassade teckensnitt eller små teckenstorlekar. Utan detta kan du märka hackiga kanter i den färdiga PDF‑en. + +## Steg 4: Bifoga textalternativ till PDF-renderingskonfiguration (Hur man använder Aspose) + +Nästa steg är att binda dessa textalternativ till PDF‑renderaren. Här glänser **aspose html to pdf** – allt från sidstorlek till komprimering kan justeras. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Du kan utelämna `PageSetup` om du är nöjd med standard A4‑storlek. Huvudpoängen är att `TextOptions`‑objektet lever inuti `PdfRenderingOptions`, och så talar du om för Aspose *hur* texten ska renderas. + +## Steg 5: Rendera HTML och spara PDF:en (Konvertera HTML till PDF) + +Till sist strömmar vi utdata till en fil. En `using`‑block garanterar att filhandtaget stängs korrekt, även om ett undantag inträffar. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +När du kör programmet hittar du `output.pdf` bredvid den körbara filen. Öppna den, så bör du se en ren rubrik och ett stycke – exakt som definierat i HTML‑strängen. + +### Förväntat resultat + +![create pdf from html example output](https://example.com/images/pdf-output.png "create pdf from html example output") + +*Skärmdumpen visar den genererade PDF‑en med rubriken “Hello, Aspose!” renderad skarpt tack vare text‑hinting.* + +--- + +## Vanliga frågor & specialfall + +### 1. Vad händer om min HTML refererar till externa resurser (bilder, CSS)? + +Aspose löser relativa URL:er baserat på dokumentets bas‑URI. Om du matar in en rå sträng, sätt bas‑URI:n manuellt: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Nu kommer varje `` att hämtas relativt till `C:/MyProject/`. + +### 2. Hur bäddar jag in teckensnitt som inte är installerade på servern? + +Lägg till ett ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Steg 4: Konfigurera sparalternativ för att använda custom storage + +`HtmlSaveOptions` låter oss säga åt Aspose att packa allt i en ZIP‑fil. `OutputStorage`‑egenskapen (legacy) får vår `MyStorage`‑instans. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Obs:** I Aspose HTML 23.9+ heter egenskapen `OutputStorage` fortfarande men är markerad som föråldrad. Det moderna alternativet är `ZipOutputStorage`. Koden nedan fungerar med båda eftersom gränssnittet är detsamma. + +### Steg 5: Spara dokumentet som ett ZIP‑arkiv + +Välj en mål‑mapp (eller stream) och låt Aspose göra det tunga arbetet. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +När programmet är klart hittar du `output.zip` som innehåller: + +* `index.html` – huvuddokumentet. +* Eventuella inbäddade bilder, CSS‑filer eller skript (om din HTML refererade dem). + +Du kan öppna ZIP‑filen med valfri arkivhanterare för att verifiera strukturen. + +--- + +## Verifiera resultatet (valfritt) + +Om du vill inspektera arkivet programatiskt utan att extrahera det till disk: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Typisk utskrift: + +``` +- index.html (452 bytes) +``` + +Om du hade bilder eller CSS skulle de visas som ytterligare poster. Denna snabba kontroll bekräftar att **create html zip archive** fungerade som förväntat. + +--- + +## Vanliga frågor & kantfall + +| Fråga | Svar | +|----------|--------| +| **Vad gör jag om jag måste skriva ZIP‑filen direkt till ett svar‑stream?** | Returnera `MemoryStream` du får från `MyStorage` efter `document.Save`. Casta den till en `byte[]` och skriv den till `HttpResponse.Body`. | +| **Min HTML refererar till externa URL‑er – laddas de ner?** | Nej. Aspose packar endast resurser som är *inbäddade* (t.ex. `` eller lokala filer). För fjärrresurser måste du ladda ner dem först och justera markupen. | +| **`OutputStorage`‑egenskapen är markerad som föråldrad – ska jag ignorera den?** | Den fungerar fortfarande, men den nyare `ZipOutputStorage` erbjuder samma API med ett annat namn. Byt ut `OutputStorage` mot `ZipOutputStorage` om du vill ha en varningsfri build. | +| **Kan jag kryptera ZIP‑filen?** | Ja. Efter sparandet kan du öppna filen med `System.IO.Compression.ZipArchive` och sätta ett lösenord via tredjepartsbibliotek som `SharpZipLib`. Aspose själv erbjuder ingen kryptering. | + +--- + +## Fullt fungerande exempel (kopiera‑klistra) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Kör programmet, öppna `output.zip` och du ser en ensam `index.html`‑fil som visar rubriken “Hello from ZIP!” när den öppnas i en webbläsare. + +--- + +## Slutsats + +Du vet nu **hur du sparar HTML som ZIP** i C# med en **custom storage**‑klass, hur du **exporterar HTML till ZIP**, och hur du **skapar ett HTML‑zip‑arkiv** som är redo för distribution. Mönstret är flexibelt – byt `MemoryStream` mot en moln‑stream, lägg till kryptering eller integrera det i ett web‑API som returnerar ZIP‑filen på begäran. + +Redo för nästa steg? Prova att mata in en fullständig webbsida med bilder och stilar, eller koppla lagringen till Azure Blob Storage för att helt undvika lokalt filsystem. Himlen är gränsen när du kombinerar Aspose.HTML:s ZIP‑funktioner med din egen lagringslogik. + +Happy coding, and may your archives always be tidy! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/thai/net/generate-jpg-and-png-images/_index.md b/html/thai/net/generate-jpg-and-png-images/_index.md index bb3254275..9711e8a67 100644 --- a/html/thai/net/generate-jpg-and-png-images/_index.md +++ b/html/thai/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Aspose.HTML สำหรับ .NET นำเสนอวิธีการง เรียนรู้วิธีเปิดใช้งาน Antialiasing เพื่อให้ภาพ PNG/JPG ที่แปลงจาก DOCX มีความคมชัดและลื่นไหล ### [แปลง DOCX เป็น PNG – สร้างไฟล์ ZIP ด้วย C#](./convert-docx-to-png-create-zip-archive-c-tutorial/) เรียนรู้วิธีแปลงไฟล์ DOCX เป็น PNG แล้วบีบอัดเป็นไฟล์ ZIP ด้วย C# โดยใช้ Aspose.HTML +### [แปลง HTML เป็น PNG – คู่มือ C# เต็มรูปแบบพร้อมการส่งออก ZIP](./convert-html-to-png-full-c-guide-with-zip-export/) +เรียนรู้วิธีแปลง HTML เป็นไฟล์ PNG และบีบอัดเป็นไฟล์ ZIP ด้วย C# อย่างละเอียด ## บทสรุป diff --git a/html/thai/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/thai/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..4829814f6 --- /dev/null +++ b/html/thai/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-03-21 +description: แปลง HTML เป็น PNG และแสดง HTML เป็นภาพพร้อมบันทึก HTML เป็นไฟล์ ZIP + เรียนรู้วิธีใช้สไตล์ฟอนต์ใน HTML และเพิ่มตัวหนาให้กับแท็ก p เพียงไม่กี่ขั้นตอน. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: th +og_description: แปลง HTML เป็น PNG อย่างรวดเร็ว คู่มือนี้แสดงวิธีเรนเดอร์ HTML เป็นภาพ, + บันทึก HTML เป็นไฟล์ ZIP, ใช้สไตล์ฟอนต์ใน HTML และเพิ่มตัวหนาให้กับแท็ก p. +og_title: แปลง HTML เป็น PNG – บทเรียน C# ฉบับสมบูรณ์ +tags: +- Aspose +- C# +title: แปลง HTML เป็น PNG – คู่มือ C# เต็มรูปแบบพร้อมการส่งออกเป็น ZIP +url: /th/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# แปลง HTML เป็น PNG – คู่มือ C# เต็มรูปแบบพร้อมการส่งออก ZIP + +เคยต้อง **แปลง HTML เป็น PNG** แต่ไม่แน่ใจว่ามีไลบรารีไหนทำได้โดยไม่ต้องดึงเบราว์เซอร์แบบ headless หรือไม่? คุณไม่ได้อยู่คนเดียว ในหลายโครงการ—เช่น รูปย่ออีเมล, ตัวอย่างเอกสาร, หรือภาพดูอย่างรวดเร็ว—การเปลี่ยนหน้าเว็บเป็นภาพคงที่เป็นความต้องการที่พบเจอจริง + +ข่าวดีคือ? ด้วย Aspose.HTML คุณสามารถ **render HTML as image**, ปรับแต่ง markup ได้ทันที, และแม้กระทั่ง **save HTML to ZIP** เพื่อการแจกจ่ายในภายหลัง ในบทแนะนำนี้เราจะเดินผ่านตัวอย่างที่สมบูรณ์และรันได้ ซึ่ง **applies font style HTML**, โดยเฉพาะ **add bold to p** ก่อนสร้างไฟล์ PNG สุดท้าย เมื่อเสร็จคุณจะมีคลาส C# เดียวที่ทำทุกอย่างตั้งแต่โหลดหน้าเว็บจนถึงบันทึกทรัพยากรเป็นไฟล์ archive + +## สิ่งที่คุณต้องเตรียม + +- .NET 6.0 หรือใหม่กว่า (API ทำงานบน .NET Core ด้วย) +- Aspose.HTML for .NET 6+ (แพ็กเกจ NuGet `Aspose.Html`) +- ความเข้าใจพื้นฐานของไวยากรณ์ C# (ไม่ต้องการความรู้ขั้นสูง) + +เท่านี้เอง ไม่ต้องใช้เบราว์เซอร์ภายนอก, ไม่ต้องใช้ phantomjs, เพียงโค้ดที่จัดการด้วย .NET เท่านั้น + +## Step 1 – Load the HTML Document + +ก่อนอื่นเรานำไฟล์ต้นฉบับ (หรือ URL) เข้าไปในอ็อบเจ็กต์ `HTMLDocument` ขั้นตอนนี้เป็นพื้นฐานสำหรับทั้ง **render html as image** และ **save html to zip** ในภายหลัง + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*ทำไมขั้นตอนนี้สำคัญ:* คลาส `HTMLDocument` จะทำการพาร์ส markup, สร้าง DOM, และแก้ไขการอ้างอิงทรัพยากรที่เชื่อมโยง (CSS, รูปภาพ, ฟอนต์) หากไม่มีอ็อบเจ็กต์เอกสารที่ถูกต้อง คุณจะไม่สามารถจัดการสไตล์หรือทำการเรนเดอร์ได้ + +## Step 2 – Apply Font Style HTML (Add Bold to p) + +ต่อไปเราจะ **apply font style HTML** โดยวนลูปทุกองค์ประกอบ `

` และตั้งค่า `font-weight` ให้เป็น bold นี่คือวิธีโปรแกรมเมติกเพื่อ **add bold to p** โดยไม่ต้องแก้ไฟล์ต้นฉบับ + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*เคล็ดลับ:* หากคุณต้องการทำให้ตัวอักษรหนาเฉพาะบางส่วน ให้เปลี่ยน selector ให้เจาะจงมากขึ้น เช่น `"p.intro"` + +## Step 3 – Render HTML as Image (Convert HTML to PNG) + +เมื่อ DOM พร้อม เราตั้งค่า `ImageRenderingOptions` แล้วเรียก `RenderToImage` ที่นี่คือจุดที่ **convert html to png** เกิดขึ้น + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*ทำไมตัวเลือกเหล่านี้สำคัญ:* การกำหนดความกว้าง/สูงคงที่ช่วยป้องกันผลลัพธ์ที่ใหญ่เกินไป, ส่วน antialiasing ทำให้ภาพดูเรียบเนียนขึ้น คุณยังสามารถสลับ `options` ไปเป็น `ImageFormat.Jpeg` หากต้องการไฟล์ขนาดเล็กกว่า + +## Step 4 – Save HTML to ZIP (Bundle Resources) + +บ่อยครั้งที่คุณต้องส่งมอบ HTML ดั้งเดิมพร้อมกับ CSS, รูปภาพ, และฟอนต์ของมัน `ZipArchiveSaveOptions` ของ Aspose.HTML ทำหน้าที่นี้ได้อย่างแม่นยำ เรายังต่อ `ResourceHandler` แบบกำหนดเองเพื่อให้ทรัพยากรภายนอกทั้งหมดถูกเขียนลงในโฟลเดอร์เดียวกับไฟล์ archive + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*กรณีขอบ:* หาก HTML ของคุณอ้างอิงรูปภาพจากระยะไกลที่ต้องการการยืนยันตัวตน ตัวจัดการเริ่มต้นจะล้มเหลว ในสถานการณ์นี้คุณสามารถขยาย `MyResourceHandler` เพื่อใส่ HTTP headers เพิ่มเติมได้ + +## Step 5 – Wire Everything Up in a Single Converter Class + +ด้านล่างเป็นคลาสเต็มรูปแบบที่พร้อมรัน ซึ่งเชื่อมต่อทุกขั้นตอนที่กล่าวมาข้างต้น คุณสามารถคัดลอก‑วางลงในแอปคอนโซล, เรียก `Convert`, แล้วดูไฟล์ที่สร้างขึ้น + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### ผลลัพธ์ที่คาดหวัง + +หลังจากรันโค้ดข้างต้น คุณจะพบไฟล์สองไฟล์ใน `outputDirectory`: + +| ไฟล์ | คำอธิบาย | +|------|-----------| +| `page.png` | PNG ขนาด 1200 × 800 ที่เรนเดอร์จาก HTML ต้นฉบับ, ทุกย่อหน้าจะแสดงเป็น **bold** | +| `archive.zip` | แพคเกจ ZIP ที่บรรจุ `input.html` ดั้งเดิม, CSS, รูปภาพ, และเว็บ‑ฟอนต์ – เหมาะสำหรับการแจกจ่ายแบบออฟไลน์ | + +คุณสามารถเปิด `page.png` ด้วยโปรแกรมดูรูปใดก็ได้เพื่อยืนยันว่าการทำให้ตัวอักษรหนาถูกนำไปใช้, และแตก `archive.zip` เพื่อดู HTML ที่ยังไม่ถูกแก้ไขพร้อมกับทรัพยากรทั้งหมด + +## คำถามที่พบบ่อย & จุดต้องระวัง + +- **ถ้า HTML มี JavaScript จะทำอย่างไร?** + Aspose.HTML **ไม่** รันสคริปต์ระหว่างการเรนเดอร์ ดังนั้นเนื้อหาแบบไดนามิกจะไม่ปรากฏ หากต้องการหน้าเต็มที่เรนเดอร์คุณต้องใช้ headless browser, แต่สำหรับเทมเพลตแบบคงที่วิธีนี้เร็วและเบากว่า + +- **สามารถเปลี่ยนรูปแบบผลลัพธ์เป็น JPEG หรือ BMP ได้หรือไม่?** + ได้ — เพียงสลับ property `ImageFormat` ของ `ImageRenderingOptions` เช่น `options.ImageFormat = ImageFormat.Jpeg;` + +- **ต้องทำการ dispose `HTMLDocument` ด้วยตนเองหรือไม่?** + คลาสนี้ implements `IDisposable` ดังนั้นในบริการที่ทำงานต่อเนื่องควรห่อด้วย `using` block หรือเรียก `document.Dispose()` หลังใช้งานเสร็จ + +- **`MyResourceHandler` ทำงานอย่างไร?** + ตัวจัดการนี้รับทรัพยากรภายนอกแต่ละรายการ (CSS, รูปภาพ, ฟอนต์) แล้วเขียนลงในโฟลเดอร์ที่คุณระบุ ทำให้ ZIP มีสำเนาที่ตรงกับสิ่งที่ HTML อ้างอิงทั้งหมด + +## สรุป + +ตอนนี้คุณมีโซลูชันขนาดกะทัดรัดพร้อมใช้งานในระดับ production ที่ **convert html to png**, **render html as image**, **save html to zip**, **apply font style html**, และ **add bold to p** — ทั้งหมดในไม่กี่บรรทัดของ C# โค้ดนี้เป็นอิสระ, ทำงานกับ .NET 6+, และสามารถนำไปใส่ในบริการ backend ใดก็ได้ที่ต้องการภาพสแนปช็อตของเนื้อหาเว็บอย่างรวดเร็ว + +พร้อมก้าวต่อไปหรือยัง? ลองเปลี่ยนขนาดการเรนเดอร์, ทดลองกับ CSS properties อื่น ๆ (เช่น `font-family` หรือ `color`), หรือรวม converter นี้เข้าไปใน endpoint ของ ASP.NET Core ที่ส่งคืน PNG ตามคำขอ ความเป็นไปได้ไม่มีที่สิ้นสุด, และด้วย Aspose.HTML คุณจะหลีกเลี่ยงการพึ่งพาเบราว์เซอร์หนัก ๆ + +หากคุณเจออุปสรรคหรือมีไอเดียสำหรับการต่อยอด, ฝากคอมเมนต์ไว้ด้านล่างได้เลย. Happy coding! + +![แปลง html เป็น png ตัวอย่าง](example.png "แปลง html เป็น png ตัวอย่าง") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/thai/net/html-document-manipulation/_index.md b/html/thai/net/html-document-manipulation/_index.md index 6df7d74b1..9feb84bb9 100644 --- a/html/thai/net/html-document-manipulation/_index.md +++ b/html/thai/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Aspose.HTML สำหรับ .NET โดดเด่นด้วยควา ปลดล็อกศักยภาพของการพัฒนาเว็บด้วย Aspose.HTML สำหรับ .NET สร้าง แปลง และจัดการเอกสาร HTML ได้อย่างง่ายดาย ### [สร้าง HTML จากสตริงใน C# – คู่มือ Custom Resource Handler](./create-html-from-string-in-c-custom-resource-handler-guide/) เรียนรู้วิธีสร้าง HTML จากสตริงใน C# ด้วยตัวจัดการทรัพยากรแบบกำหนดเองใน Aspose.HTML สำหรับ .NET +### [สร้างเอกสาร HTML C# – คู่มือแบบทีละขั้นตอน](./create-html-document-c-step-by-step-guide/) +เรียนรู้วิธีสร้างเอกสาร HTML ด้วย C# อย่างละเอียด พร้อมตัวอย่างโค้ดและคำอธิบายทีละขั้นตอน ## บทสรุป diff --git a/html/thai/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/thai/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..11469927b --- /dev/null +++ b/html/thai/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,188 @@ +--- +category: general +date: 2026-03-21 +description: สร้างเอกสาร HTML ด้วย C# และเรียนรู้วิธีการดึงองค์ประกอบโดยใช้ id, ค้นหาองค์ประกอบโดยใช้ + id, เปลี่ยนสไตล์ขององค์ประกอบ HTML และเพิ่มตัวหนาและตัวเอียงโดยใช้ Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: th +og_description: สร้างเอกสาร HTML ด้วย C# และเรียนรู้ทันทีวิธีดึงและค้นหาองค์ประกอบตาม + id, เปลี่ยนสไตล์ขององค์ประกอบ HTML และเพิ่มตัวหนา ตัวเอียง พร้อมตัวอย่างโค้ดที่ชัดเจน +og_title: สร้างเอกสาร HTML ด้วย C# – คู่มือการเขียนโปรแกรมครบวงจร +tags: +- Aspose.Html +- C# +- DOM manipulation +title: สร้างเอกสาร HTML C# – คู่มือแบบทีละขั้นตอน +url: /th/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างเอกสาร HTML ด้วย C# – คู่มือขั้นตอนต่อขั้นตอน + +เคยต้องการ **สร้างเอกสาร HTML ด้วย C#** ตั้งแต่ต้นแล้วปรับรูปแบบของย่อหน้าเดียวหรือไม่? คุณไม่ได้เป็นคนเดียว ในหลายโครงการเว็บ‑ออโตเมชันคุณจะสร้างไฟล์ HTML ขึ้นมา ค้นหาแท็กโดยใช้ ID ของมัน แล้วใส่สไตล์บางอย่าง—มักจะเป็นตัวหนา + ตัวเอียง—โดยไม่ต้องเปิดเบราว์เซอร์เลย. + +ในบทแนะนำนี้เราจะทำตามขั้นตอนนั้นอย่างละเอียด: เราจะสร้างเอกสาร HTML ด้วย C#, **get element by id**, **locate element by id**, **change HTML element style**, และสุดท้าย **add bold italic** โดยใช้ไลบรารี Aspose.Html. เมื่อเสร็จคุณจะได้โค้ดสั้นที่สามารถรันได้เต็มรูปแบบและสามารถนำไปใส่ในโครงการ .NET ใดก็ได้. + +## สิ่งที่คุณต้องการ + +- .NET 6 หรือใหม่กว่า (โค้ดนี้ทำงานบน .NET Framework 4.7+ ด้วย) +- Visual Studio 2022 (หรือโปรแกรมแก้ไขใดก็ได้ที่คุณชอบ) +- แพ็กเกจ NuGet **Aspose.Html** (`Install-Package Aspose.Html`) + +เท่านี้—ไม่มีไฟล์ HTML เพิ่มเติม, ไม่มีเว็บเซิร์ฟเวอร์, เพียงไม่กี่บรรทัดของ C#. + +## สร้างเอกสาร HTML ด้วย C# – เริ่มต้นเอกสาร + +อันดับแรก: คุณต้องมีอ็อบเจ็กต์ `HTMLDocument` ที่ทำงานได้ซึ่งเอ็นจินของ Aspose.Html สามารถใช้งานได้ คิดว่าเป็นการเปิดสมุดโน้ตใหม่ที่คุณจะเขียนมาร์กอัปของคุณ. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **ทำไมเรื่องนี้ถึงสำคัญ:** การส่งสตริงดิบไปยัง `HTMLDocument` ทำให้คุณหลีกเลี่ยงการทำงานกับไฟล์ I/O และเก็บทุกอย่างในหน่วยความจำ—เหมาะอย่างยิ่งสำหรับการทดสอบหน่วยหรือการสร้างแบบเรียลไทม์. + +## ดึงองค์ประกอบโดย ID – ค้นหาย่อหน้า + +เมื่อเอกสารมีอยู่แล้ว เราต้อง **get element by id**. API ของ DOM มีเมธอด `GetElementById` ซึ่งจะคืนค่าอ้างอิง `IElement` หรือ `null` หากไม่มี ID นั้น. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **เคล็ดลับ:** แม้ว่ามาร์กอัปของเราจะเล็กมาก การเพิ่มการตรวจสอบค่า null จะช่วยป้องกันปัญหาเมื่อใช้ตรรกะเดียวกันกับหน้าใหญ่หรือหน้าแบบไดนามิก. + +## ค้นหาองค์ประกอบโดย ID – วิธีทางเลือก + +บางครั้งคุณอาจมีอ้างอิงถึงรากของเอกสารแล้วต้องการค้นหาแบบ query‑style การใช้ตัวเลือก CSS (`QuerySelector`) เป็นอีกวิธีหนึ่งเพื่อ **locate element by id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **เมื่อใดควรใช้แต่ละวิธี?** `GetElementById` เร็วกว่าเล็กน้อยเพราะเป็นการค้นหาแบบแฮชโดยตรง `QuerySelector` จะโดดเด่นเมื่อคุณต้องการตัวเลือกที่ซับซ้อน (เช่น `div > p.highlight`). + +## เปลี่ยนสไตล์ขององค์ประกอบ HTML – เพิ่มตัวหนาและเอียง + +เมื่อได้องค์ประกอบแล้ว ขั้นตอนต่อไปคือ **change HTML element style**. Aspose.Html มีอ็อบเจ็กต์ `Style` ที่คุณสามารถปรับคุณสมบัติ CSS หรือใช้ enumeration `WebFontStyle` ที่สะดวกเพื่อกำหนดลักษณะฟอนต์หลายอย่างพร้อมกัน. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +บรรทัดเดียวนี้ตั้งค่า `font-weight` ขององค์ประกอบเป็น `bold` และ `font-style` เป็น `italic`. ภายใน Aspose.Html จะเปลี่ยน enum ให้เป็นสตริง CSS ที่เหมาะสม. + +### ตัวอย่างการทำงานเต็มรูปแบบ + +การรวมส่วนต่าง ๆ เข้าด้วยกันจะได้โปรแกรมขนาดกะทัดรัดและอิสระที่คุณสามารถคอมไพล์และรันได้ทันที: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**ผลลัพธ์ที่คาดหวัง** + +``` +Rendered HTML: +

Hello world

+``` + +แท็ก `

` ตอนนี้มีแอตทริบิวต์ `style` แบบอินไลน์ที่ทำให้ข้อความเป็นตัวหนาและเอียงพร้อมกัน—ตรงกับที่เราต้องการ. + +## กรณีขอบและข้อผิดพลาดทั่วไป + +| สถานการณ์ | สิ่งที่ควรระวัง | วิธีจัดการ | +|-----------|-------------------|---------------| +| **ID ไม่อยู่** | `GetElementById` คืนค่า `null`. | โยนข้อยกเว้นหรือใช้เอกสารเริ่มต้นเป็นค่าเริ่มต้น. | +| **หลายองค์ประกอบใช้ ID เดียวกัน** | สเปค HTML ระบุว่า ID ต้องเป็นเอกลักษณ์ แต่หน้าเว็บจริงบางครั้งละเมิดกฎนี้. | `GetElementById` คืนค่าแมทช์แรก; พิจารณาใช้ `QuerySelectorAll` หากต้องจัดการกับสำเนาซ้ำ. | +| **ความขัดแย้งของสไตล์** | สไตล์อินไลน์ที่มีอยู่แล้วอาจถูกเขียนทับ. | เพิ่มลงในอ็อบเจ็กต์ `Style` แทนการตั้งค่า `style` ทั้งหมด: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **การแสดงผลในเบราว์เซอร์** | บางเบราว์เซอร์อาจละเลย `WebFontStyle` หากองค์ประกอบมีคลาส CSS ที่มีความจำเพาะสูงกว่า. | ใช้ `!important` ผ่าน `paragraph.Style.SetProperty("font-weight", "bold", "important");` หากจำเป็น. | + +## เคล็ดลับสำหรับโครงการจริง + +- **Cache the document** หากคุณกำลังประมวลผลหลายองค์ประกอบ; การสร้าง `HTMLDocument` ใหม่สำหรับแต่ละสคริปต์เล็ก ๆ จะทำให้ประสิทธิภาพลดลง. +- **Combine style changes** ในการทำธุรกรรม `Style` เดียวเพื่อหลีกเลี่ยงการรีเฟรช DOM หลายครั้ง. +- **Leverage Aspose.Html’s rendering engine** เพื่อส่งออกเอกสารสุดท้ายเป็น PDF หรือรูปภาพ—เหมาะสำหรับเครื่องมือรายงาน. + +## การยืนยันด้วยภาพ (ตัวเลือก) + +หากคุณต้องการดูผลลัพธ์ในเบราว์เซอร์ คุณสามารถบันทึกสตริงที่เรนเดอร์เป็นไฟล์ `.html` ได้: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +เปิด `output.html` แล้วคุณจะเห็น **Hello world** แสดงเป็นตัวหนา + เอียง. + +![ตัวอย่างการสร้างเอกสาร HTML ด้วย C# แสดงย่อหน้าตัวหนาและเอียง](/images/create-html-document-csharp.png "สร้างเอกสาร HTML ด้วย C# – ผลลัพธ์ที่เรนเดอร์") + +*ข้อความแทน: สร้างเอกสาร HTML ด้วย C# – ผลลัพธ์ที่เรนเดอร์พร้อมข้อความตัวหนาและเอียง.* + +## สรุป + +เราเพิ่ง **สร้างเอกสาร HTML ด้วย C#**, **ดึงองค์ประกอบโดย id**, **ค้นหาองค์ประกอบโดย id**, **เปลี่ยนสไตล์ขององค์ประกอบ HTML**, และสุดท้าย **เพิ่มตัวหนาและเอียง**—ทั้งหมดด้วยไม่กี่บรรทัดโดยใช้ Aspose.Html วิธีนี้ง่ายต่อการทำงานในสภาพแวดล้อม .NET ใด ๆ และสามารถขยายไปสู่การจัดการ DOM ขนาดใหญ่ได้. + +พร้อมสำหรับขั้นตอนต่อไปหรือยัง? ลองเปลี่ยน `WebFontStyle` เป็น enum อื่น ๆ เช่น `Underline` หรือรวมหลายสไตล์ด้วยตนเอง หรือทดลองโหลดไฟล์ HTML ภายนอกและใช้เทคนิคเดียวกันกับหลายร้อยองค์ประกอบ ไม่จำกัดอะไรเลยและตอนนี้คุณมีพื้นฐานที่มั่นคงสำหรับการต่อยอด. + +ขอให้สนุกกับการเขียนโค้ด! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/thai/net/html-extensions-and-conversions/_index.md b/html/thai/net/html-extensions-and-conversions/_index.md index 2474ca32c..f09bf2e29 100644 --- a/html/thai/net/html-extensions-and-conversions/_index.md +++ b/html/thai/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML สำหรับ .NET ไม่ใช่แค่ไลบรา ## บทช่วยสอนเกี่ยวกับส่วนขยายและการแปลง HTML ### [แปลง HTML เป็น PDF ใน .NET ด้วย Aspose.HTML](./convert-html-to-pdf/) แปลง HTML เป็น PDF ได้อย่างง่ายดายด้วย Aspose.HTML สำหรับ .NET ปฏิบัติตามคำแนะนำทีละขั้นตอนของเราและปลดปล่อยพลังแห่งการแปลง HTML เป็น PDF +### [สร้าง PDF จาก HTML ด้วย Aspose – คู่มือ C# ทีละขั้นตอน](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +เรียนรู้วิธีสร้างไฟล์ PDF จาก HTML ด้วย Aspose.HTML ใน C# ตามขั้นตอนละเอียดของเรา ### [แปลง EPUB เป็นรูปภาพใน .NET ด้วย Aspose.HTML](./convert-epub-to-image/) เรียนรู้วิธีการแปลง EPUB เป็นรูปภาพโดยใช้ Aspose.HTML สำหรับ .NET บทช่วยสอนแบบทีละขั้นตอนพร้อมตัวอย่างโค้ดและตัวเลือกที่ปรับแต่งได้ ### [แปลง EPUB เป็น PDF ใน .NET ด้วย Aspose.HTML](./convert-epub-to-pdf/) @@ -59,20 +61,22 @@ Aspose.HTML สำหรับ .NET ไม่ใช่แค่ไลบรา แปลง HTML เป็น MHTML ใน .NET ด้วย Aspose.HTML - คำแนะนำทีละขั้นตอนสำหรับการเก็บถาวรเนื้อหาเว็บอย่างมีประสิทธิภาพ เรียนรู้วิธีใช้ Aspose.HTML สำหรับ .NET เพื่อสร้างไฟล์เก็บถาวร MHTML ### [แปลง HTML เป็น PNG ใน .NET ด้วย Aspose.HTML](./convert-html-to-png/) ค้นพบวิธีใช้ Aspose.HTML สำหรับ .NET เพื่อจัดการและแปลงเอกสาร HTML คำแนะนำทีละขั้นตอนสำหรับการพัฒนา .NET ที่มีประสิทธิภาพ +### [แปลง HTML เป็นรูปภาพใน C# – คู่มือเต็ม](./convert-html-to-image-in-c-complete-guide/) +เรียนรู้วิธีแปลง HTML เป็นรูปภาพใน C# อย่างละเอียดด้วย Aspose.HTML คู่มือขั้นตอนเต็มสำหรับนักพัฒนา ### [แปลง HTML เป็น TIFF ใน .NET ด้วย Aspose.HTML](./convert-html-to-tiff/) เรียนรู้วิธีแปลง HTML เป็น TIFF ด้วย Aspose.HTML สำหรับ .NET ปฏิบัติตามคำแนะนำทีละขั้นตอนของเราเพื่อเพิ่มประสิทธิภาพเนื้อหาเว็บอย่างมีประสิทธิภาพ ### [แปลง HTML เป็น XPS ใน .NET ด้วย Aspose.HTML](./convert-html-to-xps/) ค้นพบพลังของ Aspose.HTML สำหรับ .NET: แปลง HTML เป็น XPS ได้อย่างง่ายดาย มีข้อกำหนดเบื้องต้น คำแนะนำทีละขั้นตอน และคำถามที่พบบ่อยรวมอยู่ด้วย ### [วิธีบีบอัด HTML เป็น Zip ใน C# – บันทึก HTML เป็น Zip](./how-to-zip-html-in-c-save-html-to-zip/) เรียนรู้วิธีบีบอัดไฟล์ HTML เป็นไฟล์ Zip ด้วย C# และ Aspose.HTML สำหรับ .NET อย่างง่ายดายและปลอดภัย -### [สร้างเอกสาร HTML พร้อมข้อความที่มีสไตล์และส่งออกเป็น PDF – คู่มือเต็ม](./create-html-document-with-styled-text-and-export-to-pdf-full/) -เรียนรู้วิธีสร้างเอกสาร HTML ที่มีข้อความจัดรูปแบบและแปลงเป็น PDF อย่างละเอียดด้วย Aspose.HTML สำหรับ .NET -### [สร้าง PDF จาก HTML – คำแนะนำขั้นตอนโดยขั้นตอน C#](./create-pdf-from-html-c-step-by-step-guide/) -เรียนรู้วิธีสร้าง PDF จากไฟล์ HTML ด้วย C# โดยใช้ Aspose.HTML สำหรับ .NET ตามขั้นตอนที่ชัดเจน ### [บันทึก HTML เป็น ZIP – คอร์สเต็ม C#](./save-html-as-zip-complete-c-tutorial/) บันทึกไฟล์ HTML เป็น ZIP อย่างครบถ้วนด้วย C# ตามขั้นตอนของเรา ### [บันทึก HTML เป็น ZIP ใน C# – ตัวอย่างทำงานในหน่วยความจำเต็มรูปแบบ](./save-html-to-zip-in-c-complete-in-memory-example/) บันทึกไฟล์ HTML เป็นไฟล์ ZIP โดยใช้ C# ด้วยตัวอย่างทำงานในหน่วยความจำเต็มรูปแบบ +### [บันทึก HTML เป็น ZIP ใน C# – คู่มือเต็มพร้อมที่จัดเก็บแบบกำหนดเอง](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +บันทึก HTML เป็นไฟล์ ZIP ด้วย C# พร้อมการจัดเก็บแบบกำหนดเองอย่างละเอียด +### [วิธีบีบอัด HTML เป็น Zip ด้วย Aspose.HTML – คู่มือเต็ม](./how-to-zip-html-with-aspose-html-complete-guide/) +เรียนรู้วิธีบีบอัดไฟล์ HTML เป็น Zip อย่างละเอียดด้วย Aspose.HTML สำหรับ .NET พร้อมขั้นตอนและตัวอย่างโค้ดครบถ้วน ## บทสรุป diff --git a/html/thai/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/thai/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..51ec423c2 --- /dev/null +++ b/html/thai/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,187 @@ +--- +category: general +date: 2026-03-21 +description: แปลง HTML เป็นภาพด้วย Aspose.HTML ใน C# เรียนรู้วิธีบันทึก HTML เป็น + PNG ตั้งค่าการเรนเดอร์ขนาดภาพ และเขียนภาพลงไฟล์ในไม่กี่ขั้นตอน. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: th +og_description: แปลง HTML เป็นภาพอย่างรวดเร็ว คู่มือนี้แสดงวิธีบันทึก HTML เป็น PNG + ตั้งค่าการเรนเดอร์ขนาดภาพ และเขียนภาพลงไฟล์ด้วย Aspose.HTML. +og_title: แปลง HTML เป็นภาพใน C# – คู่มือขั้นตอนโดยละเอียด +tags: +- Aspose.HTML +- C# +- Image Rendering +title: แปลง HTML เป็นภาพใน C# – คู่มือฉบับสมบูรณ์ +url: /th/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# แปลง HTML เป็นรูปภาพใน C# – คู่มือฉบับสมบูรณ์ + +เคยต้องการ **convert HTML to image** สำหรับภาพย่อของแดชบอร์ด, ตัวอย่างอีเมล, หรือรายงาน PDF หรือไม่? นี่เป็นสถานการณ์ที่เกิดขึ้นบ่อยกว่าที่คุณคาดคิด, โดยเฉพาะเมื่อคุณต้องจัดการกับเนื้อหาเว็บแบบไดนามิกที่ต้องฝังไว้ที่อื่น. + +ข่าวดี? ด้วย Aspose.HTML คุณสามารถ **convert HTML to image** ได้ในไม่กี่บรรทัด, และคุณจะได้เรียนรู้วิธี *save HTML as PNG*, ควบคุมขนาดผลลัพธ์, และ *write image to file* โดยไม่ต้องเหนื่อย. + +ในบทแนะนำนี้เราจะพาคุณผ่านทุกอย่างที่คุณต้องรู้: ตั้งแต่การโหลดหน้าเว็บระยะไกลจนถึงการปรับขนาดการเรนเดอร์, และสุดท้ายการบันทึกผลลัพธ์เป็นไฟล์ PNG บนดิสก์. ไม่ต้องใช้เครื่องมือภายนอก, ไม่ต้องใช้เทคนิคบรรทัดคำสั่งที่ซับซ้อน—เพียงโค้ด C# แท้ที่คุณสามารถใส่ลงในโปรเจกต์ .NET ใดก็ได้. + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธี **render webpage to PNG** ด้วยคลาส `HTMLDocument` ของ Aspose.HTML. +- ขั้นตอนที่แน่นอนเพื่อ **set image size rendering** เพื่อให้ผลลัพธ์ตรงกับข้อกำหนดการจัดวางของคุณ. +- วิธีการ **write image to file** อย่างปลอดภัย, จัดการสตรีมและเส้นทางไฟล์. +- เคล็ดลับการแก้ปัญหาข้อผิดพลาดทั่วไป เช่น ฟอนต์หายหรือการหมดเวลาเครือข่าย. + +### ข้อกำหนดเบื้องต้น + +- .NET 6.0 หรือใหม่กว่า (API ทำงานกับ .NET Framework ด้วย, แต่แนะนำให้ใช้ .NET 6+). +- การอ้างอิงไปยังแพคเกจ NuGet Aspose.HTML for .NET (`Aspose.Html`). +- ความคุ้นเคยพื้นฐานกับ C# และ async/await (ไม่จำเป็นแต่เป็นประโยชน์). + +หากคุณมีทั้งหมดนี้แล้ว, คุณพร้อมที่จะเริ่มแปลง HTML เป็นรูปภาพได้ทันที. + +## ขั้นตอนที่ 1: โหลดหน้าเว็บ – พื้นฐานของการแปลง HTML เป็นรูปภาพ + +ก่อนที่การเรนเดอร์ใด ๆ จะเกิดขึ้น, คุณต้องมีอินสแตนซ์ `HTMLDocument` ที่แสดงถึงหน้าที่คุณต้องการจับภาพ. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*ทำไมเรื่องนี้สำคัญ:* `HTMLDocument` จะทำการพาร์ส HTML, แก้ไข CSS, และสร้าง DOM. หากเอกสารไม่สามารถโหลดได้ (เช่น ปัญหาเครือข่าย), การเรนเดอร์ต่อมาจะสร้างภาพเปล่า. ตรวจสอบเสมอว่า URL สามารถเข้าถึงได้ก่อนดำเนินการต่อ. + +## ขั้นตอนที่ 2: ตั้งค่าการเรนเดอร์ขนาดภาพ – ควบคุมความกว้าง, ความสูง, และคุณภาพ + +Aspose.HTML ให้คุณปรับขนาดผลลัพธ์อย่างละเอียดด้วย `ImageRenderingOptions`. ที่นี่คุณจะ **set image size rendering** ให้ตรงกับการจัดวางเป้าหมายของคุณ. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*เคล็ดลับ:* หากคุณละเว้น `Width` และ `Height`, Aspose.HTML จะใช้ขนาดโดยธรรมชาติของหน้า, ซึ่งอาจไม่คาดเดาได้สำหรับการออกแบบที่ตอบสนอง. การระบุขนาดอย่างชัดเจนจะทำให้ผลลัพธ์ **save HTML as PNG** ของคุณดูตรงตามที่คาดหวัง. + +## ขั้นตอนที่ 3: เขียนภาพลงไฟล์ – บันทึก PNG ที่เรนเดอร์แล้ว + +เมื่อเอกสารถูกเตรียมพร้อมและตั้งค่าตัวเลือกการเรนเดอร์แล้ว, คุณสามารถ **write image to file** ได้ในที่สุด. การใช้ `FileStream` จะรับประกันว่าไฟล์ถูกสร้างอย่างปลอดภัย, แม้ว่าตำแหน่งโฟลเดอร์ยังไม่มีอยู่. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +หลังจากบล็อกนี้ทำงาน, คุณจะพบ `page.png` ที่ตำแหน่งที่คุณระบุ. คุณเพิ่ง **rendered webpage to PNG** และเขียนลงดิสก์ในขั้นตอนเดียวที่ง่ายดาย. + +### ผลลัพธ์ที่คาดหวัง + +เปิด `C:\Temp\page.png` ด้วยโปรแกรมดูรูปใดก็ได้. คุณควรเห็นภาพสแนปช็อตที่ตรงกับ `https://example.com`, เรนเดอร์ที่ 1024 × 768 พิกเซลพร้อมขอบเรียบเนียนด้วย antialiasing. หากหน้ามีเนื้อหาไดนามิก (เช่น อิลิเมนต์ที่สร้างโดย JavaScript), จะถูกจับภาพตราบใดที่ DOM โหลดเต็มก่อนการเรนเดอร์. + +## ขั้นตอนที่ 4: จัดการกรณีขอบ – ฟอนต์, การยืนยันตัวตน, และหน้าขนาดใหญ่ + +แม้กระบวนการพื้นฐานจะทำงานกับเว็บไซต์สาธารณะส่วนใหญ่, แต่สถานการณ์จริงมักมีความท้าทาย: + +| Situation | What to Do | +|-----------|------------| +| **ฟอนต์ที่กำหนดเองไม่โหลด** | Embed the font files locally and set `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **หน้าที่ต้องการการยืนยันตัวตน** | Use `HTMLDocument` overload that accepts `HttpWebRequest` with cookies or tokens. | +| **หน้าที่สูงมาก** | Increase `Height` or enable `PageScaling` in `ImageRenderingOptions` to avoid truncation. | +| **การใช้หน่วยความจำพุ่งสูง** | Render in chunks using `RenderToImage` overload that accepts a `Rectangle` region. | + +การจัดการรายละเอียด *write image to file* เหล่านี้จะทำให้ pipeline `convert html to image` ของคุณคงความเสถียรในสภาพการผลิต. + +## ขั้นตอนที่ 5: ตัวอย่างทำงานเต็มรูปแบบ – พร้อมคัดลอก‑วาง + +ด้านล่างเป็นโปรแกรมทั้งหมด, พร้อมคอมไพล์. มีขั้นตอนทั้งหมด, การจัดการข้อผิดพลาด, และคอมเมนต์ที่คุณต้องการ. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +รันโปรแกรมนี้, แล้วคุณจะเห็นข้อความยืนยันในคอนโซล. ไฟล์ PNG จะเป็นสิ่งที่คุณคาดหวังเมื่อคุณ **render webpage to PNG** ด้วยตนเองในเบราว์เซอร์และถ่ายสกรีนช็อต—แต่เร็วกว่าและอัตโนมัติเต็มรูปแบบ. + +## คำถามที่พบบ่อย + +**Q: ฉันสามารถแปลงไฟล์ HTML ในเครื่องแทน URL ได้หรือไม่?** +ได้เลย. เพียงเปลี่ยน URL เป็นเส้นทางไฟล์: `new HTMLDocument(@"C:\myPage.html")`. + +**Q: ฉันต้องการไลเซนส์สำหรับ Aspose.HTML หรือไม่?** +ไลเซนส์ประเมินผลฟรีทำงานได้สำหรับการพัฒนาและทดสอบ. สำหรับการใช้งานจริง, ควรซื้อไลเซนส์เพื่อเอา watermark การประเมินออก. + +**Q: ถ้าหน้าใช้ JavaScript โหลดเนื้อหาหลังจากการโหลดครั้งแรกจะทำอย่างไร?** +Aspose.HTML จะดำเนินการ JavaScript แบบ synchronous ระหว่างการพาร์ส, แต่สคริปต์ที่ทำงานนานอาจต้องการการหน่วงเวลาแบบแมนนวล. คุณสามารถใช้ `HTMLDocument.WaitForReadyState` ก่อนการเรนเดอร์. + +## สรุป + +คุณมีโซลูชันครบวงจรเพื่อ **convert HTML to image** ใน C# แล้ว. ด้วยการทำตามขั้นตอนข้างต้นคุณสามารถ **save HTML as PNG**, ตั้งค่า **set image size rendering** อย่างแม่นยำ, และมั่นใจ **write image to file** บนสภาพแวดล้อม Windows หรือ Linux ใดก็ได้. + +ตั้งแต่การจับภาพหน้าจอแบบง่ายจนถึงการสร้างรายงานอัตโนมัติ, เทคนิคนี้สามารถขยายได้ดี. ต่อไปลองทดลองรูปแบบเอาต์พุตอื่น ๆ เช่น JPEG หรือ BMP, หรือผสานโค้ดเข้ากับ ASP.NET Core API ที่ส่งคืน PNG โดยตรงให้ผู้เรียก. ความเป็นไปได้แทบไม่มีที่สิ้นสุด. + +ขอให้เขียนโค้ดอย่างสนุกสนาน, และขอให้ภาพที่เรนเดอร์ของคุณดูพิกเซล‑เพอร์เฟ็กต์เสมอ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/thai/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/thai/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..2caa4e563 --- /dev/null +++ b/html/thai/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-03-21 +description: สร้าง PDF จาก HTML อย่างรวดเร็วด้วย Aspose HTML. เรียนรู้การเรนเดอร์ + HTML เป็น PDF, การแปลง HTML เป็น PDF, และวิธีใช้ Aspose ในบทแนะนำสั้น ๆ. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: th +og_description: สร้าง PDF จาก HTML ด้วย Aspose ใน C# คู่มือนี้แสดงวิธีเรนเดอร์ HTML + เป็น PDF, แปลง HTML เป็น PDF, และวิธีใช้ Aspose อย่างมีประสิทธิภาพ +og_title: สร้าง PDF จาก HTML – บทเรียน Aspose C# อย่างครบถ้วน +tags: +- Aspose +- C# +- PDF generation +title: สร้าง PDF จาก HTML ด้วย Aspose – คู่มือ C# ทีละขั้นตอน +url: /th/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้าง PDF จาก HTML ด้วย Aspose – คู่มือขั้นตอน C# + +เคยต้องการ **สร้าง PDF จาก HTML** แต่ไม่แน่ใจว่าห้องสมุดใดจะให้ผลลัพธ์ที่พิกเซล‑เพอร์เฟค? คุณไม่ได้เป็นคนเดียว นักพัฒนาหลายคนเจอปัญหาเมื่อต้องแปลงส่วนของเว็บให้เป็นเอกสารที่พิมพ์ได้ แล้วเจอข้อความเบลอหรือเค้าโครงที่เสียหาย + +ข่าวดีคือ Aspose HTML ทำให้กระบวนการทั้งหมดเป็นเรื่องง่าย ในบทแนะนำนี้เราจะพาคุณผ่านโค้ดที่จำเป็นเพื่อ **render HTML to PDF** ตรวจสอบว่าการตั้งค่าแต่ละอย่างสำคัญอย่างไร และแสดงวิธี **convert HTML to PDF** โดยไม่มีเทคนิคลับใด ๆ เมื่อจบคุณจะรู้ **how to use Aspose** เพื่อสร้าง PDF ที่เชื่อถือได้ในโครงการ .NET ใด ๆ + +## Prerequisites – What You’ll Need Before You Start + +- **.NET 6.0 หรือใหม่กว่า** (ตัวอย่างทำงานบน .NET Framework 4.7+ ด้วย) +- **Visual Studio 2022** หรือ IDE ใด ๆ ที่รองรับ C# +- **Aspose.HTML for .NET** NuGet package (รุ่นทดลองหรือเวอร์ชันที่มีลิขสิทธิ์) +- ความเข้าใจพื้นฐานของไวยากรณ์ C# (ไม่ต้องมีความรู้เชิงลึกเกี่ยวกับ PDF) + +ถ้าคุณมีทั้งหมดนี้ คุณพร้อมเริ่มแล้ว หากยังไม่มี ให้ดาวน์โหลด .NET SDK ล่าสุดและติดตั้ง NuGet package ด้วย: + +```bash +dotnet add package Aspose.HTML +``` + +บรรทัดเดียวนี้จะดึงทุกอย่างที่คุณต้องการสำหรับการ **aspose html to pdf** conversion + +--- + +## Step 1: Set Up Your Project to Create PDF from HTML + +สิ่งแรกที่ทำคือสร้างแอปคอนโซลใหม่ (หรือผสานโค้ดนี้เข้าในเซอร์วิสที่มีอยู่) ตัวอย่างโครงสร้าง `Program.cs` ขั้นพื้นฐาน: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro tip:** หากคุณเห็น `Aspise.Html.Rendering.Text` ในตัวอย่างเก่า ให้เปลี่ยนเป็น `Aspose.Html.Rendering.Text` การพิมพ์ผิดนี้จะทำให้เกิดข้อผิดพลาดในการคอมไพล์ + +การใช้ namespace ที่ถูกต้องทำให้คอมไพเลอร์ค้นหา **TextOptions** class ที่เราจะใช้ต่อไปได้ + +## Step 2: Build the HTML Document (Render HTML to PDF) + +ต่อไปเราจะสร้าง HTML ต้นฉบับ Aspose ให้คุณส่งสตริงดิบ, เส้นทางไฟล์ หรือแม้แต่ URL สำหรับการสาธิตนี้เราจะใช้สตริงง่าย ๆ: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +ทำไมต้องส่งสตริง? เพราะช่วยหลีกเลี่ยง I/O ของไฟล์, เร็วขึ้นในการแปลง, และรับประกันว่า HTML ที่คุณเห็นในโค้ดคือสิ่งที่ถูกเรนเดอร์จริง ๆ หากคุณต้องการโหลดจากไฟล์ เพียงเปลี่ยนอาร์กิวเมนต์ของคอนสตรัคเตอร์เป็น URI ของไฟล์ + +## Step 3: Fine‑Tune Text Rendering (Convert HTML to PDF with Better Quality) + +การเรนเดอร์ข้อความมักเป็นปัจจัยที่กำหนดว่า PDF ของคุณดูคมชัดหรือเบลอ Aspose มีคลาส `TextOptions` ที่ให้คุณเปิดใช้งาน sub‑pixel hinting — จำเป็นสำหรับผลลัพธ์ DPI สูง: + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +การเปิด `UseHinting` มีประโยชน์เป็นพิเศษเมื่อ HTML ต้นฉบับของคุณมีฟอนต์กำหนดเองหรือขนาดฟอนต์เล็ก หากไม่เปิดใช้งาน คุณอาจเห็นขอบหยักใน PDF สุดท้าย + +## Step 4: Attach Text Options to PDF Rendering Configuration (How to Use Aspose) + +ต่อไปเราจะผูกตัวเลือกข้อความเหล่านั้นเข้ากับการตั้งค่า PDF renderer นี่คือจุดที่ **aspose html to pdf** ส่องแสง — ตั้งค่าขนาดหน้า, การบีบอัด ฯลฯ สามารถปรับได้: + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +คุณสามารถละ `PageSetup` ได้หากพอใจกับขนาด A4 เริ่มต้น สิ่งสำคัญคืออ็อบเจ็กต์ `TextOptions` อยู่ภายใน `PdfRenderingOptions` และนี่คือวิธีบอก Aspose *ว่าจะ* เรนเดอร์ข้อความอย่างไร + +## Step 5: Render the HTML and Save the PDF (Convert HTML to PDF) + +สุดท้าย เราจะสตรีมผลลัพธ์ไปยังไฟล์ การใช้บล็อก `using` รับประกันว่าการจัดการไฟล์จะปิดอย่างถูกต้อง แม้จะเกิดข้อยกเว้น: + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +เมื่อรันโปรแกรม คุณจะพบ `output.pdf` อยู่ข้างไฟล์ executable เปิดไฟล์นั้นขึ้นมา คุณควรเห็นหัวเรื่องและย่อหน้าที่สะอาดตามที่กำหนดในสตริง HTML + +### Expected Output + +![create pdf from html example output](https://example.com/images/pdf-output.png "create pdf from html example output") + +*ภาพหน้าจอแสดง PDF ที่สร้างขึ้นโดยมีหัวเรื่อง “Hello, Aspose!” เรนเดอร์คมชัดด้วย text hinting* + +--- + +## Common Questions & Edge Cases + +### 1. What if my HTML references external resources (images, CSS)? + +Aspose แก้ไข URL แบบ relative ตาม base URI ของเอกสาร หากคุณส่งสตริงดิบ ให้ตั้งค่า base URI ด้วยตนเอง: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +ตอนนี้ `` จะถูกค้นหาโดยอ้างอิงจาก `C:/MyProject/` + +### 2. How do I embed fonts that aren’t installed on the server? + +เพิ่มบล็อก ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### ขั้นตอนที่ 4: กำหนดค่า Save Options ให้ใช้การจัดเก็บแบบกำหนดเอง + +`HtmlSaveOptions` ให้เราบอก Aspose ให้บรรจุทุกอย่างลงในไฟล์ ZIP คุณสมบัติ `OutputStorage` (legacy) จะรับอินสแตนซ์ `MyStorage` ของเรา + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **หมายเหตุ:** ใน Aspose HTML 23.9+ คุณสมบัตินี้ชื่อ `OutputStorage` แต่ถูกทำให้ obsolete. ตัวเลือกสมัยใหม่คือ `ZipOutputStorage`. โค้ดด้านล่างทำงานได้กับทั้งสองเพราะอินเทอร์เฟซเดียวกัน + +### ขั้นตอนที่ 5: บันทึกเอกสารเป็นไฟล์ ZIP + +เลือกโฟลเดอร์เป้าหมาย (หรือสตรีม) แล้วให้ Aspose ทำงานหนักให้คุณ + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +เมื่อโปรแกรมทำงานเสร็จ คุณจะพบไฟล์ `output.zip` ที่มี: + +* `index.html` – เอกสารหลัก +* รูปภาพ, ไฟล์ CSS, หรือสคริปต์ที่ฝังอยู่ (หาก HTML ของคุณอ้างอิงถึง) + +คุณสามารถเปิด ZIP ด้วยโปรแกรมจัดการไฟล์ใดก็ได้เพื่อยืนยันโครงสร้าง + +--- + +## ตรวจสอบผลลัพธ์ (ไม่บังคับ) + +หากต้องการตรวจสอบ archive อย่างโปรแกรมโดยไม่ต้องแตกไฟล์ลงดิสก์: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +ผลลัพธ์ทั่วไป: + +``` +- index.html (452 bytes) +``` + +หากมีรูปภาพหรือ CSS จะปรากฏเป็นรายการเพิ่มเติม การตรวจสอบสั้น ๆ นี้ยืนยันว่า **create html zip archive** ทำงานตามที่คาดหวัง + +--- + +## คำถามที่พบบ่อย & กรณีขอบ + +| Question | Answer | +|----------|--------| +| **What if I need to write the ZIP directly to a response stream?** | Return the `MemoryStream` you get from `MyStorage` after `document.Save`. Cast it to a `byte[]` and write it to `HttpResponse.Body`. | +| **My HTML references external URLs—will they be downloaded?** | No. Aspose only packs resources that are *embedded* (e.g., `` or local files). For remote assets you must download them first and adjust the markup. | +| **The `OutputStorage` property is marked obsolete—should I ignore it?** | It still works, but the newer `ZipOutputStorage` offers the same API with a different name. Replace `OutputStorage` with `ZipOutputStorage` if you want a warning‑free build. | +| **Can I encrypt the ZIP?** | Yes. After saving, open the file with `System.IO.Compression.ZipArchive` and set a password using third‑party libraries like `SharpZipLib`. Aspose itself doesn’t provide encryption. | + +--- + +## ตัวอย่างทำงานเต็มรูปแบบ (คัดลอก‑วาง) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +รันโปรแกรม, เปิด `output.zip`, คุณจะเห็นไฟล์ `index.html` เพียงไฟล์เดียวที่แสดงหัวข้อ “Hello from ZIP!” เมื่อเปิดในเบราว์เซอร์ + +--- + +## สรุป + +คุณได้เรียนรู้ **วิธีบันทึก HTML เป็น ZIP** ใน C# ด้วย **คลาสจัดเก็บแบบกำหนดเอง**, วิธี **ส่งออก HTML ไปเป็น ZIP**, และวิธี **สร้าง HTML zip archive** ที่พร้อมสำหรับการแจกจ่าย แพทเทิร์นนี้ยืดหยุ่น—เปลี่ยน `MemoryStream` เป็นสตรีมคลาวด์, เพิ่มการเข้ารหัส, หรือรวมเข้าไปใน Web API ที่ส่ง ZIP ตามคำขอ + +พร้อมก้าวต่อไปหรือยัง? ลองใส่หน้าเว็บเต็มรูปแบบที่มีรูปภาพและสไตล์, หรือเชื่อมต่อ storage เข้ากับ Azure Blob Storage เพื่อข้ามระบบไฟล์ท้องถิ่นเลยก็ได้ ความเป็นไปได้ไม่มีที่สิ้นสุดเมื่อคุณผสานความสามารถ ZIP ของ Aspose.HTML กับตรรกะการจัดเก็บของคุณเอง + +Happy coding, and may your archives always be tidy! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/turkish/net/generate-jpg-and-png-images/_index.md b/html/turkish/net/generate-jpg-and-png-images/_index.md index a918363c4..3dd96dd5b 100644 --- a/html/turkish/net/generate-jpg-and-png-images/_index.md +++ b/html/turkish/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ HTML belgelerini düzenlemek, HTML'yi resimlere dönüştürmek ve daha fazlası DOCX belgelerini PNG veya JPG formatına dönüştürürken antialiasing'i etkinleştirerek daha net ve pürüzsüz görüntüler elde edin. ### [docx'i png'ye dönüştür – zip arşivi oluşturma C# eğitimi](./convert-docx-to-png-create-zip-archive-c-tutorial/) C# kullanarak docx dosyalarını png formatına dönüştürüp, sonuçları zip arşivi içinde paketlemeyi öğrenin. +### [HTML'yi PNG'ye Dönüştür – ZIP Dışa Aktarımlı Tam C# Kılavuzu](./convert-html-to-png-full-c-guide-with-zip-export/) +HTML dosyalarını PNG formatına dönüştürüp, sonuçları ZIP arşivi olarak dışa aktarmayı adım adım gösteren kapsamlı C# rehberi. ## Çözüm diff --git a/html/turkish/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/turkish/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..61fc3517b --- /dev/null +++ b/html/turkish/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: HTML'yi PNG'ye dönüştürün ve HTML'yi resim olarak render edin, aynı zamanda + HTML'yi ZIP'e kaydedin. Font stilini HTML'ye uygulamayı ve p öğelerine kalın (bold) + eklemeyi sadece birkaç adımda öğrenin. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: tr +og_description: HTML'yi hızlıca PNG'ye dönüştürün. Bu kılavuz, HTML'yi resim olarak + nasıl render edeceğinizi, HTML'yi ZIP'e nasıl kaydedeceğinizi, HTML'ye yazı tipi + stili nasıl uygulayacağınızı ve p öğelerine kalın (bold) nasıl ekleyeceğinizi gösterir. +og_title: HTML'yi PNG'ye Dönüştür – Tam C# Öğreticisi +tags: +- Aspose +- C# +title: HTML'yi PNG'ye Dönüştür – ZIP Dışa Aktarımlı Tam C# Rehberi +url: /tr/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML'yi PNG'ye Dönüştür – ZIP Dışa Aktarımlı Tam C# Kılavuzu + +Hiç **HTML'yi PNG'ye dönüştürmek** istediğinizde, başsız bir tarayıcı kullanmadan bunu yapabilecek bir kütüphane bulamadınız mı? Yalnız değilsiniz. Birçok projede—e‑posta küçük resimleri, dokümantasyon ön izlemeleri veya hızlı‑bakış görselleri—bir web sayfasını statik bir resme dönüştürmek gerçek bir ihtiyaçtır. + +İyi haber? Aspose.HTML ile **HTML'yi resim olarak render** edebilir, işaretlemede anlık değişiklikler yapabilir ve hatta **HTML'yi ZIP olarak kaydedebilir** ve sonradan dağıtabilirsiniz. Bu öğreticide, **p** öğelerine **kalın (bold) ekleme** gibi bir **font style HTML** uygulamasını içeren tam, çalıştırılabilir bir örnek üzerinden geçeceğiz ve sonunda bir PNG dosyası üreteceğiz. Sonunda, bir sayfayı yüklemekten kaynakları arşivlemeye kadar her şeyi yapan tek bir C# sınıfına sahip olacaksınız. + +## Gereksinimler + +- .NET 6.0 veya üzeri (API .NET Core üzerinde de çalışır) +- Aspose.HTML for .NET 6+ (NuGet paketi `Aspose.Html`) +- C# sözdizimi hakkında temel bilgi (ileri seviye kavramlar gerekmez) + +Hepsi bu. Harici tarayıcılar, phantomjs yok, sadece saf yönetilen kod. + +## Adım 1 – HTML Belgesini Yükle + +İlk olarak kaynak dosyayı (veya URL'yi) bir `HTMLDocument` nesnesine getiriyoruz. Bu adım, **render html as image** ve **save html to zip** işlemlerinin temelini oluşturur. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Neden önemli:* `HTMLDocument` sınıfı işaretlemi ayrıştırır, bir DOM oluşturur ve bağlı kaynakları (CSS, görseller, fontlar) çözer. Uygun bir belge nesnesi olmadan stilleri değiştiremez veya bir şey render edemezsiniz. + +## Adım 2 – Font Style HTML Uygula (p'ye Bold Ekle) + +Şimdi her `

` öğesini dolaşarak `font-weight` değerini **bold** yapacağız. Bu, **add bold to p** etiketlerini orijinal dosyaya dokunmadan programatik olarak eklemenin yolu. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*İpucu:* Sadece bir alt küme için kalınlaştırma gerekiyorsa, seçiciyi daha spesifik bir şeyle değiştirin, örneğin `"p.intro"`. + +## Adım 3 – HTML'yi Resim Olarak Render Et (HTML'yi PNG'ye Dönüştür) + +DOM hazır olduğunda, `ImageRenderingOptions` ayarlarını yapıp `RenderToImage` metodunu çağırıyoruz. İşte **convert html to png** sihrinin gerçekleştiği yer. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Seçeneklerin önemi:* Sabit bir genişlik/yükseklik ayarlamak çıktının çok büyük olmasını engeller, antialiasing ise daha pürüzsüz bir görsel sağlar. Daha küçük dosya boyutu isterseniz `options`ı `ImageFormat.Jpeg` olarak da değiştirebilirsiniz. + +## Adım 4 – HTML'yi ZIP Olarak Kaydet (Kaynakları Paketle) + +Genellikle orijinal HTML'i CSS, görseller ve fontlarla birlikte dağıtmanız gerekir. Aspose.HTML’in `ZipArchiveSaveOptions` tam da bunu yapar. Ayrıca tüm dış varlıkların arşivle aynı klasöre yazılmasını sağlayan özel bir `ResourceHandler` ekliyoruz. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Köşe durumu:* HTML'niz kimlik doğrulama gerektiren uzak görseller referans veriyorsa, varsayılan işleyici başarısız olur. Bu durumda `MyResourceHandler`ı genişleterek HTTP başlıkları ekleyebilirsiniz. + +## Adım 5 – Her Şeyi Tek Bir Dönüştürücü Sınıfında Birleştir + +Aşağıda, önceki adımları bir araya getiren tam, çalıştırılabilir sınıf yer alıyor. Konsol uygulamasına kopyalayıp `Convert` metodunu çağırarak dosyaların oluştuğunu izleyebilirsiniz. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Beklenen Çıktı + +Yukarıdaki kodu çalıştırdıktan sonra `outputDirectory` içinde iki dosya bulacaksınız: + +| Dosya | Açıklama | +|------|----------| +| `page.png` | Kaynak HTML'nin 1200 × 800 boyutlarında **bold** olarak gösterilen bir PNG render'ı. | +| `archive.zip` | Orijinal `input.html`, CSS, görseller ve web‑fontları içeren bir ZIP paketi – çevrim dışı dağıtım için mükemmel. | + +`page.png` dosyasını herhangi bir görüntü görüntüleyicide açıp kalın stilin uygulandığını doğrulayabilir, `archive.zip`i çıkararak dokunulmamış HTML'yi varlıklarıyla birlikte görebilirsiniz. + +## Yaygın Sorular & Dikkat Edilmesi Gerekenler + +- **HTML içinde JavaScript varsa ne olur?** + Aspose.HTML render sırasında **script çalıştırmaz**, bu yüzden dinamik içerik görünmez. Tamamen render edilmiş sayfalar için başsız bir tarayıcı gerekir, ancak statik şablonlar için bu yöntem daha hızlı ve hafiftir. + +- **Çıktı formatını JPEG veya BMP yapabilir miyim?** + Evet—`ImageRenderingOptions` içindeki `ImageFormat` özelliğini değiştirin, örneğin `options.ImageFormat = ImageFormat.Jpeg;`. + +- **`HTMLDocument` nesnesini manuel olarak dispose etmem gerekiyor mu?** + Sınıf `IDisposable` uygular. Uzun süren bir hizmette `using` bloğu içinde kullanın veya işiniz bittiğinde `document.Dispose()` çağırın. + +- **Özel `MyResourceHandler` nasıl çalışıyor?** + Her dış kaynağı (CSS, görseller, fontlar) alır ve belirttiğiniz klasöre yazar. Böylece ZIP, HTML'nin referans verdiği her şeyi eksiksiz içerir. + +## Sonuç + +Artık **convert html to png**, **render html as image**, **save html to zip**, **apply font style html** ve **add bold to p** işlemlerini birkaç C# satırıyla gerçekleştiren kompakt, üretim‑hazır bir çözümünüz var. Kod bağımsız, .NET 6+ ile çalışıyor ve web içeriğinin hızlı görsel anlık görüntülerine ihtiyaç duyan herhangi bir arka uç servisine kolayca entegre edilebilir. + +Bir sonraki adıma hazır mısınız? Render boyutunu değiştirin, `font-family` veya `color` gibi diğer CSS özellikleriyle deney yapın ya da bu dönüştürücüyü isteğe bağlı PNG dönen bir ASP.NET Core uç noktasına entegre edin. Olanaklar sonsuz ve Aspose.HTML sayesinde ağır tarayıcı bağımlılıklarından uzak kalırsınız. + +Sorun yaşarsanız ya da ekleme fikirleriniz varsa aşağıya yorum bırakın. İyi kodlamalar! + +![convert html to png example](example.png "convert html to png example") + +{{< /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-document-manipulation/_index.md b/html/turkish/net/html-document-manipulation/_index.md index f736f400d..414f044ce 100644 --- a/html/turkish/net/html-document-manipulation/_index.md +++ b/html/turkish/net/html-document-manipulation/_index.md @@ -30,7 +30,7 @@ Eğitimlere dalmadan önce, Aspose.HTML for .NET ile tanışalım. .NET uygulama - Zahmetsiz Belge Dönüştürme: HTML belgelerini birkaç satır kodla PDF, XPS ve daha fazlası gibi çeşitli biçimlere dönüştürün. -- DOM Manipülasyonu: HTML Belge Nesne Modelleri'nin (DOM) derinlemesine manipülasyonunu kolaylıkla gerçekleştirin. +- DOM Manipülasyonu: HTML Belge Nesno Modelleri'nin (DOM) derinlemesine manipülasyonunu kolaylıkla gerçekleştirin. ## Eğitimlerimizi keşfedin @@ -71,6 +71,8 @@ Aspose.HTML for .NET kullanarak dinamik ve web içerikleri oluşturmayı öğren Aspose.HTML for .NET ile web geliştirmenin potansiyelini açığa çıkarın. HTML belgelerini kolayca oluşturun, dönüştürün ve düzenleyin. ### [C#'ta Dizeden HTML Oluşturma – Özel Kaynak İşleyici Rehberi](./create-html-from-string-in-c-custom-resource-handler-guide/) C# içinde dizeden HTML oluşturmayı ve özel kaynak işleyicisiyle nasıl kullanacağınızı öğrenin. +### [C# ile HTML Belgesi Oluşturma – Adım Adım Rehber](./create-html-document-c-step-by-step-guide/) +C# kullanarak Aspose.HTML ile sıfırdan HTML belgesi oluşturmayı adım adım öğrenin. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/turkish/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/turkish/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..f67a6d8f3 --- /dev/null +++ b/html/turkish/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,188 @@ +--- +category: general +date: 2026-03-21 +description: C# ile HTML belgesi oluşturun ve Aspose.Html kullanarak id ile öğeyi + almayı, id ile öğeyi bulmayı, HTML öğesinin stilini değiştirmeyi ve kalın italik + eklemeyi öğrenin. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: tr +og_description: C# ile HTML belgesi oluşturun ve anında id ile öğeyi almayı, id ile + öğeyi bulmayı, HTML öğesinin stilini değiştirmeyi ve net kod örnekleriyle kalın + italik eklemeyi öğrenin. +og_title: HTML Belgesi Oluşturma C# – Tam Programlama Rehberi +tags: +- Aspose.Html +- C# +- DOM manipulation +title: HTML Belgesi Oluşturma C# – Adım Adım Rehber +url: /tr/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML Belgesi Oluşturma C# – Adım Adım Kılavuz + +Hiç **HTML belge C# oluşturma** işini sıfırdan yapıp tek bir paragrafın görünümünü değiştirmek zorunda kaldınız mı? Tek başınıza değilsiniz. Birçok web‑otomasyon projesinde bir HTML dosyası oluşturur, bir etiketi ID'sine göre bulur ve ardından stil uygularsınız—genellikle kalın + italik—tarayıcıya hiç dokunmadan. + +Bu öğreticide tam olarak bunu adım adım göstereceğiz: C#'ta bir HTML belgesi oluşturacağız, **get element by id**, **locate element by id**, **change HTML element style** ve sonunda Aspose.Html kütüphanesini kullanarak **add bold italic** ekleyeceğiz. Sonunda, herhangi bir .NET projesine ekleyebileceğiniz tamamen çalıştırılabilir bir kod parçacığına sahip olacaksınız. + +## İhtiyacınız Olanlar + +- .NET 6 veya üzeri (kod .NET Framework 4.7+ üzerinde de çalışır) +- Visual Studio 2022 (ya da tercih ettiğiniz herhangi bir editör) +- **Aspose.Html** NuGet paketi (`Install-Package Aspose.Html`) + +Hepsi bu—ek HTML dosyaları, web sunucusu yok, sadece birkaç satır C#. + +## HTML Belgesi Oluşturma C# – Belgeyi Başlatma + +İlk olarak: Aspose.Html motorunun çalışabileceği canlı bir `HTMLDocument` nesnesine ihtiyacınız var. Bunu, işaretlemenizi yazacağınız taze bir defter açmak gibi düşünün. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Why this matters:** `HTMLDocument`'e ham dizeyi geçirerek dosya G/Ç ile uğraşmaz ve her şeyi bellek içinde tutarsınız—birim testleri veya anlık oluşturma için mükemmel. + +## ID ile Eleman Al – Paragrafı Bulma + +Şimdi belge mevcut olduğuna göre **get element by id** yapmamız gerekiyor. DOM API'si bize `GetElementById` sunar; bu, bir `IElement` referansı ya da ID bulunamazsa `null` döndürür. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Pro tip:** İşaretlememiz çok küçük olsa bile, bir null‑kontrolü eklemek aynı mantığı daha büyük, dinamik sayfalarda yeniden kullandığınızda baş ağrısını önler. + +## ID ile Eleman Bul – Alternatif Bir Yaklaşım + +Bazen belgenin köküne zaten bir referansınız olabilir ve sorgu‑tarzı bir aramayı tercih edebilirsiniz. CSS seçicileri (`QuerySelector`) kullanmak **locate element by id** için başka bir yoldur: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **When to use which?** `GetElementById` doğrudan bir hash araması olduğu için biraz daha hızlıdır. `QuerySelector` ise karmaşık seçicilere (ör. `div > p.highlight`) ihtiyaç duyduğunuzda öne çıkar. + +## HTML Eleman Stilini Değiştir – Kalın İtalik Ekleme + +Elemanı elde ettikten sonra bir sonraki adım **change HTML element style** yapmaktır. Aspose.Html, CSS özelliklerini ayarlayabileceğiniz bir `Style` nesnesi sunar veya birden fazla yazı tipi özelliğini aynı anda uygulamak için kullanışlı `WebFontStyle` enum'ını kullanabilirsiniz. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +### Tam Çalışan Örnek + +Tüm parçaları bir araya getirdiğinizde, derleyip hemen çalıştırabileceğiniz kompakt, bağımsız bir program elde edersiniz: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Expected output** + +``` +Rendered HTML: +

Hello world

+``` + +`

` etiketi artık metni hem kalın hem de italik yapan bir satır içi `style` niteliğine sahip—tam da istediğimiz gibi. + +## Kenar Durumları ve Yaygın Tuzaklar + +| Durum | Dikkat Edilmesi Gereken | Nasıl Ele Alınır | +|-----------|-------------------|---------------| +| **ID mevcut değil** | `GetElementById` `null` döndürür. | Bir istisna fırlatın ya da varsayılan bir elemana geri dönün. | +| **Birden çok eleman aynı ID'yi paylaşıyor** | HTML spesifikasyonu ID'lerin benzersiz olması gerektiğini söyler, ancak gerçek dünyadaki sayfalar bazen bu kuralı ihlal eder. | `GetElementById` ilk eşleşmeyi döndürür; çoğullukları yönetmeniz gerekiyorsa `QuerySelectorAll` kullanmayı düşünün. | +| **Stil çakışmaları** | Mevcut satır içi stiller üzerine yazılabilir. | Tüm `style` dizesini ayarlamak yerine `Style` nesnesine ekleyin: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Tarayıcıda render** | Bazı tarayıcılar, elemanın zaten daha yüksek özgüllüğe sahip bir CSS sınıfı varsa `WebFontStyle`'ı görmez. | Gerekirse `paragraph.Style.SetProperty("font-weight", "bold", "important");` ile `!important` kullanın. | + +## Gerçek Dünya Projeleri için Pro İpuçları + +- **Cache the document** birden çok eleman işliyorsanız; her küçük snippet için yeni bir `HTMLDocument` oluşturmak performansı düşürebilir. +- **Combine style changes** tek bir `Style` işlemi içinde birleştirerek birden çok DOM yeniden akışını önleyin. +- **Leverage Aspose.Html’s rendering engine** son belgeyi PDF veya görüntü olarak dışa aktarmak için kullanın—raporlama araçları için harika. + +## Görsel Doğrulama (Opsiyonel) + +Sonucu bir tarayıcıda görmek isterseniz, render edilen dizeyi bir `.html` dosyasına kaydedebilirsiniz: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +`output.html` dosyasını açın ve **Hello world** metninin kalın + italik olarak görüntülendiğini göreceksiniz. + +![HTML Belgesi Oluşturma C# örneği, kalın italik paragraf gösterimi](/images/create-html-document-csharp.png "HTML Belgesi Oluşturma C# – render edilmiş çıktı") + +*Alt metin: HTML Belgesi Oluşturma C# – render edilmiş çıktı, kalın italik metin.* + +## Sonuç + +Şimdi **created an HTML document C#**, **got element by id**, **located element by id**, **changed HTML element style** ve sonunda **added bold italic** işlemlerini Aspose.Html kullanarak birkaç satır kodla gerçekleştirdik. Yaklaşım basit, herhangi bir .NET ortamında çalışır ve daha büyük DOM manipülasyonlarına ölçeklenebilir. + +Bir sonraki adıma hazır mısınız? `WebFontStyle`'ı `Underline` gibi diğer enum'larla değiştirin ya da birden çok stili manuel olarak birleştirin. Ya da harici bir HTML dosyası yükleyip aynı tekniği yüzlerce elemana uygulamayı deneyin. Ufkunuz sınırsız ve şimdi üzerine inşa edebileceğiniz sağlam bir temele sahipsiniz. + +Kodlamaktan keyif alın! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/turkish/net/html-extensions-and-conversions/_index.md b/html/turkish/net/html-extensions-and-conversions/_index.md index 8dd996b05..85d4ea027 100644 --- a/html/turkish/net/html-extensions-and-conversions/_index.md +++ b/html/turkish/net/html-extensions-and-conversions/_index.md @@ -39,6 +39,8 @@ Aspose.HTML for .NET yalnızca bir kütüphane değil; web geliştirme dünyası ## HTML Uzantıları ve Dönüşümleri Eğitimleri ### [Aspose.HTML ile .NET'te HTML'yi PDF'ye dönüştürün](./convert-html-to-pdf/) Aspose.HTML for .NET ile HTML'yi zahmetsizce PDF'ye dönüştürün. Adım adım kılavuzumuzu izleyin ve HTML'den PDF'ye dönüştürmenin gücünü serbest bırakın. +### [Aspose.HTML ile HTML'den PDF Oluşturma – Adım Adım C# Kılavuzu](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Aspose.HTML for .NET kullanarak HTML'den PDF oluşturmayı adım adım öğrenin. C# ile kolayca PDF'ye dönüştürün. ### [Aspose.HTML ile .NET'te EPUB'ı Görüntüye Dönüştürme](./convert-epub-to-image/) Aspose.HTML for .NET kullanarak EPUB'ı görsellere nasıl dönüştüreceğinizi öğrenin. Kod örnekleri ve özelleştirilebilir seçenekler içeren adım adım eğitim. ### [Aspose.HTML ile .NET'te EPUB'ı PDF'ye dönüştürün](./convert-epub-to-pdf/) @@ -59,6 +61,8 @@ Etkili içerik düzenlemesi için Aspose.HTML kullanarak .NET'te HTML'yi Markdow Aspose.HTML ile .NET'te HTML'yi MHTML'ye dönüştürün - Etkili web içeriği arşivleme için adım adım bir kılavuz. MHTML arşivleri oluşturmak için .NET için Aspose.HTML'yi nasıl kullanacağınızı öğrenin. ### [Aspose.HTML ile .NET'te HTML'yi PNG'ye dönüştürün](./convert-html-to-png/) HTML belgelerini düzenlemek ve dönüştürmek için Aspose.HTML for .NET'in nasıl kullanılacağını keşfedin. Etkili .NET geliştirme için adım adım kılavuz. +### [Aspose.HTML ile .NET'te HTML'yi Görsele Dönüştürme – Tam Kılavuz](./convert-html-to-image-in-c-complete-guide/) +Aspose.HTML for .NET kullanarak HTML'yi görsellere dönüştürün. Adım adım kılavuzla C#'ta görsel dönüşümün tüm detaylarını öğrenin. ### [Aspose.HTML ile .NET'te HTML'yi TIFF'e dönüştürün](./convert-html-to-tiff/) Aspose.HTML for .NET ile HTML'yi TIFF'e nasıl dönüştüreceğinizi öğrenin. Etkili web içeriği optimizasyonu için adım adım kılavuzumuzu izleyin. ### [Aspose.HTML ile .NET'te HTML'yi XPS'e dönüştürün](./convert-html-to-xps/) @@ -71,6 +75,9 @@ Aspose.HTML for .NET kullanarak HTML'den PDF'ye nasıl dönüştüreceğinizi ad 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. +### [C# ile HTML'yi ZIP Olarak Kaydet – Özel Depolama ile Tam Kılavuz](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Aspose.HTML for .NET kullanarak HTML dosyasını özel depolama alanına ZIP arşivi olarak kaydetmeyi adım adım öğrenin. +### [Aspose.HTML ile HTML'i ZIP'e Sıkıştırma – Tam Kılavuz](./how-to-zip-html-with-aspose-html-complete-guide/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/turkish/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/turkish/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..7a7cc9ace --- /dev/null +++ b/html/turkish/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: C#'ta Aspose.HTML kullanarak HTML'yi görüntüye dönüştürün. HTML'yi PNG + olarak kaydetmeyi, görüntü boyutunu ayarlamayı ve görüntüyü dosyaya yazmayı sadece + birkaç adımda öğrenin. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: tr +og_description: HTML'yi hızlı bir şekilde görüntüye dönüştürün. Bu kılavuz, HTML'yi + PNG olarak kaydetmeyi, görüntü boyutunu ayarlamayı ve Aspose.HTML ile görüntüyü + dosyaya yazmayı gösterir. +og_title: C# ile HTML'yi Görsele Dönüştür – Adım Adım Rehber +tags: +- Aspose.HTML +- C# +- Image Rendering +title: C#'ta HTML'yi Görsele Dönüştürme – Tam Rehber +url: /tr/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML'yi Görüntüye Dönüştürme C# – Tam Kılavuz + +Hiç **HTML'yi görüntüye dönüştür** ihtiyacı duydunuz mu; bir gösterge paneli küçük resmi, bir e‑posta ön izlemesi ya da bir PDF raporu için? Bu senaryo, özellikle dinamik web içeriğini başka bir yere gömmeniz gerektiğinde, beklediğinizden daha sık karşınıza çıkar. + +İyi haber? Aspose.HTML ile sadece birkaç satır kodla **HTML'yi görüntüye dönüştür**ebilir ve aynı zamanda *HTML'yi PNG olarak kaydet*, çıktı boyutlarını kontrol et ve *görüntüyü dosyaya yaz* konularını da sorunsuz öğrenebilirsiniz. + +Bu öğreticide, uzaktaki bir sayfayı yüklemekten render boyutunu ayarlamaya, son olarak sonucu diske PNG dosyası olarak kalıcı hale getirmeye kadar bilmeniz gereken her şeyi adım adım ele alacağız. Harici araçlar, karmaşık komut satırı hileleri yok — sadece herhangi bir .NET projesine ekleyebileceğiniz saf C# kodu. + +## Öğrenecekleriniz + +- Aspose.HTML’nin `HTMLDocument` sınıfını kullanarak **web sayfasını PNG olarak render** etme. +- **Görüntü boyutu render** ayarlarını tam olarak yaparak çıktının tasarım gereksinimlerinize uymasını sağlama. +- **Görüntüyü dosyaya yaz** işlemini güvenli bir şekilde gerçekleştirme, akışları ve dosya yollarını yönetme. +- Eksik fontlar veya ağ zaman aşımı gibi yaygın sorunların nasıl giderileceğine dair ipuçları. + +### Önkoşullar + +- .NET 6.0 veya üzeri (API, .NET Framework ile de çalışır, ancak .NET 6+ önerilir). +- Aspose.HTML for .NET NuGet paketine referans (`Aspose.Html`). +- C# ve async/await konusunda temel bilgi (opsiyonel ama faydalı). + +Bu şartlar sizde mevcutsa, HTML'yi görüntüye dönüştürmeye hemen başlayabilirsiniz. + +## Adım 1: Web Sayfasını Yükle – HTML'yi Görüntüye Dönüştürmenin Temeli + +Render işlemi başlamadan önce, yakalamak istediğiniz sayfayı temsil eden bir `HTMLDocument` örneğine ihtiyacınız var. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Neden önemli:* `HTMLDocument` HTML'i ayrıştırır, CSS'i çözer ve DOM'u oluşturur. Belge yüklenemezse (ör. ağ sorunu) sonraki render işlemi boş bir görüntü üretir. Devam etmeden önce URL'nin erişilebilir olduğundan emin olun. + +## Adım 2: Görüntü Boyutu Render – Genişlik, Yükseklik ve Kaliteyi Kontrol Et + +Aspose.HTML, `ImageRenderingOptions` ile çıktı boyutlarını ince ayar yapmanıza olanak tanır. İşte **görüntü boyutu render** ayarlarını hedef düzeninize göre belirlediğiniz yer. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Profesyonel ipucu:* `Width` ve `Height` değerlerini atlamazsanız, Aspose.HTML sayfanın içsel boyutunu kullanır; bu da responsive tasarımlar için öngörülemez olabilir. Açık boyutlar belirlemek, **HTML'yi PNG olarak kaydet** çıktısının tam istediğiniz gibi görünmesini sağlar. + +## Adım 3: Görüntüyü Dosyaya Yaz – Render Edilen PNG'yi Kalıcılaştır + +Artık belge hazır ve render seçenekleri ayarlandı, sonunda **görüntüyü dosyaya yaz**abilirsiniz. `FileStream` kullanmak, klasör henüz mevcut olmasa bile dosyanın güvenli bir şekilde oluşturulmasını garanti eder. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +Bu blok çalıştıktan sonra, belirttiğiniz konumda `page.png` dosyasını bulacaksınız. Tek bir, basit işlemle **web sayfasını PNG olarak render** edip diske kaydettiniz. + +### Beklenen Sonuç + +`C:\Temp\page.png` dosyasını herhangi bir görüntü görüntüleyicide açın. `https://example.com` sitesinin 1024 × 768 piksel boyutunda, antialiasing sayesinde yumuşak kenarlı bir anlık görüntüsünü görmelisiniz. Sayfa dinamik içerik (ör. JavaScript‑tarafından oluşturulan öğeler) içeriyorsa, DOM tamamen yüklendiği sürece bu öğeler de yakalanır. + +## Adım 4: Kenar Durumlarını Ele Alma – Fontlar, Kimlik Doğrulama ve Büyük Sayfalar + +Temel akış çoğu halka açık site için çalışsa da, gerçek dünya senaryoları sık sık sürprizler çıkarır: + +| Durum | Yapılması Gereken | +|-----------|------------| +| **Özel fontların yüklenmemesi** | Font dosyalarını yerel olarak ekleyin ve `htmlDoc.Fonts.Add("path/to/font.ttf")` ile ayarlayın. | +| **Kimlik doğrulama gerektiren sayfalar** | Çerez veya token içeren `HttpWebRequest` kabul eden `HTMLDocument` aşırı yüklemesini kullanın. | +| **Çok uzun sayfalar** | Kesintiyi önlemek için `Height` değerini artırın veya `ImageRenderingOptions` içinde `PageScaling` özelliğini etkinleştirin. | +| **Bellek kullanımının ani artışı** | `RenderToImage` aşırı yüklemesinin `Rectangle` bölgesi kabul eden sürümünü kullanarak parçalar halinde render edin. | + +Bu *görüntüyü dosyaya yaz* inceliklerini ele almak, **HTML'yi görüntüye dönüştür** hattınızın üretimde sağlam kalmasını sağlar. + +## Adım 5: Tam Çalışan Örnek – Kopyala‑Yapıştır Hazır + +Aşağıda, derlenmeye hazır tüm program yer alıyor. Tüm adımları, hata yönetimini ve ihtiyacınız olan yorumları içeriyor. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Bu programı çalıştırın; konsolda onay mesajını göreceksiniz. PNG dosyası, bir tarayıcıda **web sayfasını PNG olarak render** edip ekran görüntüsü almanızla aynı sonucu verir — sadece çok daha hızlı ve tamamen otomatik. + +## Sıkça Sorulan Sorular + +**S: URL yerine yerel bir HTML dosyasını dönüştürebilir miyim?** +Elbette. URL'yi dosya yolu ile değiştirin: `new HTMLDocument(@"C:\myPage.html")`. + +**S: Aspose.HTML için lisansa ihtiyacım var mı?** +Ücretsiz deneme lisansı geliştirme ve test için yeterlidir. Üretim ortamında değerlendirme filigranını kaldırmak için bir lisans satın alın. + +**S: Sayfa, içerik yüklemek için JavaScript kullanıyorsa ne olur?** +Aspose.HTML, ayrıştırma sırasında JavaScript'i senkron olarak çalıştırır, ancak uzun süren script'ler için manuel bir gecikme gerekebilir. Render öncesinde `HTMLDocument.WaitForReadyState` kullanabilirsiniz. + +## Sonuç + +Artık C# içinde **HTML'yi görüntüye dönüştür** için sağlam, uçtan uca bir çözümünüz var. Yukarıdaki adımları izleyerek **HTML'yi PNG olarak kaydet**, tam olarak **görüntü boyutu render** ayarlarını yapabilir ve **görüntüyü dosyaya yaz** işlemini herhangi bir Windows ya da Linux ortamında güvenle gerçekleştirebilirsiniz. + +Basit ekran görüntülerinden otomatik rapor üretimine kadar bu teknik sorunsuz ölçeklenir. Sonraki adımda JPEG veya BMP gibi diğer çıktı formatlarıyla denemeler yapabilir ya da kodu doğrudan PNG'yi çağrılara dönen bir ASP.NET Core API'sine entegre edebilirsiniz. Olanaklar neredeyse sınırsız. + +İyi kodlamalar, ve render ettiğiniz görüntüler her zaman piksel‑kusursuz olsun! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/turkish/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..a80f07bba --- /dev/null +++ b/html/turkish/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-03-21 +description: Aspose HTML kullanarak HTML'den hızlıca PDF oluşturun. HTML'yi PDF'ye + render etmeyi, HTML'yi PDF'ye dönüştürmeyi ve Aspose'u nasıl kullanacağınızı kısa + bir öğreticide öğrenin. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: tr +og_description: Aspose ile C#'ta HTML'den PDF oluşturun. Bu kılavuz, HTML'yi PDF'ye + nasıl render edeceğinizi, HTML'yi PDF'ye nasıl dönüştüreceğinizi ve Aspose'u etkili + bir şekilde nasıl kullanacağınızı gösterir. +og_title: HTML'den PDF Oluşturma – Tam Aspose C# Öğreticisi +tags: +- Aspose +- C# +- PDF generation +title: Aspose ile HTML'den PDF Oluşturma – Adım Adım C# Rehberi +url: /tr/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# HTML'den PDF Oluşturma Aspose ile – Adım‑Adım C# Rehberi + +HTML'den **PDF oluşturma** ihtiyacı hiç duydunuz mu ama hangi kütüphanenin pikselleri mükemmel sonuçlar vereceğinden emin değildiniz? Yalnız değilsiniz. Birçok geliştirici, bir web parçacığını yazdırılabilir bir belgeye dönüştürmeye çalışırken, bulanık metinler veya bozuk düzenlerle karşılaşıyor. + +İyi haber, Aspose HTML'in tüm süreci sorunsuz hâle getirmesi. Bu öğreticide **HTML'yi PDF'ye render** etmek için gereken tam kodu adım adım inceleyecek, her ayarın neden önemli olduğunu keşfedecek ve **HTML'yi PDF'ye dönüştürme** işlemini gizli bir hile olmadan nasıl yapacağınızı göstereceğiz. Sonunda, **Aspose'ı nasıl kullanacağınızı** .NET projenizde güvenilir PDF üretimi için öğreneceksiniz. + +## Ön Koşullar – Başlamadan Önce Neye İhtiyacınız Olacak + +- **.NET 6.0 veya üzeri** (örnek .NET Framework 4.7+ üzerinde de çalışır) +- **Visual Studio 2022** veya C# destekleyen herhangi bir IDE +- **Aspose.HTML for .NET** NuGet paketi (ücretsiz deneme veya lisanslı sürüm) +- C# sözdizimi hakkında temel bir anlayış (derin PDF bilgisi gerektirmez) + +Eğer bunlara sahipseniz, hazırsınız. Aksi takdirde, en son .NET SDK'sını alın ve NuGet paketini şu şekilde kurun: + +```bash +dotnet add package Aspose.HTML +``` + +Bu tek satır, **aspose html to pdf** dönüşümü için ihtiyacınız olan her şeyi getirir. + +--- + +## Adım 1: HTML'den PDF Oluşturmak İçin Projenizi Kurun + +İlk olarak yeni bir konsol uygulaması oluşturursunuz (veya kodu mevcut bir servise entegre edersiniz). İşte minimal bir `Program.cs` iskeleti: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Pro ipucu:** Eski örneklerde `Aspise.Html.Rendering.Text` görürseniz, bunu `Aspose.Html.Rendering.Text` ile değiştirin. Yazım hatası derleme hatasına yol açar. + +Doğru ad alanlarını kullanmak, derleyicinin daha sonra ihtiyaç duyacağımız **TextOptions** sınıfını bulmasını sağlar. + +## Adım 2: HTML Belgesini Oluşturun (HTML'yi PDF'ye Render Etme) + +Şimdi kaynak HTML'i oluşturuyoruz. Aspose, ham bir dize, dosya yolu veya hatta bir URL geçmenize izin verir. Bu demo için basit tutacağız: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Neden bir dize geçiyoruz? Bu, dosya sistemi I/O'sundan kaçınır, dönüşümü hızlandırır ve kodda gördüğünüz HTML'in tam olarak render edildiğinden emin olur. Dosyadan yüklemeyi tercih ederseniz, sadece yapıcı argümanını bir dosya URI'siyle değiştirin. + +## Adım 3: Metin Render'ını İnce Ayar Yapın (HTML'yi Daha İyi Kalitede PDF'ye Dönüştürme) + +Metin render'ı genellikle PDF'in net mi yoksa bulanık mı göründüğünü belirler. Aspose, yüksek DPI çıktısı için gerekli olan alt‑piksel ipuçlamasını etkinleştirmenizi sağlayan bir `TextOptions` sınıfı sunar. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +`UseHinting`'i etkinleştirmek, kaynak HTML'inizde özel yazı tipleri veya küçük font boyutları olduğunda özellikle faydalıdır. Bunu yapmazsanız, son PDF'de tırtıklı kenarlar görebilirsiniz. + +## Adım 4: Metin Seçeneklerini PDF Render Yapılandırmasına Bağlayın (Aspose Nasıl Kullanılır) + +Şimdi bu metin seçeneklerini PDF render'ına bağlıyoruz. İşte **aspose html to pdf**'in gerçekten parladığı yer—sayfa boyutundan sıkıştırmaya kadar her şey ayarlanabilir. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Varsayılan A4 boyutundan memnunsanız `PageSetup`'ı atlayabilirsiniz. Önemli nokta, `TextOptions` nesnesinin `PdfRenderingOptions` içinde yer alması ve Aspose'a metni *nasıl* render edeceğini bu şekilde söylemeniz. + +## Adım 5: HTML'i Render Edin ve PDF'i Kaydedin (HTML'yi PDF'ye Dönüştürme) + +Son olarak, çıktıyı bir dosyaya akıtıyoruz. Bir `using` bloğu kullanmak, bir istisna oluşsa bile dosya tutamacının düzgün bir şekilde kapatılmasını garanti eder. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Programı çalıştırdığınızda, yürütülebilir dosyanın yanında `output.pdf` dosyasını bulacaksınız. Açın ve HTML dizesinde tanımlandığı gibi temiz bir başlık ve paragraf görmelisiniz. + +### Beklenen Çıktı + +![HTML'den PDF oluşturma örnek çıktısı](https://example.com/images/pdf-output.png "HTML'den PDF oluşturma örnek çıktısı") + +*Ekran görüntüsü, “Hello, Aspose!” başlığıyla oluşturulan PDF'i, metin ipuçlaması sayesinde keskin bir şekilde render edildiğini gösterir.* + +--- + +## Yaygın Sorular ve Kenar Durumları + +### 1. HTML'im dış kaynaklara (görseller, CSS) referans veriyorsa ne olur? + +Aspose, belgeye göreli URL'leri temel URI'ye göre çözer. Ham bir dize sağlıyorsanız, temel URI'yi manuel olarak ayarlayın: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Artık herhangi bir `` ifadesi `C:/MyProject/` konumuna göre aranacaktır. + +### 2. Sunucuda yüklü olmayan yazı tiplerini nasıl gömebilirim? + +Yerel veya uzak bir yazı tipi dosyasına işaret eden `@font-face` kullanan bir ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Adım 4: Kaydetme Seçeneklerini Özel Depolamayı Kullanacak Şekilde Yapılandırın + +`HtmlSaveOptions`, Aspose'a her şeyi bir ZIP dosyasına paketlemesini söyler. `OutputStorage` özelliği (eski) bizim `MyStorage` örneğimizi alır. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Not:** Aspose HTML 23.9+ sürümünde özellik `OutputStorage` olarak adlandırılmış ancak kullanımdan kaldırılmıştır. Modern alternatif `ZipOutputStorage`'dır. Aşağıdaki kod her ikisiyle de çalışır çünkü arayüz aynı. + +### Adım 5: Belgeyi ZIP Arşivi Olarak Kaydedin + +Hedef bir klasör (veya akış) seçin ve Aspose'un işi halletmesine izin verin. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Program tamamlandığında içinde `output.zip` dosyasını bulacaksınız: + +* `index.html` – ana belge. +* Gömülü resimler, CSS dosyaları veya betikler (HTML'niz bunlara referans veriyorsa). + +ZIP'i herhangi bir arşiv yöneticisiyle açarak yapıyı doğrulayabilirsiniz. + +--- + +## Sonucu Doğrulama (İsteğe Bağlı) + +Arşivi diske çıkarmadan programatik olarak incelemek istiyorsanız: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Tipik çıktı: + +``` +- index.html (452 bytes) +``` + +Eğer resimler veya CSS dosyalarınız varsa, ek girişler olarak görüneceklerdir. Bu hızlı kontrol, **create html zip archive** işleminin beklendiği gibi çalıştığını doğrular. + +## Yaygın Sorular & Kenar Durumları + +| Soru | Cevap | +|----------|--------| +| **ZIP'i doğrudan bir yanıt akışına yazmam gerekirse ne olur?** | `document.Save` işleminden sonra `MyStorage`'tan aldığınız `MemoryStream`'i döndürün. Bunu `byte[]`'e dönüştürün ve `HttpResponse.Body`'ye yazın. | +| **HTML'm dış URL'lere referans veriyor—indirilecek mi?** | Hayır. Aspose yalnızca *gömülü* kaynakları paketler (ör. `` veya yerel dosyalar). Uzaktaki varlıklar için önce onları indirmeniz ve işaretlemeyi buna göre ayarlamanız gerekir. | +| **`OutputStorage` özelliği kullanımdan kaldırıldı—göz ardı etmeliyim mi?** | Hâlâ çalışıyor, ancak daha yeni `ZipOutputStorage` aynı API'yi farklı bir adla sunar. Uyarısız bir derleme istiyorsanız `OutputStorage`'ı `ZipOutputStorage` ile değiştirin. | +| **ZIP'i şifreleyebilir miyim?** | Evet. Kaydettikten sonra dosyayı `System.IO.Compression.ZipArchive` ile açın ve `SharpZipLib` gibi üçüncü taraf kütüphanelerle bir şifre belirleyin. Aspose kendisi şifreleme sağlamaz. | + +## Tam Çalışan Örnek (Kopyala‑Yapıştır) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Programı çalıştırın, `output.zip` dosyasını açın ve tarayıcıda açıldığında “Hello from ZIP!” başlığını gösteren tek bir `index.html` dosyası göreceksiniz. + +## Sonuç + +Artık C#'ta bir **özel depolama** sınıfı kullanarak **HTML'yi ZIP olarak kaydetmenin**, **HTML'yi ZIP'e dışa aktarmanın** ve dağıtıma hazır bir **HTML zip arşivi oluşturmanın** nasıl yapılacağını biliyorsunuz. Desen esnek—`MemoryStream`'i bir bulut akışıyla değiştirin, şifreleme ekleyin veya ZIP'i isteğe bağlı olarak döndüren bir web API'sine entegre edin. + +Bir sonraki adıma hazır mısınız? Görseller ve stiller içeren tam bir web sayfasını deneyin ya da depolamayı Azure Blob Storage'a bağlayarak yerel dosya sistemini tamamen atlayın. Aspose.HTML’in ZIP yeteneklerini kendi depolama mantığınızla birleştirdiğinizde sınır yoktur. + +Kodlamaktan keyif alın, ve arşivleriniz her zaman düzenli olsun! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/vietnamese/net/generate-jpg-and-png-images/_index.md b/html/vietnamese/net/generate-jpg-and-png-images/_index.md index 364f75161..d96bf20a4 100644 --- a/html/vietnamese/net/generate-jpg-and-png-images/_index.md +++ b/html/vietnamese/net/generate-jpg-and-png-images/_index.md @@ -45,6 +45,8 @@ Học cách sử dụng Aspose.HTML cho .NET để thao tác với các tài li Hướng dẫn chi tiết cách bật khử răng cưa để cải thiện chất lượng hình ảnh khi chuyển đổi tài liệu DOCX sang PNG hoặc JPG bằng Aspose.HTML. ### [Chuyển đổi DOCX sang PNG – tạo tệp ZIP bằng C# – Hướng dẫn](./convert-docx-to-png-create-zip-archive-c-tutorial/) Hướng dẫn cách chuyển đổi tài liệu DOCX thành hình ảnh PNG và đóng gói chúng vào tệp ZIP bằng C#. +### [Chuyển đổi HTML sang PNG – Hướng dẫn đầy đủ C# với xuất ZIP](./convert-html-to-png-full-c-guide-with-zip-export/) +Hướng dẫn chi tiết cách chuyển đổi HTML thành PNG và xuất kết quả vào tệp ZIP bằng C#. ## Phần kết luận diff --git a/html/vietnamese/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md b/html/vietnamese/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md new file mode 100644 index 000000000..9041b6320 --- /dev/null +++ b/html/vietnamese/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-03-21 +description: Chuyển đổi HTML sang PNG và hiển thị HTML dưới dạng hình ảnh trong khi + lưu HTML vào ZIP. Học cách áp dụng kiểu phông chữ HTML và thêm in đậm cho các phần + tử p chỉ trong vài bước. +draft: false +keywords: +- convert html to png +- render html as image +- save html to zip +- apply font style html +- add bold to p +language: vi +og_description: Chuyển đổi HTML sang PNG nhanh chóng. Hướng dẫn này chỉ cách render + HTML thành hình ảnh, lưu HTML vào file ZIP, áp dụng kiểu phông chữ cho HTML và thêm + in đậm cho các phần tử p. +og_title: Chuyển đổi HTML sang PNG – Hướng dẫn C# đầy đủ +tags: +- Aspose +- C# +title: Chuyển đổi HTML sang PNG – Hướng dẫn C# đầy đủ với xuất file ZIP +url: /vi/net/generate-jpg-and-png-images/convert-html-to-png-full-c-guide-with-zip-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Chuyển đổi HTML sang PNG – Hướng dẫn đầy đủ bằng C# với xuất ZIP + +Bạn đã bao giờ cần **chuyển đổi HTML sang PNG** nhưng không chắc thư viện nào có thể thực hiện mà không cần dùng trình duyệt không giao diện? Bạn không phải là người duy nhất. Trong nhiều dự án—hình thu nhỏ email, bản xem trước tài liệu, hoặc hình ảnh xem nhanh—việc biến một trang web thành một bức ảnh tĩnh là nhu cầu thực tế. + +Tin tốt là gì? Với Aspose.HTML, bạn có thể **render HTML as image**, chỉnh sửa markup ngay lập tức, và thậm chí **save HTML to ZIP** để phân phối sau. Trong hướng dẫn này, chúng ta sẽ đi qua một ví dụ hoàn chỉnh, có thể chạy được, **áp dụng font style HTML**, cụ thể là **thêm in đậm cho các thẻ p**, trước khi tạo ra file PNG. Khi kết thúc, bạn sẽ có một lớp C# duy nhất thực hiện mọi thứ từ tải trang đến nén tài nguyên. + +## Những gì bạn cần + +- .NET 6.0 hoặc mới hơn (API cũng hoạt động trên .NET Core) +- Aspose.HTML cho .NET 6+ (gói NuGet `Aspose.Html`) +- Kiến thức cơ bản về cú pháp C# (không cần khái niệm nâng cao) + +Chỉ vậy thôi. Không cần trình duyệt bên ngoài, không cần phantomjs, chỉ thuần mã quản lý. + +## Bước 1 – Tải tài liệu HTML + +Đầu tiên chúng ta đưa file nguồn (hoặc URL) vào một đối tượng `HTMLDocument`. Bước này là nền tảng cho cả **render html as image** và **save html to zip** sau này. + +```csharp +using Aspose.Html; +using System.IO; + +/// +/// Loads an HTML file from disk or a remote address. +/// +private HTMLDocument LoadDocument(string sourcePath) +{ + // Aspose.HTML automatically detects whether sourcePath is a file or a URL. + return new HTMLDocument(sourcePath); +} +``` + +*Lý do quan trọng:* Lớp `HTMLDocument` phân tích markup, xây dựng DOM, và giải quyết các tài nguyên liên kết (CSS, hình ảnh, phông chữ). Nếu không có đối tượng tài liệu đúng, bạn không thể thao tác style hoặc render bất kỳ thứ gì. + +## Bước 2 – Áp dụng Font Style HTML (Thêm in đậm cho p) + +Bây giờ chúng ta sẽ **apply font style HTML** bằng cách duyệt qua mọi phần tử `

` và đặt `font-weight` thành bold. Đây là cách lập trình để **add bold to p** mà không cần sửa file gốc. + +```csharp +using Aspose.Html.Drawing; + +///

+/// Makes every paragraph bold using the DOM API. +/// +private void BoldParagraphs(HTMLDocument doc) +{ + foreach (var paragraph in doc.QuerySelectorAll("p")) + { + // WebFontStyle.Bold is the Aspose enum that maps to CSS font-weight: bold. + paragraph.Style.FontStyle = WebFontStyle.Bold; + } +} +``` + +*Mẹo:* Nếu bạn chỉ cần in đậm một phần, hãy thay selector bằng một cái cụ thể hơn, ví dụ: `"p.intro"`. + +## Bước 3 – Render HTML as Image (Chuyển đổi HTML sang PNG) + +Khi DOM đã sẵn sàng, chúng ta cấu hình `ImageRenderingOptions` và gọi `RenderToImage`. Đây là nơi phép thuật **convert html to png** diễn ra. + +```csharp +using Aspose.Html.Rendering.Image; + +/// +/// Renders the modified HTML document to a PNG file. +/// +private void RenderToPng(HTMLDocument doc, string outputPath) +{ + var options = new ImageRenderingOptions + { + Width = 1200, // Desired width in pixels + Height = 800, // Desired height in pixels + UseAntialiasing = true + }; + + // Ensure the directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + using (var stream = File.Create(outputPath)) + { + doc.RenderToImage(stream, options); + } +} +``` + +*Tại sao các tùy chọn quan trọng:* Đặt chiều rộng/chiều cao cố định ngăn kết quả quá lớn, trong khi antialiasing mang lại hình ảnh mượt hơn. Bạn cũng có thể chuyển `options` sang `ImageFormat.Jpeg` nếu muốn file có kích thước nhỏ hơn. + +## Bước 4 – Lưu HTML vào ZIP (Gói tài nguyên) + +Thường bạn cần đóng gói HTML gốc cùng với CSS, hình ảnh và phông chữ. `ZipArchiveSaveOptions` của Aspose.HTML làm đúng điều này. Chúng ta cũng chèn một `ResourceHandler` tùy chỉnh để tất cả các tài nguyên bên ngoài được ghi vào cùng thư mục với file nén. + +```csharp +using Aspose.Html.Saving; + +/// +/// Saves the HTML document and all linked resources into a ZIP archive. +/// +private void SaveToZip(HTMLDocument doc, string zipPath, string resourcesFolder) +{ + var zipOptions = new ZipArchiveSaveOptions + { + // Custom handler stores each resource next to the ZIP file. + ResourceHandler = new MyResourceHandler(resourcesFolder) + }; + + using (var zipStream = File.Create(zipPath)) + { + doc.Save(zipStream, zipOptions); + } +} +``` + +*Trường hợp đặc biệt:* Nếu HTML của bạn tham chiếu tới hình ảnh từ xa yêu cầu xác thực, trình xử lý mặc định sẽ thất bại. Khi đó bạn có thể mở rộng `MyResourceHandler` để chèn các header HTTP. + +## Bước 5 – Kết nối mọi thứ trong một lớp Converter duy nhất + +Dưới đây là lớp hoàn chỉnh, sẵn sàng chạy, kết hợp tất cả các bước trước. Bạn chỉ cần sao chép‑dán vào một console app, gọi `Convert`, và quan sát các file được tạo. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering.Image; +using Aspose.Html.Saving; +using System.IO; + +class Converter +{ + /// + /// Main entry point – loads HTML, bolds paragraphs, renders PNG, and creates a ZIP. + /// + public void Convert(string sourceHtmlPath, string outputDirectory) + { + // 1️⃣ Load the document (supports both local files and URLs) + var document = new HTMLDocument(sourceHtmlPath); + + // 2️⃣ Apply bold style to every

element + foreach (var paragraph in document.QuerySelectorAll("p")) + paragraph.Style.FontStyle = WebFontStyle.Bold; // add bold to p + + // 3️⃣ Render the HTML to a PNG image (convert html to png) + string pngPath = Path.Combine(outputDirectory, "page.png"); + var imageOptions = new ImageRenderingOptions + { + Width = 1200, + Height = 800, + UseAntialiasing = true + }; + using (var pngStream = File.Create(pngPath)) + document.RenderToImage(pngStream, imageOptions); + + // 4️⃣ Save the original HTML plus all its resources into a ZIP archive + string zipPath = Path.Combine(outputDirectory, "archive.zip"); + var zipOptions = new ZipArchiveSaveOptions + { + ResourceHandler = new MyResourceHandler(outputDirectory) + }; + using (var zipStream = File.Create(zipPath)) + document.Save(zipStream, zipOptions); + } +} + +// Example usage – adjust the paths to match your environment +// var converter = new Converter(); +// converter.Convert("C:/MyProject/input.html", "C:/MyProject/output"); +``` + +### Kết quả mong đợi + +Sau khi chạy đoạn mã trên, bạn sẽ thấy hai file trong `outputDirectory`: + +| File | Mô tả | +|------|------| +| `page.png` | Một ảnh PNG kích thước 1200 × 800 được render từ HTML nguồn, với mọi đoạn văn được **in đậm**. | +| `archive.zip` | Một gói ZIP chứa `input.html` gốc, CSS, hình ảnh và bất kỳ web‑fonts nào – hoàn hảo cho việc phân phối offline. | + +Bạn có thể mở `page.png` bằng bất kỳ trình xem ảnh nào để xác nhận style in đậm đã được áp dụng, và giải nén `archive.zip` để xem HTML chưa thay đổi cùng các tài nguyên của nó. + +## Câu hỏi thường gặp & Lưu ý + +- **Nếu HTML chứa JavaScript thì sao?** + Aspose.HTML **không** thực thi script trong quá trình render, vì vậy nội dung động sẽ không xuất hiện. Đối với các trang cần render đầy đủ, bạn sẽ cần một trình duyệt không giao diện, nhưng với các mẫu tĩnh thì cách này nhanh hơn và nhẹ hơn. + +- **Có thể đổi định dạng đầu ra sang JPEG hoặc BMP không?** + Có—chỉ cần thay thuộc tính `ImageFormat` của `ImageRenderingOptions`, ví dụ: `options.ImageFormat = ImageFormat.Jpeg;`. + +- **Có cần phải dispose `HTMLDocument` thủ công không?** + Lớp này triển khai `IDisposable`. Trong một service chạy lâu, hãy bọc nó trong khối `using` hoặc gọi `document.Dispose()` sau khi hoàn thành. + +- **`MyResourceHandler` tùy chỉnh hoạt động như thế nào?** + Nó nhận mỗi tài nguyên bên ngoài (CSS, hình ảnh, phông chữ) và ghi vào thư mục bạn chỉ định. Điều này đảm bảo ZIP chứa bản sao chính xác của mọi thứ mà HTML tham chiếu. + +## Kết luận + +Bây giờ bạn đã có một giải pháp gọn gàng, sẵn sàng cho môi trường production để **convert html to png**, **render html as image**, **save html to zip**, **apply font style html**, và **add bold to p**—tất cả trong vài dòng C#. Mã nguồn độc lập, hoạt động với .NET 6+, và có thể được nhúng vào bất kỳ dịch vụ backend nào cần chụp nhanh nội dung web dưới dạng hình ảnh. + +Sẵn sàng cho bước tiếp theo? Hãy thử thay đổi kích thước render, thử nghiệm các thuộc tính CSS khác (như `font-family` hoặc `color`), hoặc tích hợp converter này vào một endpoint ASP.NET Core trả về PNG theo yêu cầu. Khả năng là vô hạn, và với Aspose.HTML bạn sẽ không phải phụ thuộc vào các trình duyệt nặng. + +Nếu bạn gặp khó khăn hoặc có ý tưởng mở rộng, hãy để lại bình luận bên dưới. Chúc lập trình vui! + +![ví dụ chuyển html sang png](example.png "ví dụ chuyển html sang png") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/vietnamese/net/html-document-manipulation/_index.md b/html/vietnamese/net/html-document-manipulation/_index.md index 69f32029f..0329cd470 100644 --- a/html/vietnamese/net/html-document-manipulation/_index.md +++ b/html/vietnamese/net/html-document-manipulation/_index.md @@ -71,6 +71,8 @@ Học cách sử dụng Aspose.HTML cho .NET. Nhập không gian tên, hợp nh Mở khóa tiềm năng phát triển web với Aspose.HTML cho .NET. Tạo, chuyển đổi và thao tác tài liệu HTML dễ dàng. ### [Tạo HTML từ chuỗi trong C# – Hướng dẫn Trình xử lý tài nguyên tùy chỉnh](./create-html-from-string-in-c-custom-resource-handler-guide/) Tìm hiểu cách tạo tài liệu HTML từ chuỗi trong C# bằng trình xử lý tài nguyên tùy chỉnh của Aspose.HTML. +### [Tạo tài liệu HTML C# – Hướng dẫn từng bước](./create-html-document-c-step-by-step-guide/) +Học cách tạo tài liệu HTML trong C# bằng Aspose.HTML qua các bước chi tiết và ví dụ thực tế. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/html/vietnamese/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md b/html/vietnamese/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..e76e5f9b6 --- /dev/null +++ b/html/vietnamese/net/html-document-manipulation/create-html-document-c-step-by-step-guide/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-03-21 +description: Tạo tài liệu HTML bằng C# và học cách lấy phần tử theo id, định vị phần + tử theo id, thay đổi kiểu dáng của phần tử HTML và thêm in đậm, in nghiêng bằng + Aspose.Html. +draft: false +keywords: +- create html document c# +- get element by id +- locate element by id +- change html element style +- add bold italic +language: vi +og_description: Tạo tài liệu HTML bằng C# và ngay lập tức học cách lấy phần tử theo + id, định vị phần tử theo id, thay đổi kiểu dáng phần tử HTML và thêm in đậm, in + nghiêng với các ví dụ mã rõ ràng. +og_title: Tạo tài liệu HTML C# – Hướng dẫn lập trình toàn diện +tags: +- Aspose.Html +- C# +- DOM manipulation +title: Tạo tài liệu HTML C# – Hướng dẫn từng bước +url: /vi/net/html-document-manipulation/create-html-document-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo Tài liệu HTML C# – Hướng Dẫn Từng Bước + +Bạn đã bao giờ cần **tạo tài liệu HTML C#** từ đầu và sau đó chỉnh sửa giao diện của một đoạn văn duy nhất? Bạn không phải là người duy nhất. Trong nhiều dự án tự động hoá web, bạn sẽ tạo một tệp HTML, tìm một thẻ theo ID của nó, và sau đó áp dụng một số kiểu—thường là in đậm + in nghiêng—mà không cần mở trình duyệt. + +Trong hướng dẫn này, chúng ta sẽ thực hiện đúng như vậy: chúng ta sẽ tạo một tài liệu HTML trong C#, **lấy phần tử theo id**, **tìm phần tử theo id**, **thay đổi kiểu phần tử HTML**, và cuối cùng **thêm in đậm nghiêng** bằng thư viện Aspose.Html. Khi kết thúc, bạn sẽ có một đoạn mã có thể chạy được hoàn toàn mà bạn có thể chèn vào bất kỳ dự án .NET nào. + +## Những gì bạn cần + +- .NET 6 hoặc mới hơn (mã cũng chạy trên .NET Framework 4.7+) +- Visual Studio 2022 (hoặc bất kỳ trình soạn thảo nào bạn thích) +- Gói NuGet **Aspose.Html** (`Install-Package Aspose.Html`) + +Chỉ vậy thôi—không cần tệp HTML bổ sung, không cần máy chủ web, chỉ một vài dòng C#. + +## Tạo Tài liệu HTML C# – Khởi tạo Tài liệu + +Trước hết: bạn cần một đối tượng `HTMLDocument` đang hoạt động mà engine Aspose.Html có thể làm việc. Hãy tưởng tượng đây như mở một cuốn sổ mới nơi bạn sẽ viết markup. + +```csharp +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +// Step 1: Build the HTML markup as a string +string markup = "

Hello world

"; + +// Step 2: Feed the markup into an HTMLDocument instance +HTMLDocument htmlDoc = new HTMLDocument(markup); +``` + +> **Tại sao điều này quan trọng:** Bằng cách truyền chuỗi thô vào `HTMLDocument`, bạn tránh việc xử lý I/O file và giữ mọi thứ trong bộ nhớ—lý tưởng cho các bài kiểm tra đơn vị hoặc việc tạo nhanh trong lúc chạy. + +## Lấy phần tử theo ID – Tìm đoạn văn + +Bây giờ tài liệu đã tồn tại, chúng ta cần **lấy phần tử theo id**. API DOM cung cấp `GetElementById`, trả về một tham chiếu `IElement` hoặc `null` nếu ID không tồn tại. + +```csharp +// Step 3: Retrieve the paragraph using its ID +IElement paragraphElement = htmlDoc.GetElementById("msg"); + +// Defensive check – always a good habit +if (paragraphElement == null) +{ + throw new InvalidOperationException("Element with ID 'msg' not found."); +} +``` + +> **Mẹo chuyên nghiệp:** Mặc dù markup của chúng ta rất nhỏ, việc thêm kiểm tra null sẽ giúp bạn tránh rắc rối khi cùng logic được tái sử dụng trên các trang lớn hơn, động. + +## Tìm phần tử theo ID – Cách tiếp cận thay thế + +Đôi khi bạn đã có tham chiếu tới gốc của tài liệu và muốn tìm kiếm kiểu truy vấn. Sử dụng bộ chọn CSS (`QuerySelector`) là một cách khác để **tìm phần tử theo id**: + +```csharp +// Alternative: using a CSS selector +IElement paragraphAlt = htmlDoc.QuerySelector("#msg"); + +// Both methods return the same element instance +Debug.Assert(paragraphElement == paragraphAlt); +``` + +> **Khi nào nên dùng cái nào?** `GetElementById` nhanh hơn một chút vì nó là tra cứu hash trực tiếp. `QuerySelector` tỏa sáng khi bạn cần các bộ chọn phức tạp (ví dụ, `div > p.highlight`). + +## Thay đổi Kiểu phần tử HTML – Thêm In đậm Nghiêng + +Với phần tử trong tay, bước tiếp theo là **thay đổi kiểu phần tử HTML**. Aspose.Html cung cấp một đối tượng `Style` cho phép bạn điều chỉnh các thuộc tính CSS hoặc sử dụng enum tiện lợi `WebFontStyle` để áp dụng nhiều đặc tính phông chữ cùng lúc. + +```csharp +// Step 4: Apply combined bold and italic styling +paragraphElement.Style.FontStyle = WebFontStyle.BoldItalic; +``` + +Dòng duy nhất đó đặt `font-weight` của phần tử thành `bold` và `font-style` thành `italic`. Bên trong, Aspose.Html chuyển đổi enum thành chuỗi CSS tương ứng. + +### Ví dụ Hoạt động đầy đủ + +Kết hợp tất cả các phần lại với nhau tạo ra một chương trình gọn gàng, tự chứa mà bạn có thể biên dịch và chạy ngay lập tức: + +```csharp +using System; +using Aspose.Html; +using Aspose.Html.Drawing; +using Aspose.Html.Rendering; + +class Program +{ + static void Main() + { + // 1️⃣ Create the HTML markup + string markup = "

Hello world

"; + + // 2️⃣ Load the markup into an HTMLDocument + HTMLDocument htmlDoc = new HTMLDocument(markup); + + // 3️⃣ Find the paragraph by its ID + IElement paragraph = htmlDoc.GetElementById("msg") + ?? throw new InvalidOperationException("Paragraph not found."); + + // 4️⃣ Apply bold + italic style + paragraph.Style.FontStyle = WebFontStyle.BoldItalic; + + // 5️⃣ Render the document to a string for verification + string result = htmlDoc.RenderToString(); + + Console.WriteLine("Rendered HTML:"); + Console.WriteLine(result); + } +} +``` + +**Kết quả mong đợi** + +``` +Rendered HTML: +

Hello world

+``` + +Thẻ `

` giờ đã có thuộc tính `style` nội tuyến khiến văn bản vừa in đậm vừa in nghiêng—đúng như chúng ta mong muốn. + +## Các trường hợp góc cạnh & Những lỗi thường gặp + +| Situation | What to Watch For | How to Handle | +|-----------|-------------------|---------------| +| **ID không tồn tại** | `GetElementById` trả về `null`. | Ném một ngoại lệ hoặc chuyển sang phần tử mặc định. | +| **Nhiều phần tử chia sẻ cùng một ID** | Đặc tả HTML nói ID phải là duy nhất, nhưng các trang thực tế đôi khi vi phạm quy tắc này. | `GetElementById` trả về kết quả đầu tiên; cân nhắc sử dụng `QuerySelectorAll` nếu bạn cần xử lý các phần tử trùng lặp. | +| **Xung đột kiểu** | Các kiểu nội tuyến hiện có có thể bị ghi đè. | Thêm vào đối tượng `Style` thay vì đặt toàn bộ chuỗi `style`: `paragraph.Style.FontWeight = "bold"; paragraph.Style.FontStyle = "italic";` | +| **Hiển thị trong trình duyệt** | Một số trình duyệt bỏ qua `WebFontStyle` nếu phần tử đã có lớp CSS có độ đặc hiệu cao hơn. | Sử dụng `!important` qua `paragraph.Style.SetProperty("font-weight", "bold", "important");` nếu cần. | + +## Mẹo chuyên nghiệp cho các dự án thực tế + +- **Cache tài liệu** nếu bạn đang xử lý nhiều phần tử; tạo một `HTMLDocument` mới cho mỗi đoạn mã nhỏ có thể làm giảm hiệu năng. +- **Kết hợp các thay đổi kiểu** trong một giao dịch `Style` duy nhất để tránh nhiều lần tái tính DOM. +- **Tận dụng engine render của Aspose.Html** để xuất tài liệu cuối cùng dưới dạng PDF hoặc hình ảnh—rất hữu ích cho các công cụ báo cáo. + +## Xác nhận trực quan (Tùy chọn) + +Nếu bạn muốn xem kết quả trong trình duyệt, bạn có thể lưu chuỗi đã render vào tệp `.html`: + +```csharp +System.IO.File.WriteAllText("output.html", result); +``` + +Mở `output.html` và bạn sẽ thấy **Hello world** hiển thị in đậm + in nghiêng. + +![Ví dụ Tạo tài liệu HTML C# hiển thị đoạn văn in đậm nghiêng](/images/create-html-document-csharp.png "Tạo tài liệu HTML C# – kết quả render") + +*Văn bản thay thế: Tạo tài liệu HTML C# – kết quả render với văn bản in đậm nghiêng.* + +## Kết luận + +Chúng ta vừa **tạo một tài liệu HTML C#**, **lấy phần tử theo id**, **tìm phần tử theo id**, **thay đổi kiểu phần tử HTML**, và cuối cùng **thêm in đậm nghiêng**—tất cả chỉ với vài dòng code sử dụng Aspose.Html. Cách tiếp cận này đơn giản, hoạt động trong bất kỳ môi trường .NET nào, và mở rộng được cho các thao tác DOM lớn hơn. + +Sẵn sàng cho bước tiếp theo? Hãy thử thay thế `WebFontStyle` bằng các enum khác như `Underline` hoặc kết hợp nhiều kiểu thủ công. Hoặc thử tải một tệp HTML bên ngoài và áp dụng cùng một kỹ thuật cho hàng trăm phần tử. Không có giới hạn, và giờ bạn đã có nền tảng vững chắc để xây dựng. + +Chúc lập trình vui vẻ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/vietnamese/net/html-extensions-and-conversions/_index.md b/html/vietnamese/net/html-extensions-and-conversions/_index.md index 169c7624f..9ce74139c 100644 --- a/html/vietnamese/net/html-extensions-and-conversions/_index.md +++ b/html/vietnamese/net/html-extensions-and-conversions/_index.md @@ -63,6 +63,8 @@ Khám phá cách sử dụng Aspose.HTML cho .NET để thao tác và chuyển Tìm hiểu cách chuyển đổi HTML sang TIFF bằng Aspose.HTML cho .NET. Làm theo hướng dẫn từng bước của chúng tôi để tối ưu hóa nội dung web hiệu quả. ### [Chuyển đổi HTML sang XPS trong .NET với Aspose.HTML](./convert-html-to-xps/) 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. +### [Chuyển đổi HTML sang hình ảnh trong C# – Hướng dẫn đầy đủ](./convert-html-to-image-in-c-complete-guide/) +Hướng dẫn chi tiết cách chuyển đổi HTML sang hình ảnh trong C# bằng Aspose.HTML, bao gồm ví dụ mã và các tùy chọn cấu hình. ### [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/) @@ -73,6 +75,12 @@ Tạo PDF từ HTML trong .NET bằng C#. Hướng dẫn chi tiết từng bư 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 dưới dạng ZIP trong C# – Hướng dẫn đầy đủ với lưu trữ tùy chỉnh](./save-html-as-zip-in-c-complete-guide-with-custom-storage/) +Hướng dẫn chi tiết cách lưu HTML thành tệp ZIP trong C# với tùy chọn lưu trữ tùy chỉnh, bao gồm ví dụ mã và cấu hình. +### [Cách Nén HTML thành Zip với Aspose.HTML – Hướng dẫn đầy đủ](./how-to-zip-html-with-aspose-html-complete-guide/) +Hướng dẫn toàn diện cách nén HTML thành ZIP bằng Aspose.HTML, bao gồm ví dụ mã và các tùy chọn cấu hình. +### [Tạo PDF từ HTML với Aspose – Hướng dẫn từng bước C#](./create-pdf-from-html-with-aspose-step-by-step-c-guide/) +Hướng dẫn chi tiết từng bước để tạo PDF từ HTML trong .NET bằng C# và Aspose.HTML. ## Phần kết luận diff --git a/html/vietnamese/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md b/html/vietnamese/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md new file mode 100644 index 000000000..63d1d5115 --- /dev/null +++ b/html/vietnamese/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-03-21 +description: Chuyển đổi HTML sang hình ảnh bằng Aspose.HTML trong C#. Tìm hiểu cách + lưu HTML dưới dạng PNG, thiết lập kích thước hiển thị hình ảnh và ghi hình ảnh vào + tệp chỉ trong vài bước. +draft: false +keywords: +- convert html to image +- save html as png +- write image to file +- render webpage to png +- set image size rendering +language: vi +og_description: Chuyển đổi HTML sang hình ảnh nhanh chóng. Hướng dẫn này chỉ cách + lưu HTML dưới dạng PNG, thiết lập kích thước hiển thị của hình ảnh và ghi hình ảnh + vào tệp bằng Aspose.HTML. +og_title: Chuyển đổi HTML sang hình ảnh trong C# – Hướng dẫn từng bước +tags: +- Aspose.HTML +- C# +- Image Rendering +title: Chuyển đổi HTML sang hình ảnh trong C# – Hướng dẫn toàn diện +url: /vi/net/html-extensions-and-conversions/convert-html-to-image-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Chuyển đổi HTML thành Hình ảnh trong C# – Hướng dẫn đầy đủ + +Bạn đã bao giờ cần **chuyển đổi HTML thành hình ảnh** cho một ảnh thu nhỏ bảng điều khiển, bản xem trước email, hoặc báo cáo PDF chưa? Đó là một tình huống xuất hiện thường xuyên hơn bạn nghĩ, đặc biệt khi bạn phải làm việc với nội dung web động cần được nhúng ở nơi khác. + +Tin tốt là gì? Với Aspose.HTML, bạn có thể **chuyển đổi HTML thành hình ảnh** chỉ trong vài dòng code, và bạn sẽ học cách *lưu HTML dưới dạng PNG*, kiểm soát kích thước đầu ra, và *ghi hình ảnh vào tệp* mà không gặp khó khăn. + +Trong tutorial này, chúng ta sẽ đi qua mọi thứ bạn cần biết: từ việc tải một trang từ xa đến tinh chỉnh kích thước render, và cuối cùng lưu kết quả dưới dạng tệp PNG trên đĩa. Không cần công cụ bên ngoài, không cần các thủ thuật dòng lệnh rắc rối—chỉ cần code C# thuần túy mà bạn có thể đưa vào bất kỳ dự án .NET nào. + +## Những gì bạn sẽ học + +- Cách **render trang web thành PNG** bằng lớp `HTMLDocument` của Aspose.HTML. +- Các bước chính xác để **đặt kích thước hình ảnh khi render** sao cho đầu ra phù hợp với yêu cầu bố cục của bạn. +- Cách **ghi hình ảnh vào tệp** một cách an toàn, xử lý streams và đường dẫn tệp. +- Mẹo khắc phục các vấn đề thường gặp như thiếu phông chữ hoặc thời gian chờ mạng. + +### Yêu cầu trước + +- .NET 6.0 hoặc mới hơn (API cũng hoạt động với .NET Framework, nhưng .NET 6+ được khuyến nghị). +- Tham chiếu tới gói NuGet Aspose.HTML for .NET (`Aspose.Html`). +- Kiến thức cơ bản về C# và async/await (tùy chọn nhưng hữu ích). + +Nếu bạn đã có những thứ này, bạn đã sẵn sàng bắt đầu chuyển đổi HTML thành hình ảnh ngay lập tức. + +## Bước 1: Tải Trang Web – Nền tảng cho việc Chuyển đổi HTML thành Hình ảnh + +Trước khi bất kỳ quá trình render nào diễn ra, bạn cần một thể hiện `HTMLDocument` đại diện cho trang bạn muốn chụp. + +```csharp +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +// Load a remote URL into an HTMLDocument. +// This is the starting point for any convert html to image workflow. +HTMLDocument htmlDoc = new HTMLDocument("https://example.com"); +``` + +*Lý do quan trọng:* `HTMLDocument` phân tích HTML, giải quyết CSS và xây dựng DOM. Nếu tài liệu không tải được (ví dụ: lỗi mạng), quá trình render tiếp theo sẽ tạo ra một hình ảnh trống. Luôn kiểm tra URL có thể truy cập được trước khi tiếp tục. + +## Bước 2: Đặt Kích thước Hình ảnh Khi Render – Kiểm soát Chiều rộng, Chiều cao và Chất lượng + +Aspose.HTML cho phép bạn tinh chỉnh kích thước đầu ra bằng `ImageRenderingOptions`. Đây là nơi bạn **đặt kích thước hình ảnh khi render** để phù hợp với bố cục mục tiêu. + +```csharp +// Configure rendering options: width, height, and antialiasing. +// Adjust these values based on the size you need for your PNG. +ImageRenderingOptions renderingOptions = new ImageRenderingOptions +{ + Width = 1024, // Desired pixel width + Height = 768, // Desired pixel height + UseAntialiasing = true // Improves visual quality, especially for text +}; +``` + +*Mẹo chuyên nghiệp:* Nếu bạn bỏ qua `Width` và `Height`, Aspose.HTML sẽ sử dụng kích thước nội tại của trang, điều này có thể không đoán trước được đối với các thiết kế đáp ứng. Việc chỉ định kích thước rõ ràng đảm bảo đầu ra **lưu HTML dưới dạng PNG** của bạn trông chính xác như mong đợi. + +## Bước 3: Ghi Hình ảnh vào Tệp – Lưu Trữ PNG Đã Render + +Bây giờ tài liệu đã sẵn sàng và các tùy chọn render đã được thiết lập, bạn cuối cùng có thể **ghi hình ảnh vào tệp**. Sử dụng `FileStream` đảm bảo tệp được tạo một cách an toàn, ngay cả khi thư mục chưa tồn tại. + +```csharp +// Define where the PNG will be saved. +string outputFilePath = @"C:\Temp\page.png"; + +// Ensure the directory exists – otherwise you'll get an exception. +Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)!); + +using (var outputStream = File.Create(outputFilePath)) +{ + // This call renders the HTML document to the stream using the options above. + // It effectively performs the convert html to image operation. + htmlDoc.RenderToImage(outputStream, renderingOptions); +} +``` + +Sau khi khối này chạy, bạn sẽ thấy `page.png` ở vị trí bạn chỉ định. Bạn vừa **render trang web thành PNG** và ghi nó vào đĩa trong một thao tác đơn giản, trực quan. + +### Kết quả Mong đợi + +Mở `C:\Temp\page.png` bằng bất kỳ trình xem ảnh nào. Bạn sẽ thấy một bản sao chính xác của `https://example.com`, được render ở kích thước 1024 × 768 pixel với các cạnh mịn nhờ khử răng cưa. Nếu trang chứa nội dung động (ví dụ: các phần tử được tạo bằng JavaScript), chúng sẽ được chụp lại miễn là DOM đã được tải đầy đủ trước khi render. + +## Bước 4: Xử lý Các Trường hợp Đặc biệt – Phông chữ, Xác thực và Trang lớn + +Trong khi luồng cơ bản hoạt động với hầu hết các trang công cộng, các kịch bản thực tế thường gặp những tình huống bất ngờ: + +| Tình huống | Cách thực hiện | +|-----------|----------------| +| **Phông chữ tùy chỉnh không tải** | Nhúng các tệp phông chữ cục bộ và đặt `htmlDoc.Fonts.Add("path/to/font.ttf")`. | +| **Trang yêu cầu xác thực** | Sử dụng overload của `HTMLDocument` chấp nhận `HttpWebRequest` có cookie hoặc token. | +| **Trang rất dài** | Tăng `Height` hoặc bật `PageScaling` trong `ImageRenderingOptions` để tránh cắt bớt. | +| **Sự tăng đột biến bộ nhớ** | Render theo từng phần bằng cách sử dụng overload `RenderToImage` chấp nhận vùng `Rectangle`. | + +Việc giải quyết những chi tiết *ghi hình ảnh vào tệp* này giúp quy trình **chuyển đổi HTML thành hình ảnh** của bạn luôn ổn định trong môi trường sản xuất. + +## Bước 5: Ví dụ Hoàn chỉnh – Sẵn sàng Sao chép + +Dưới đây là toàn bộ chương trình, sẵn sàng biên dịch. Nó bao gồm tất cả các bước, xử lý lỗi và các chú thích cần thiết. + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering.Image; + +class HtmlToPngDemo +{ + static void Main() + { + // 1️⃣ Load the web page you want to convert. + string url = "https://example.com"; + HTMLDocument htmlDoc = new HTMLDocument(url); + + // 2️⃣ Configure image size rendering (width, height, antialiasing). + ImageRenderingOptions renderingOptions = new ImageRenderingOptions + { + Width = 1024, + Height = 768, + UseAntialiasing = true + }; + + // 3️⃣ Define the output path and ensure the folder exists. + string outputPath = @"C:\Temp\page.png"; + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // 4️⃣ Render the HTML document to a PNG and write image to file. + using (var outputStream = File.Create(outputPath)) + { + htmlDoc.RenderToImage(outputStream, renderingOptions); + } + + Console.WriteLine($"✅ Successfully saved PNG to: {outputPath}"); + } +} +``` + +Chạy chương trình này, và bạn sẽ thấy thông báo xác nhận trên console. Tệp PNG sẽ chính xác như khi bạn **render trang web thành PNG** thủ công trong trình duyệt và chụp ảnh màn hình—chỉ nhanh hơn và hoàn toàn tự động. + +## Câu hỏi Thường gặp + +**Q:** Tôi có thể chuyển đổi tệp HTML cục bộ thay vì URL không? +**A:** Chắc chắn. Chỉ cần thay thế URL bằng đường dẫn tệp: `new HTMLDocument(@"C:\myPage.html")`. + +**Q:** Tôi có cần giấy phép cho Aspose.HTML không? +**A:** Giấy phép đánh giá miễn phí hoạt động cho phát triển và thử nghiệm. Đối với môi trường sản xuất, mua giấy phép để loại bỏ watermark đánh giá. + +**Q:** Nếu trang sử dụng JavaScript để tải nội dung sau khi tải ban đầu thì sao? +**A:** Aspose.HTML thực thi JavaScript đồng bộ trong quá trình phân tích, nhưng các script chạy lâu có thể cần độ trễ thủ công. Bạn có thể sử dụng `HTMLDocument.WaitForReadyState` trước khi render. + +## Kết luận + +Bạn giờ đã có một giải pháp toàn diện, đầu‑cuối để **chuyển đổi HTML thành hình ảnh** trong C#. Bằng cách làm theo các bước trên, bạn có thể **lưu HTML dưới dạng PNG**, **đặt kích thước hình ảnh khi render** một cách chính xác, và tự tin **ghi hình ảnh vào tệp** trên bất kỳ môi trường Windows hoặc Linux nào. + +Từ các ảnh chụp màn hình đơn giản đến việc tạo báo cáo tự động, kỹ thuật này mở rộng linh hoạt. Tiếp theo, hãy thử nghiệm các định dạng đầu ra khác như JPEG hoặc BMP, hoặc tích hợp code vào một API ASP.NET Core trả về PNG trực tiếp cho người gọi. Các khả năng gần như vô hạn. + +Chúc lập trình vui vẻ, và hy vọng các hình ảnh render luôn đạt độ pixel‑perfect! + +{{< /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/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md b/html/vietnamese/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md new file mode 100644 index 000000000..946b9efbf --- /dev/null +++ b/html/vietnamese/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-03-21 +description: Tạo PDF từ HTML nhanh chóng bằng Aspose HTML. Học cách chuyển đổi HTML + sang PDF, render HTML thành PDF và cách sử dụng Aspose trong một hướng dẫn ngắn + gọn. +draft: false +keywords: +- create pdf from html +- render html to pdf +- convert html to pdf +- how to use aspose +- aspose html to pdf +language: vi +og_description: Tạo PDF từ HTML bằng Aspose trong C#. Hướng dẫn này chỉ cách render + HTML thành PDF, chuyển HTML sang PDF và cách sử dụng Aspose một cách hiệu quả. +og_title: Tạo PDF từ HTML – Hướng dẫn đầy đủ Aspose C# +tags: +- Aspose +- C# +- PDF generation +title: Tạo PDF từ HTML với Aspose – Hướng dẫn C# chi tiết từng bước +url: /vi/net/html-extensions-and-conversions/create-pdf-from-html-with-aspose-step-by-step-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo PDF từ HTML với Aspose – Hướng dẫn C# Từng Bước + +Bạn đã bao giờ **tạo PDF từ HTML** nhưng không chắc thư viện nào sẽ cho kết quả pixel‑perfect? Bạn không phải là người duy nhất. Nhiều lập trình viên gặp khó khăn khi chuyển một đoạn mã web thành tài liệu có thể in, chỉ để cuối cùng nhận được văn bản mờ hoặc bố cục bị phá vỡ. + +Tin tốt là Aspose HTML giúp toàn bộ quá trình trở nên dễ dàng. Trong hướng dẫn này, chúng ta sẽ đi qua đoạn mã chính xác cần **render HTML thành PDF**, tìm hiểu lý do mỗi thiết lập quan trọng, và chỉ cho bạn cách **chuyển đổi HTML sang PDF** mà không có bất kỳ mánh khóe nào. Khi kết thúc, bạn sẽ biết **cách sử dụng Aspose** để tạo PDF đáng tin cậy trong bất kỳ dự án .NET nào. + +## Các Điều Kiện Cần Thiết – Những Gì Bạn Cần Trước Khi Bắt Đầu + +- **.NET 6.0 trở lên** (ví dụ cũng chạy được trên .NET Framework 4.7+) +- **Visual Studio 2022** hoặc bất kỳ IDE nào hỗ trợ C# +- Gói NuGet **Aspose.HTML for .NET** (bản dùng thử miễn phí hoặc bản có giấy phép) +- Kiến thức cơ bản về cú pháp C# (không cần hiểu sâu về PDF) + +Nếu bạn đã có những thứ trên, bạn đã sẵn sàng. Nếu chưa, hãy tải SDK .NET mới nhất và cài đặt gói NuGet bằng: + +```bash +dotnet add package Aspose.HTML +``` + +Dòng lệnh duy nhất này sẽ kéo về mọi thứ bạn cần cho việc **aspose html to pdf** conversion. + +--- + +## Bước 1: Thiết Lập Dự Án Để Tạo PDF từ HTML + +Điều đầu tiên bạn làm là tạo một ứng dụng console mới (hoặc tích hợp mã vào dịch vụ hiện có). Đây là khung `Program.cs` tối thiểu: + +```csharp +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Rendering; +using Aspose.Html.Rendering.Text; // Note the correct namespace: Aspose.Html.Rendering.Text + +namespace HtmlToPdfDemo +{ + class Program + { + static void Main(string[] args) + { + // We'll fill this in in the next steps. + } + } +} +``` + +> **Mẹo chuyên nghiệp:** Nếu bạn thấy `Aspise.Html.Rendering.Text` trong các mẫu cũ, hãy thay bằng `Aspose.Html.Rendering.Text`. Lỗi đánh máy sẽ gây lỗi biên dịch. + +Việc sử dụng đúng namespace giúp trình biên dịch tìm thấy lớp **TextOptions** mà chúng ta sẽ cần sau này. + +## Bước 2: Xây Dựng Tài Liệu HTML (Render HTML to PDF) + +Bây giờ chúng ta tạo HTML nguồn. Aspose cho phép bạn truyền một chuỗi thô, một đường dẫn tệp, hoặc thậm chí một URL. Trong ví dụ này, chúng ta sẽ giữ đơn giản: + +```csharp +// Step 2: Create an HTML document with the desired markup +var htmlContent = "" + + "

Hello, Aspose!

This PDF was generated directly from HTML.

"; + +var htmlDocument = new HTMLDocument(htmlContent); +``` + +Tại sao lại truyền chuỗi? Điều này tránh việc I/O trên hệ thống tập tin, tăng tốc chuyển đổi, và đảm bảo HTML bạn thấy trong mã chính là HTML sẽ được render. Nếu bạn muốn tải từ tệp, chỉ cần thay đối số khởi tạo bằng URI của tệp. + +## Bước 3: Tinh Chỉnh Render Văn Bản (Convert HTML to PDF with Better Quality) + +Việc render văn bản thường quyết định PDF của bạn sẽ sắc nét hay mờ. Aspose cung cấp lớp `TextOptions` cho phép bạn bật sub‑pixel hinting—rất cần thiết cho đầu ra DPI cao. + +```csharp +// Step 3: Set up text rendering options (enable sub‑pixel hinting for sharper glyphs) +var textRenderOptions = new TextOptions +{ + UseHinting = true // Turns on hinting for smoother characters +}; +``` + +Bật `UseHinting` đặc biệt hữu ích khi HTML nguồn chứa phông chữ tùy chỉnh hoặc kích thước chữ nhỏ. Nếu không bật, bạn có thể thấy các cạnh răng cưa trong PDF cuối cùng. + +## Bước 4: Gắn Text Options vào Cấu Hình Render PDF (How to Use Aspose) + +Tiếp theo, chúng ta gắn các tùy chọn văn bản vào bộ render PDF. Đây là nơi **aspose html to pdf** thực sự tỏa sáng—mọi thứ từ kích thước trang đến nén đều có thể điều chỉnh. + +```csharp +// Step 4: Attach the text options to the PDF rendering configuration +var pdfRenderOptions = new PdfRenderingOptions +{ + TextOptions = textRenderOptions, + PageSetup = new PageSetup + { + Width = 595, // A4 width in points + Height = 842 // A4 height in points + } +}; +``` + +Bạn có thể bỏ qua `PageSetup` nếu không quan tâm tới kích thước A4 mặc định. Điều quan trọng là đối tượng `TextOptions` nằm trong `PdfRenderingOptions`, và đó là cách bạn chỉ cho Aspose *cách* render văn bản. + +## Bước 5: Render HTML và Lưu PDF (Convert HTML to PDF) + +Cuối cùng, chúng ta stream kết quả ra tệp. Sử dụng khối `using` đảm bảo handle tệp được đóng đúng cách, ngay cả khi có ngoại lệ xảy ra. + +```csharp +// Step 5: Open a file stream for the output PDF and render +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.pdf"); + +using (var outputStream = File.Create(outputPath)) +{ + htmlDocument.RenderToPdf(outputStream, pdfRenderOptions); +} + +Console.WriteLine($"PDF successfully created at: {outputPath}"); +``` + +Khi chạy chương trình, bạn sẽ thấy `output.pdf` nằm cạnh file thực thi. Mở nó lên, bạn sẽ thấy tiêu đề và đoạn văn bản sạch sẽ—đúng như đã định nghĩa trong chuỗi HTML. + +### Kết Quả Mong Đợi + +![create pdf from html example output](https://example.com/images/pdf-output.png "create pdf from html example output") + +*Ảnh chụp màn hình cho thấy PDF được tạo với tiêu đề “Hello, Aspose!” render sắc nét nhờ text hinting.* + +--- + +## Các Câu Hỏi Thường Gặp & Trường Hợp Đặc Biệt + +### 1. Nếu HTML của tôi tham chiếu tới tài nguyên bên ngoài (hình ảnh, CSS) thì sao? + +Aspose giải quyết các URL tương đối dựa trên URI cơ sở của tài liệu. Nếu bạn truyền một chuỗi thô, hãy đặt URI cơ sở thủ công: + +```csharp +var htmlDocument = new HTMLDocument(htmlContent, new Uri("file:///C:/MyProject/")); +``` + +Bây giờ bất kỳ `` nào sẽ được tìm kiếm tương đối với `C:/MyProject/`. + +### 2. Làm thế nào để nhúng phông chữ chưa được cài trên server? + +Thêm một khối ` + + +

Hello, world!

+

This HTML will be saved inside a ZIP archive.

+ +"; + +HTMLDocument document = new HTMLDocument(htmlContent); +``` + +### Bước 4: Cấu hình tùy chọn Lưu để dùng Lưu trữ Tùy chỉnh + +`HtmlSaveOptions` cho phép chúng ta chỉ định Aspose đóng gói mọi thứ vào một tệp ZIP. Thuộc tính `OutputStorage` (phiên bản legacy) nhận thể hiện `MyStorage` của chúng ta. + +```csharp +using Aspose.Html.Saving; + +// Set up save options – the default format is ZIP. +HtmlSaveOptions saveOptions = new HtmlSaveOptions +{ + // Attach our custom storage implementation. + OutputStorage = new MyStorage() +}; +``` + +> **Lưu ý:** Trong Aspose HTML 23.9+ thuộc tính này được đặt tên là `OutputStorage` nhưng đã bị đánh dấu lỗi thời. Thay thế hiện đại là `ZipOutputStorage`. Đoạn code dưới đây hoạt động với cả hai vì giao diện vẫn giống nhau. + +### Bước 5: Lưu tài liệu dưới dạng Archive ZIP + +Chọn thư mục đích (hoặc stream) và để Aspose thực hiện phần còn lại. + +```csharp +// Choose an output path – the library will create `output.zip`. +string outputPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + +// The Save method writes the main HTML file and all referenced resources +// into the ZIP using the streams supplied by MyStorage. +document.Save(outputPath, saveOptions); + +Console.WriteLine($"✅ HTML saved as ZIP at: {outputPath}"); +``` + +Khi chương trình kết thúc, bạn sẽ thấy `output.zip` chứa: + +* `index.html` – tài liệu chính. +* Các hình ảnh, tệp CSS hoặc script được nhúng (nếu HTML của bạn tham chiếu tới chúng). + +Bạn có thể mở ZIP bằng bất kỳ trình quản lý archive nào để kiểm tra cấu trúc. + +--- + +## Kiểm tra Kết quả (Tùy chọn) + +Nếu muốn kiểm tra archive một cách lập trình mà không giải nén ra đĩa: + +```csharp +using System.IO.Compression; + +// Open the ZIP in read‑only mode. +using var zip = ZipFile.OpenRead(outputPath); +foreach (var entry in zip.Entries) +{ + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); +} +``` + +Kết quả mẫu: + +``` +- index.html (452 bytes) +``` + +Nếu có hình ảnh hoặc CSS, chúng sẽ xuất hiện dưới dạng các entry bổ sung. Kiểm tra nhanh này xác nhận rằng **tạo html zip archive** đã hoạt động như mong đợi. + +--- + +## Câu hỏi Thường gặp & Các Trường hợp Cạnh + +| Câu hỏi | Trả lời | +|----------|--------| +| **Nếu tôi cần ghi ZIP trực tiếp vào stream phản hồi thì sao?** | Trả về `MemoryStream` nhận được từ `MyStorage` sau khi gọi `document.Save`. Ép nó thành `byte[]` và ghi vào `HttpResponse.Body`. | +| **HTML của tôi tham chiếu tới URL bên ngoài—các tài nguyên đó có được tải về không?** | Không. Aspose chỉ đóng gói các tài nguyên *được nhúng* (ví dụ `` hoặc tệp cục bộ). Đối với tài nguyên từ xa, bạn phải tải chúng về trước và chỉnh sửa markup. | +| **Thuộc tính `OutputStorage` đã bị lỗi thời—có nên bỏ qua không?** | Nó vẫn hoạt động, nhưng `ZipOutputStorage` mới cung cấp cùng API với tên khác. Thay `OutputStorage` bằng `ZipOutputStorage` nếu muốn biên dịch không cảnh báo. | +| **Có thể mã hoá ZIP không?** | Có. Sau khi lưu, mở tệp bằng `System.IO.Compression.ZipArchive` và đặt mật khẩu bằng các thư viện bên thứ ba như `SharpZipLib`. Aspose không cung cấp tính năng mã hoá. | + +--- + +## Ví dụ Hoàn chỉnh (Sao chép‑Dán) + +```csharp +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Html; +using Aspose.Html.Saving; + +class MyStorage : IOutputStorage +{ + public Stream GetOutputStream(string resourceName) => new MemoryStream(); +} + +class Program +{ + static void Main() + { + // 1️⃣ Prepare HTML content. + string html = @" + + + Demo +

Hello from ZIP!

+ "; + + // 2️⃣ Load document. + HTMLDocument doc = new HTMLDocument(html); + + // 3️⃣ Set up custom storage and save options. + HtmlSaveOptions options = new HtmlSaveOptions + { + OutputStorage = new MyStorage() // legacy property; works with newer versions too. + }; + + // 4️⃣ Define output path. + string zipPath = Path.Combine(Environment.CurrentDirectory, "output.zip"); + + // 5️⃣ Save as ZIP. + doc.Save(zipPath, options); + Console.WriteLine($"✅ Saved ZIP to {zipPath}"); + + // 6️⃣ (Optional) List contents. + using var zip = ZipFile.OpenRead(zipPath); + Console.WriteLine("Archive contains:"); + foreach (var entry in zip.Entries) + Console.WriteLine($"- {entry.FullName} ({entry.Length} bytes)"); + } +} +``` + +Chạy chương trình, mở `output.zip`, và bạn sẽ thấy một tệp `index.html` duy nhất hiển thị tiêu đề “Hello from ZIP!” khi mở trong trình duyệt. + +--- + +## Kết luận + +Bây giờ bạn đã biết **cách lưu HTML dưới dạng ZIP** trong C# bằng một lớp **lưu trữ tùy chỉnh**, cách **xuất HTML ra ZIP**, và cách **tạo một HTML zip archive** sẵn sàng phân phối. Mẫu này rất linh hoạt—thay `MemoryStream` bằng stream đám mây, thêm mã hoá, hoặc tích hợp vào Web API trả về ZIP theo yêu cầu. + +Sẵn sàng cho bước tiếp theo? Hãy thử đưa vào một trang web đầy đủ với hình ảnh và style, hoặc kết nối lưu trữ với Azure Blob Storage để bỏ qua hệ thống file cục bộ hoàn toàn. Khi kết hợp khả năng ZIP của Aspose.HTML với logic lưu trữ của bạn, khả năng là vô hạn. + +Chúc lập trình vui vẻ, và hy vọng các archive của bạn luôn gọn gàng! + +{{< /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