From 3e7f7e3bea6a5fe22f630608982e634d756ab50f Mon Sep 17 00:00:00 2001 From: agent-aspose-html-examples Date: Fri, 2 Oct 2026 23:28:04 +0500 Subject: [PATCH] =?UTF-8?q?feat(website-to-html):=20Add=2030=20and=20remov?= =?UTF-8?q?e=2018=20renamed=20Aspose.HTML=20.NET=20C#=20examples=20for=20W?= =?UTF-8?q?ebsite=20To=20Html=20=E2=80=94=20Aspose.HTML=20for=20.NET=2026.?= =?UTF-8?q?9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...te-validation-callbacks-ensure-security.cs | 35 +++ ...te_validation_callbacks_ensure_security.cs | 44 ---- ...ion-to-override-default-website-styling.cs | 54 ++++ ...onverted-content-consistent-page-layout.cs | 57 ++++ ...ion_to_override_default_website_styling.cs | 57 ---- ..._template_wrap_converted_content_layout.cs | 67 ----- ...te-firewalls-securely-during-conversion.cs | 29 +++ ...storing-each-result-separate-html-files.cs | 32 +++ ...sly-generate-pdf-snapshots-for-archival.cs | 42 +++ ...storing_each_result_separate_html_files.cs | 112 -------- ...sly_generate_pdf_snapshots_for_archival.cs | 32 --- ...links-during-website-to-html-conversion.cs | 86 +++++++ ...ut-reduce-file-size-faster-transmission.cs | 37 +++ ...ite-capture-dynamic-content-html-output.cs | 39 +++ ...-regular-expression-filters-processing.cs} | 31 ++- ...ongside-html-output-map-converted-pages.cs | 54 ++++ ...essed-url-output-path-conversion-status.cs | 78 ++++++ ...essed_url_output_path_conversion_status.cs | 144 ----------- ...ing-website-resources-during-conversion.cs | 57 ++++ ...ing_website_resources_during_conversion.cs | 108 -------- ...4-encoded-data-uris-generated-html-file.cs | 66 +++++ ...s-comments-in-generated-html-debugging.cs} | 23 +- ...ication-for-on-demand-website-rendering.cs | 34 +++ ...ication_for_on_demand_website_rendering.cs | 76 ------ ...ert-single-html-file-embedded-resources.cs | 31 +++ ...s-file-troubleshooting-batch-operations.cs | 93 +++++++ ...o_file_troubleshooting_batch_operations.cs | 243 ------------------ ...ngside-converted-html-interactive-pages.cs | 38 +++ ...ibutes-converting-website-pages-to-html.cs | 42 +++ ...ry-preserving-original-folder-structure.cs | 59 +++++ ...ry_preserving_original_folder_structure.cs | 82 ------ ...nerated-html-files-ensure-compatibility.cs | 30 +++ ...th-linked-pages-converting-website-html.cs | 26 ++ ...l-outputs-to-manage-storage-constraints.cs | 51 ++++ ...s-prevent-excessively-long-conversions.cs} | 24 +- ...nerated_html_files_ensure_compatibility.cs | 44 ---- ...l_outputs_to_manage_storage_constraints.cs | 53 ---- ...ed-on-source-url-host-and-path-segments.cs | 48 ++++ ...icular-browser-during-website-retrieval.cs | 65 +++++ ...r-during-large-scale-website-conversion.cs | 51 ++++ ...t_server_large_scale_website_conversion.cs | 67 ----- ...nverting-multiple-websites-concurrently.cs | 64 +++++ ...nverting_multiple_websites_concurrently.cs | 198 -------------- ...w3c-standards-report-compliance-issues.cs} | 20 +- 44 files changed, 1333 insertions(+), 1390 deletions(-) create mode 100644 website-to-html/allow-conversion-https-websites-custom-ssl-certificate-validation-callbacks-ensure-security.cs delete mode 100644 website-to-html/allow_conversion_https_websites_custom_ssl_certificate_validation_callbacks_ensure_security.cs create mode 100644 website-to-html/apply-custom-css-stylesheet-during-conversion-to-override-default-website-styling.cs create mode 100644 website-to-html/apply-custom-html-template-wrap-converted-content-consistent-page-layout.cs delete mode 100644 website-to-html/apply_custom_css_stylesheet_during_conversion_to_override_default_website_styling.cs delete mode 100644 website-to-html/apply_custom_html_template_wrap_converted_content_layout.cs create mode 100644 website-to-html/configure-proxy-settings-access-websites-behind-corporate-firewalls-securely-during-conversion.cs create mode 100644 website-to-html/convert-multiple-website-urls-batch-mode-storing-each-result-separate-html-files.cs create mode 100644 website-to-html/convert-website-pages-to-html-simultaneously-generate-pdf-snapshots-for-archival.cs delete mode 100644 website-to-html/convert_multiple_website_urls_batch_mode_storing_each_result_separate_html_files.cs delete mode 100644 website-to-html/convert_website_pages_to_html_simultaneously_generate_pdf_snapshots_for_archival.cs create mode 100644 website-to-html/enable-automatic-detection-and-correction-of-broken-links-during-website-to-html-conversion.cs create mode 100644 website-to-html/enable-compression-html-output-reduce-file-size-faster-transmission.cs create mode 100644 website-to-html/enable-javascript-execution-loading-site-capture-dynamic-content-html-output.cs rename website-to-html/{exclude_specific_url_patterns_conversion_regular_expression_filters_processing.cs => exclude-specific-url-patterns-from-conversion-regular-expression-filters-processing.cs} (51%) create mode 100644 website-to-html/generate-sitemap-xml-file-alongside-html-output-map-converted-pages.cs create mode 100644 website-to-html/generate-summary-report-processed-url-output-path-conversion-status.cs delete mode 100644 website-to-html/generate_summary_report_processed_url_output_path_conversion_status.cs create mode 100644 website-to-html/implement-retry-logic-transient-network-failures-fetching-website-resources-during-conversion.cs delete mode 100644 website-to-html/implement_retry_logic_for_transient_network_failures_when_fetching_website_resources_during_conversion.cs create mode 100644 website-to-html/include-external-images-base64-encoded-data-uris-generated-html-file.cs rename website-to-html/{include_http_response_headers_as_comments_in_generated_html_for_debugging.cs => include-http-response-headers-comments-in-generated-html-debugging.cs} (69%) create mode 100644 website-to-html/integrate-conversion-library-aspnet-mvc-application-for-on-demand-website-rendering.cs delete mode 100644 website-to-html/integrate_conversion_library_into_aspnet_mvc_application_for_on_demand_website_rendering.cs create mode 100644 website-to-html/load-website-url-convert-single-html-file-embedded-resources.cs create mode 100644 website-to-html/log-detailed-conversion-progress-errors-file-troubleshooting-batch-operations.cs delete mode 100644 website-to-html/log_detailed_conversion_progress_and_errors_to_file_troubleshooting_batch_operations.cs create mode 100644 website-to-html/option-retain-original-javascript-files-alongside-converted-html-interactive-pages.cs create mode 100644 website-to-html/preserve-original-meta-tags-seo-attributes-converting-website-pages-to-html.cs create mode 100644 website-to-html/save-converted-website-html-to-specified-output-directory-preserving-original-folder-structure.cs delete mode 100644 website-to-html/save_converted_website_html_to_specified_output_directory_preserving_original_folder_structure.cs create mode 100644 website-to-html/set-character-encoding-utf8-all-generated-html-files-ensure-compatibility.cs create mode 100644 website-to-html/set-maximum-crawl-depth-linked-pages-converting-website-html.cs create mode 100644 website-to-html/set-maximum-file-size-limit-for-individual-html-outputs-to-manage-storage-constraints.cs rename website-to-html/{set_timeout_limit_for_loading_website_resources_to_prevent_excessively_long_conversions.cs => set-timeout-limit-loading-website-resources-prevent-excessively-long-conversions.cs} (50%) delete mode 100644 website-to-html/set_character_encoding_utf8_all_generated_html_files_ensure_compatibility.cs delete mode 100644 website-to-html/set_maximum_file_size_limit_for_individual_html_outputs_to_manage_storage_constraints.cs create mode 100644 website-to-html/specify-output-file-naming-conventions-based-on-source-url-host-and-path-segments.cs create mode 100644 website-to-html/specify-user-agent-string-to-mimic-particular-browser-during-website-retrieval.cs create mode 100644 website-to-html/throttle-network-requests-avoid-overwhelming-target-server-during-large-scale-website-conversion.cs delete mode 100644 website-to-html/throttle_network_requests_avoid_overwhelming_target_server_large_scale_website_conversion.cs create mode 100644 website-to-html/use-asynchronous-loading-improve-performance-converting-multiple-websites-concurrently.cs delete mode 100644 website-to-html/use_asynchronous_loading_improve_performance_converting_multiple_websites_concurrently.cs rename website-to-html/{validate_generated_html_against_w3c_standards_and_report_compliance_issues.cs => validate-generated-html-against-w3c-standards-report-compliance-issues.cs} (71%) diff --git a/website-to-html/allow-conversion-https-websites-custom-ssl-certificate-validation-callbacks-ensure-security.cs b/website-to-html/allow-conversion-https-websites-custom-ssl-certificate-validation-callbacks-ensure-security.cs new file mode 100644 index 0000000..abe4833 --- /dev/null +++ b/website-to-html/allow-conversion-https-websites-custom-ssl-certificate-validation-callbacks-ensure-security.cs @@ -0,0 +1,35 @@ +// Allow conversion of HTTPS websites with custom SSL certificate validation callbacks to ensure security. + +using System; +using System.Net; +using System.Security.Cryptography.X509Certificates; + +class Program +{ + static void Main() + { + try + { + // Custom SSL certificate validation: accept only if there are no SSL errors. + ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => + { + return sslPolicyErrors == System.Net.Security.SslPolicyErrors.None; + }; + + string url = "https://example.com"; + string outputPath = "output.pdf"; + + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) + { + Aspose.Html.Saving.PdfSaveOptions options = new Aspose.Html.Saving.PdfSaveOptions(); + Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/allow_conversion_https_websites_custom_ssl_certificate_validation_callbacks_ensure_security.cs b/website-to-html/allow_conversion_https_websites_custom_ssl_certificate_validation_callbacks_ensure_security.cs deleted file mode 100644 index 20be0cd..0000000 --- a/website-to-html/allow_conversion_https_websites_custom_ssl_certificate_validation_callbacks_ensure_security.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Allow conversion of HTTPS websites with custom SSL certificate validation callbacks to ensure security. - -using System; -using System.IO; - -class Program -{ - static void Main() - { - try - { - // Define input HTML file path and output PDF file path - string url = "sample.html"; - string outputPath = "output.pdf"; - - // Create a minimal HTML file if it does not exist - if (!File.Exists(url)) - { - string htmlContent = "Sample

Hello, Aspose.HTML!

"; - File.WriteAllText(url, htmlContent); - } - - // Initialize Aspose.HTML configuration - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - - // Load the HTML document - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) - { - // Set PDF save options (default options are sufficient for this example) - Aspose.Html.Saving.PdfSaveOptions options = new Aspose.Html.Saving.PdfSaveOptions(); - - // Convert HTML to PDF and save to the specified path - Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); - } - - Console.WriteLine($"Conversion completed successfully. PDF saved to '{Path.GetFullPath(outputPath)}'."); - } - catch (Exception ex) - { - Console.WriteLine("An error occurred during conversion:"); - Console.WriteLine(ex.Message); - } - } -} \ No newline at end of file diff --git a/website-to-html/apply-custom-css-stylesheet-during-conversion-to-override-default-website-styling.cs b/website-to-html/apply-custom-css-stylesheet-during-conversion-to-override-default-website-styling.cs new file mode 100644 index 0000000..ae5d238 --- /dev/null +++ b/website-to-html/apply-custom-css-stylesheet-during-conversion-to-override-default-website-styling.cs @@ -0,0 +1,54 @@ +// Apply a custom CSS stylesheet during conversion to override the default website styling. + +using System; +using System.IO; + +class Program +{ + static void Main() + { + try + { + // Define file paths + string inputHtmlPath = "sample.html"; + string cssPath = "custom.css"; + string outputPdfPath = "output.pdf"; + + // Create sample HTML file + if (!File.Exists(inputHtmlPath)) + { + File.WriteAllText(inputHtmlPath, "

Hello World

"); + } + + // Create custom CSS file + if (!File.Exists(cssPath)) + { + File.WriteAllText(cssPath, "h1 { color: red; }"); + } + + // Read CSS content + string cssContent = File.ReadAllText(cssPath); + + // Configure Aspose.HTML with custom stylesheet + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + Aspose.Html.Services.IUserAgentService userAgent = (Aspose.Html.Services.IUserAgentService)configuration.GetService(typeof(Aspose.Html.Services.IUserAgentService)); + userAgent.UserStyleSheet = cssContent; + + // Set PDF save options + Aspose.Html.Saving.PdfSaveOptions options = new Aspose.Html.Saving.PdfSaveOptions(); + + // Convert HTML to PDF applying the custom CSS + Aspose.Html.Converters.Converter.ConvertHTML( + new Aspose.Html.Url(inputHtmlPath), + configuration, + options, + outputPdfPath); + + Console.WriteLine("Conversion completed successfully. Output saved to: " + outputPdfPath); + } + catch (Exception ex) + { + Console.WriteLine("An error occurred: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/apply-custom-html-template-wrap-converted-content-consistent-page-layout.cs b/website-to-html/apply-custom-html-template-wrap-converted-content-consistent-page-layout.cs new file mode 100644 index 0000000..19b2b51 --- /dev/null +++ b/website-to-html/apply-custom-html-template-wrap-converted-content-consistent-page-layout.cs @@ -0,0 +1,57 @@ +// Apply a custom HTML template to wrap converted content for a consistent page layout. + +using System; +using System.IO; + +class Program +{ + static void Main() + { + try + { + // Define file paths + string sourcePath = "source.html"; + string templateDataPath = "template.html"; + string resultPath = "result.html"; + + // Create sample source HTML if it does not exist + if (!File.Exists(sourcePath)) + { + File.WriteAllText(sourcePath, "

Hello, World!

"); + } + + // Create sample template HTML if it does not exist + if (!File.Exists(templateDataPath)) + { + // The template should contain a placeholder where the source content will be inserted. + // Using {{content}} as a placeholder is typical for Aspose HTML templates. + File.WriteAllText(templateDataPath, + "Template Page
{{content}}
"); + } + + // Load the source document + using Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(sourcePath, new Aspose.Html.Configuration()); + + // Prepare template data + Aspose.Html.Converters.TemplateData templateData = new Aspose.Html.Converters.TemplateData(templateDataPath); + + // Load template options + Aspose.Html.Loading.TemplateLoadOptions options = new Aspose.Html.Loading.TemplateLoadOptions(); + + // Convert using the template + Aspose.Html.HTMLDocument resultDocument = Aspose.Html.Converters.Converter.ConvertTemplate(document, templateData, options); + + // Save the resulting document + resultDocument.Save(resultPath); + + // Dispose the result document + resultDocument.Dispose(); + + Console.WriteLine($"Template conversion completed successfully. Output saved to '{resultPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/website-to-html/apply_custom_css_stylesheet_during_conversion_to_override_default_website_styling.cs b/website-to-html/apply_custom_css_stylesheet_during_conversion_to_override_default_website_styling.cs deleted file mode 100644 index 1368fb0..0000000 --- a/website-to-html/apply_custom_css_stylesheet_during_conversion_to_override_default_website_styling.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Apply a custom CSS stylesheet during conversion to override the default website styling. - -using System; -using System.IO; - -class Program -{ - static void Main() - { - try - { - // Prepare input EPUB file (minimal placeholder if not present) - string inputPath = "sample.epub"; - if (!File.Exists(inputPath)) - { - // Create an empty file as a placeholder; conversion will fail gracefully if invalid - File.WriteAllBytes(inputPath, new byte[0]); - } - - // Prepare a simple CSS file for the user style sheet - string cssPath = "style.css"; - if (!File.Exists(cssPath)) - { - File.WriteAllText(cssPath, "body { font-family: Arial; }"); - } - - // Open the EPUB file as a stream - Stream stream = File.OpenRead(inputPath); - - // Create Aspose.Html configuration - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - - // Get the user agent service and set a custom style sheet - Aspose.Html.Services.IUserAgentService userAgent = - (Aspose.Html.Services.IUserAgentService)configuration.GetService(typeof(Aspose.Html.Services.IUserAgentService)); - - string cssContent = File.ReadAllText(cssPath); - userAgent.UserStyleSheet = cssContent; - - // Set XPS save options (default options are sufficient for this example) - Aspose.Html.Saving.XpsSaveOptions options = new Aspose.Html.Saving.XpsSaveOptions(); - - // Define output path - string outputPath = "output.xps"; - - // Perform the conversion - Aspose.Html.Converters.Converter.ConvertEPUB(stream, configuration, options, outputPath); - - Console.WriteLine("Conversion completed successfully. Output saved to: " + outputPath); - } - catch (Exception ex) - { - Console.WriteLine("An error occurred during conversion:"); - Console.WriteLine(ex.Message); - } - } -} \ No newline at end of file diff --git a/website-to-html/apply_custom_html_template_wrap_converted_content_layout.cs b/website-to-html/apply_custom_html_template_wrap_converted_content_layout.cs deleted file mode 100644 index b00c8b4..0000000 --- a/website-to-html/apply_custom_html_template_wrap_converted_content_layout.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Apply a custom HTML template to wrap converted content for a consistent page layout. - -using System; -using System.IO; - -class Program -{ - static void Main() - { - try - { - // Prepare sample template file - string sourcePath = "template.html"; - if (!File.Exists(sourcePath)) - { - File.WriteAllText(sourcePath, "

{{title}}

"); - } - - // Prepare sample template data file (JSON) - string templateDataPath = "data.json"; - if (!File.Exists(templateDataPath)) - { - File.WriteAllText(templateDataPath, "{\"title\":\"Hello World\"}"); - } - - // Load template data - Aspose.Html.Converters.TemplateData templateData = new Aspose.Html.Converters.TemplateData(templateDataPath); - - // Load the HTML document (template) - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(sourcePath, new Aspose.Html.Configuration()); - - // Load options for template processing - Aspose.Html.Loading.TemplateLoadOptions options = new Aspose.Html.Loading.TemplateLoadOptions(); - - // Convert the template with data - Aspose.Html.HTMLDocument resultDocument = Aspose.Html.Converters.Converter.ConvertTemplate(document, templateData, options); - - // Save the resulting HTML - string resultPath = "result.html"; - resultDocument.Save(resultPath); - Console.WriteLine($"Template conversion completed. Output saved to '{resultPath}'."); - - // ----------------------------------------------------------------- - // Additional example: convert raw HTML string to a file using template data - // ----------------------------------------------------------------- - string htmlContent = "

{{message}}

"; - string outputPath = "output.html"; - - // Create a document from the HTML string - Aspose.Html.HTMLDocument docFromString = new Aspose.Html.HTMLDocument(htmlContent, ""); - - // Create template data directly from a JSON string - Aspose.Html.Converters.TemplateData dataFromString = new Aspose.Html.Converters.TemplateData("{\"message\":\"This is a test.\"}"); - - // Convert the document with the inline template data - Aspose.Html.HTMLDocument convertedDoc = Aspose.Html.Converters.Converter.ConvertTemplate(docFromString, dataFromString, new Aspose.Html.Loading.TemplateLoadOptions()); - - // Save the converted document - convertedDoc.Save(outputPath); - Console.WriteLine($"HTML string conversion completed. Output saved to '{outputPath}'."); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/website-to-html/configure-proxy-settings-access-websites-behind-corporate-firewalls-securely-during-conversion.cs b/website-to-html/configure-proxy-settings-access-websites-behind-corporate-firewalls-securely-during-conversion.cs new file mode 100644 index 0000000..a66d229 --- /dev/null +++ b/website-to-html/configure-proxy-settings-access-websites-behind-corporate-firewalls-securely-during-conversion.cs @@ -0,0 +1,29 @@ +// Configure proxy settings to access websites behind corporate firewalls securely during conversion. + +using System; + +class Program +{ + static void Main() + { + try + { + string url = "https://www.example.com"; + string outputPath = "example.pdf"; + + var config = new Aspose.Html.Configuration(); + + using (var document = new Aspose.Html.HTMLDocument(url, config)) + { + var pdfOptions = new Aspose.Html.Saving.PdfSaveOptions(); + Aspose.Html.Converters.Converter.ConvertHTML(document, pdfOptions, outputPath); + } + + Console.WriteLine("Conversion completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/convert-multiple-website-urls-batch-mode-storing-each-result-separate-html-files.cs b/website-to-html/convert-multiple-website-urls-batch-mode-storing-each-result-separate-html-files.cs new file mode 100644 index 0000000..437fc0d --- /dev/null +++ b/website-to-html/convert-multiple-website-urls-batch-mode-storing-each-result-separate-html-files.cs @@ -0,0 +1,32 @@ +// Convert multiple website URLs in batch mode, storing each result in separate HTML files. + +using System; + +class Program +{ + static void Main() + { + try + { + string outputDir = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "output"); + System.IO.Directory.CreateDirectory(outputDir); + + string[] urls = new string[] { "https://example.com", "https://example.org" }; + + for (int i = 0; i < urls.Length; i++) + { + using (var document = new Aspose.Html.HTMLDocument(urls[i])) + { + string outputPath = System.IO.Path.Combine(outputDir, $"page_{i + 1}.html"); + document.Save(outputPath); + } + } + + System.Console.WriteLine("Conversion completed."); + } + catch (System.Exception ex) + { + System.Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/convert-website-pages-to-html-simultaneously-generate-pdf-snapshots-for-archival.cs b/website-to-html/convert-website-pages-to-html-simultaneously-generate-pdf-snapshots-for-archival.cs new file mode 100644 index 0000000..99b7142 --- /dev/null +++ b/website-to-html/convert-website-pages-to-html-simultaneously-generate-pdf-snapshots-for-archival.cs @@ -0,0 +1,42 @@ +// Convert website pages to HTML and simultaneously generate PDF snapshots for archival purposes. + +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Converters; +using Aspose.Html.Saving; + +class Program +{ + static void Main(string[] args) + { + try + { + // Input URL of the website page + string url = "https://example.com"; + + // Output file paths + string htmlOutputPath = "example.html"; + string pdfOutputPath = "example.pdf"; + + // Load the web page into an HTMLDocument + HTMLDocument document = new HTMLDocument(url); + + // Save the HTML content to a file + document.Save(htmlOutputPath); + + // Prepare PDF conversion options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Convert the HTMLDocument to PDF and save + Aspose.Html.Converters.Converter.ConvertHTML(document, pdfOptions, pdfOutputPath); + + Console.WriteLine("HTML saved to: " + Path.GetFullPath(htmlOutputPath)); + Console.WriteLine("PDF snapshot saved to: " + Path.GetFullPath(pdfOutputPath)); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/convert_multiple_website_urls_batch_mode_storing_each_result_separate_html_files.cs b/website-to-html/convert_multiple_website_urls_batch_mode_storing_each_result_separate_html_files.cs deleted file mode 100644 index 73a7f7d..0000000 --- a/website-to-html/convert_multiple_website_urls_batch_mode_storing_each_result_separate_html_files.cs +++ /dev/null @@ -1,112 +0,0 @@ -// Convert multiple website URLs in batch mode, storing each result in separate HTML files. - -using System; -using System.IO; -using System.Collections.Generic; -using Aspose.Html; -using Aspose.Html.Net; -using Aspose.Html.Services; -using Aspose.Html.Saving; -using Aspose.Html.Rendering.Image; - -class Program -{ - static void Main() - { - try - { - // Prepare output directory - string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output"); - Directory.CreateDirectory(outputDir); - - // Prepare input directory and sample files - string inputDir = Path.Combine(Directory.GetCurrentDirectory(), "input"); - Directory.CreateDirectory(inputDir); - - string sample1Path = Path.Combine(inputDir, "sample1.html"); - string sample2Path = Path.Combine(inputDir, "sample2.html"); - - if (!File.Exists(sample1Path)) - { - File.WriteAllText(sample1Path, "

Sample 1

"); - } - if (!File.Exists(sample2Path)) - { - File.WriteAllText(sample2Path, "

Sample 2

"); - } - - // Input files - string[] inputs = new string[] { sample1Path, sample2Path }; - - // Convert each HTML file to JPEG with specific resolution - for (int i = 0; i < inputs.Length; i++) - { - string inputPath = inputs[i]; - using (var document = new Aspose.Html.HTMLDocument(inputPath, Directory.GetCurrentDirectory())) - { - var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Jpeg); - options.HorizontalResolution = 300; - options.VerticalResolution = 300; - - string outputPath = Path.Combine(outputDir, Path.GetFileNameWithoutExtension(inputPath) + ".jpg"); - Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); - } - } - - // Convert all HTML files in the input folder to JPEG - foreach (string htmlPath in Directory.GetFiles(inputDir, "*.html")) - { - using (var document = new Aspose.Html.HTMLDocument(htmlPath)) - { - var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Jpeg); - string outputPath = Path.Combine(outputDir, Path.GetFileNameWithoutExtension(htmlPath) + "_all.jpg"); - Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); - } - } - - // Create a new document, add a DIV element, and convert to JPEG - using (var document = new Aspose.Html.HTMLDocument(inputs[0], Directory.GetCurrentDirectory())) - { - Aspose.Html.HTMLElement div = (Aspose.Html.HTMLElement)document.CreateElement("div"); - div.SetAttribute("style", "color:red; font-size:24px;"); - div.TextContent = "Hello Aspose!"; - document.Body.AppendChild(div); - - var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Jpeg); - string outputPath = Path.Combine(outputDir, "document_with_div.jpg"); - Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); - } - - // Convert each HTML file to PDF with network logging - foreach (string htmlPath in Directory.GetFiles(inputDir, "*.html")) - { - var configuration = new Aspose.Html.Configuration(); - var network = configuration.GetService(); - network.MessageHandlers.Add(new LogHandler()); - - using (var document = new Aspose.Html.HTMLDocument(htmlPath, configuration)) - { - string pdfPath = Path.ChangeExtension(htmlPath, ".pdf"); - var pdfOptions = new Aspose.Html.Saving.PdfSaveOptions(); - Aspose.Html.Converters.Converter.ConvertHTML(document, pdfOptions, pdfPath); - } - } - - Console.WriteLine("Processing completed successfully."); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} - -// Custom network message handler for logging -class LogHandler : Aspose.Html.Net.MessageHandler -{ - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - Next(context); - Console.WriteLine($"{context.Request.RequestUri} | {context.Response.StatusCode}"); - } -} \ No newline at end of file diff --git a/website-to-html/convert_website_pages_to_html_simultaneously_generate_pdf_snapshots_for_archival.cs b/website-to-html/convert_website_pages_to_html_simultaneously_generate_pdf_snapshots_for_archival.cs deleted file mode 100644 index 91ce786..0000000 --- a/website-to-html/convert_website_pages_to_html_simultaneously_generate_pdf_snapshots_for_archival.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Convert website pages to HTML and simultaneously generate PDF snapshots for archival purposes. - -using System; -using System.IO; - -class Program -{ - static void Main() - { - try - { - string inputPath = "sample.html"; - string outputPath = "sample.pdf"; - - if (!File.Exists(inputPath)) - { - File.WriteAllText(inputPath, "

Hello Aspose.HTML

"); - } - - var document = new Aspose.Html.HTMLDocument(inputPath); - var options = new Aspose.Html.Saving.PdfSaveOptions(); - - Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); - - Console.WriteLine($"Conversion succeeded. PDF saved to: {Path.GetFullPath(outputPath)}"); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/website-to-html/enable-automatic-detection-and-correction-of-broken-links-during-website-to-html-conversion.cs b/website-to-html/enable-automatic-detection-and-correction-of-broken-links-during-website-to-html-conversion.cs new file mode 100644 index 0000000..5e919b5 --- /dev/null +++ b/website-to-html/enable-automatic-detection-and-correction-of-broken-links-during-website-to-html-conversion.cs @@ -0,0 +1,86 @@ +// Enable automatic detection and correction of broken links during website‑to‑HTML conversion. + +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; +using Aspose.Html; +using Aspose.Html.Dom; +using Aspose.Html.Saving; + +class Program +{ + static void Main() + { + try + { + // Source website URL and output HTML file path + string sourceUrl = "https://example.com"; + string outputPath = "converted.html"; + + // Load the website into an HTMLDocument + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(sourceUrl); + + // List to store detected broken links + List brokenLinks = new List(); + + // HttpClient for link validation + using (HttpClient httpClient = new HttpClient()) + { + foreach (Aspose.Html.Dom.Element linkElement in document.Links) + { + string href = linkElement.GetAttribute("href"); + if (string.IsNullOrEmpty(href)) + continue; + + // Resolve relative URLs against the document's base URI + Uri resolvedUri; + try + { + resolvedUri = new Uri(new Uri(document.BaseURI), href); + } + catch + { + brokenLinks.Add(href); + linkElement.SetAttribute("href", "#"); + continue; + } + + // Perform a HEAD request to check the link status + HttpResponseMessage response; + try + { + HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, resolvedUri); + response = httpClient.SendAsync(request).Result; + } + catch + { + brokenLinks.Add(resolvedUri.ToString()); + linkElement.SetAttribute("href", "#"); + continue; + } + + if ((int)response.StatusCode >= 400) + { + brokenLinks.Add(resolvedUri.ToString()); + linkElement.SetAttribute("href", "#"); + } + } + } + + // Save the corrected HTML document + document.Save(outputPath, new Aspose.Html.Saving.HTMLSaveOptions()); + + // Output summary + Console.WriteLine($"Conversion completed. Fixed {brokenLinks.Count} broken link(s)."); + foreach (string link in brokenLinks) + { + Console.WriteLine(link); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/enable-compression-html-output-reduce-file-size-faster-transmission.cs b/website-to-html/enable-compression-html-output-reduce-file-size-faster-transmission.cs new file mode 100644 index 0000000..8f13242 --- /dev/null +++ b/website-to-html/enable-compression-html-output-reduce-file-size-faster-transmission.cs @@ -0,0 +1,37 @@ +// Enable compression of the HTML output to reduce file size for faster transmission. + +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +class Program +{ + static void Main() + { + try + { + string inputPath = Path.Combine(Path.GetTempPath(), "sample.html"); + string outputPath = Path.Combine(Path.GetTempPath(), "sample_compressed.html"); + + // Create a minimal HTML file. + File.WriteAllText(inputPath, "Sample

Hello, Aspose.HTML!

"); + + // Load the HTML document from the file. + HTMLDocument document = new HTMLDocument(inputPath); + + // Set up HTML save options (compression can be set if supported). + HTMLSaveOptions options = new HTMLSaveOptions(); + // Example: options.Compression = Aspose.Html.Saving.Compression.GZip; // Uncomment if the property exists. + + // Save the document with the specified options. + document.Save(outputPath, options); + + Console.WriteLine("HTML saved to: " + outputPath); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/enable-javascript-execution-loading-site-capture-dynamic-content-html-output.cs b/website-to-html/enable-javascript-execution-loading-site-capture-dynamic-content-html-output.cs new file mode 100644 index 0000000..b59bd3e --- /dev/null +++ b/website-to-html/enable-javascript-execution-loading-site-capture-dynamic-content-html-output.cs @@ -0,0 +1,39 @@ +// Enable JavaScript execution while loading the site to capture dynamic content in the HTML output. + +using System; +using System.Threading; + +class Program +{ + static void Main() + { + try + { + string url = "https://example.com"; + + using (System.Threading.AutoResetEvent resetEvent = new System.Threading.AutoResetEvent(false)) + { + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument()) + { + string htmlResult = string.Empty; + document.OnReadyStateChange += (sender, e) => + { + if (document.ReadyState == "complete") + { + htmlResult = document.DocumentElement != null ? document.DocumentElement.TextContent : string.Empty; + resetEvent.Set(); + } + }; + + document.Navigate(url); + resetEvent.WaitOne(); + System.Console.WriteLine(htmlResult); + } + } + } + catch (Exception ex) + { + System.Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/exclude_specific_url_patterns_conversion_regular_expression_filters_processing.cs b/website-to-html/exclude-specific-url-patterns-from-conversion-regular-expression-filters-processing.cs similarity index 51% rename from website-to-html/exclude_specific_url_patterns_conversion_regular_expression_filters_processing.cs rename to website-to-html/exclude-specific-url-patterns-from-conversion-regular-expression-filters-processing.cs index a710075..69cf163 100644 --- a/website-to-html/exclude_specific_url_patterns_conversion_regular_expression_filters_processing.cs +++ b/website-to-html/exclude-specific-url-patterns-from-conversion-regular-expression-filters-processing.cs @@ -2,15 +2,15 @@ using System; using System.Text.RegularExpressions; +using Aspose.Html.Net; -class ExcludeUrlMessageHandler : Aspose.Html.Net.MessageHandler +class ExcludeUrlHandler : Aspose.Html.Net.MessageHandler { - private readonly Regex _excludeRegex = new Regex(@"^https?://.*\.png$", RegexOptions.Compiled | RegexOptions.IgnoreCase); - + private readonly Regex _excludeRegex = new Regex(@"https?://.*\.png", RegexOptions.Compiled | RegexOptions.IgnoreCase); public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) { - string urlText = context.Request.RequestUri.ToString(); - if (_excludeRegex.IsMatch(urlText)) + string url = context.Request.RequestUri.ToString(); + if (_excludeRegex.IsMatch(url)) { return; } @@ -24,33 +24,32 @@ static void Main() { try { - // Create configuration and customize network service + // Create configuration and add custom message handler Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); Aspose.Html.Services.INetworkService networkService = configuration.GetService(); - networkService.MessageHandlers.Add(new ExcludeUrlMessageHandler()); + networkService.MessageHandlers.Add(new ExcludeUrlHandler()); - // Prepare request (using a simple HTML string via data URI) - string htmlContent = "Test

Hello, Aspose.HTML!

"; - string dataUri = "data:text/html;charset=utf-8," + Uri.EscapeDataString(htmlContent); - Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(dataUri); + // Define the request URL + Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage("https://example.com"); - // Load document + // Load the HTML document using the request and configuration using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(request, configuration)) { - // Set MHTML save options (default options are sufficient) + // Set up MHTML save options Aspose.Html.Saving.MHTMLSaveOptions options = new Aspose.Html.Saving.MHTMLSaveOptions(); // Define output path string outputPath = "output.mhtml"; - // Convert HTML document to MHTML file + // Convert HTML to MHTML Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); - Console.WriteLine($"Conversion completed. Output saved to: {outputPath}"); } + + Console.WriteLine("Conversion completed successfully."); } catch (Exception ex) { - Console.WriteLine($"Error: {ex.Message}"); + Console.WriteLine("Error: " + ex.Message); } } } \ No newline at end of file diff --git a/website-to-html/generate-sitemap-xml-file-alongside-html-output-map-converted-pages.cs b/website-to-html/generate-sitemap-xml-file-alongside-html-output-map-converted-pages.cs new file mode 100644 index 0000000..6f74670 --- /dev/null +++ b/website-to-html/generate-sitemap-xml-file-alongside-html-output-map-converted-pages.cs @@ -0,0 +1,54 @@ +// Generate a sitemap XML file alongside the HTML output to map converted pages. + +using System; +using System.IO; + +class Program +{ + static void Main() + { + try + { + // Prepare paths + string sourcePath = "sample.html"; + string outputDir = "output"; + string resultPath = Path.Combine(outputDir, "sample_converted.html"); + string sitemapPath = Path.Combine(outputDir, "sitemap.xml"); + + // Ensure output directory exists + if (!Directory.Exists(outputDir)) + Directory.CreateDirectory(outputDir); + + // Create a minimal sample HTML file if it does not exist + if (!File.Exists(sourcePath)) + { + string sampleHtml = "Sample

Hello, Aspose.HTML!

"; + File.WriteAllText(sourcePath, sampleHtml); + } + + // Load the HTML document + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(sourcePath, new Aspose.Html.Configuration()); + + // Save the converted HTML to the result path + document.Save(resultPath); + document.Dispose(); + + // Generate a simple sitemap XML file + string sitemapXml = @" + + + " + resultPath.Replace("\\", "/") + @" + +"; + File.WriteAllText(sitemapPath, sitemapXml); + + Console.WriteLine("Conversion completed successfully."); + Console.WriteLine("HTML output: " + resultPath); + Console.WriteLine("Sitemap generated: " + sitemapPath); + } + catch (Exception ex) + { + Console.WriteLine("An error occurred: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/generate-summary-report-processed-url-output-path-conversion-status.cs b/website-to-html/generate-summary-report-processed-url-output-path-conversion-status.cs new file mode 100644 index 0000000..7c663a3 --- /dev/null +++ b/website-to-html/generate-summary-report-processed-url-output-path-conversion-status.cs @@ -0,0 +1,78 @@ +// Generate a summary report listing each processed URL, output path, and conversion status. + +using System; +using System.IO; +using System.Collections.Generic; +using Aspose.Html; + +class Program +{ + static void Main() + { + try + { + // Define input URLs + string[] urls = new string[] + { + "https://example.com", + "https://www.wikipedia.org" + }; + + // Prepare output directory and CSV report path + string outputDirectory = "output"; + Directory.CreateDirectory(outputDirectory); + string csvPath = "summary.csv"; + + // List to hold report entries + List report = new List(); + + // Process each URL + for (int i = 0; i < urls.Length; i++) + { + string url = urls[i]; + string outputPath = Path.Combine(outputDirectory, $"page{i + 1}.html"); + try + { + // Load HTML document from URL + HTMLDocument document = new HTMLDocument(url); + // Save document to local file + document.Save(outputPath); + // Record success + report.Add(new ReportEntry { Url = url, OutputPath = outputPath, Status = "Success" }); + } + catch (Exception ex) + { + // Record failure + report.Add(new ReportEntry { Url = url, OutputPath = string.Empty, Status = "Failed: " + ex.Message }); + } + } + + // Write CSV summary report + using (StreamWriter csvWriter = new StreamWriter(csvPath, false)) + { + csvWriter.WriteLine("URL,OutputPath,Status"); + foreach (ReportEntry entry in report) + { + // Escape commas in fields if necessary + string escapedUrl = entry.Url.Contains(",") ? $"\"{entry.Url}\"" : entry.Url; + string escapedPath = entry.OutputPath.Contains(",") ? $"\"{entry.OutputPath}\"" : entry.OutputPath; + string escapedStatus = entry.Status.Contains(",") ? $"\"{entry.Status}\"" : entry.Status; + csvWriter.WriteLine($"{escapedUrl},{escapedPath},{escapedStatus}"); + } + } + + Console.WriteLine("Processing completed. Summary report saved to " + csvPath); + } + catch (Exception e) + { + Console.WriteLine("An error occurred: " + e.Message); + } + } + + class ReportEntry + { + public string Url { get; set; } + public string OutputPath { get; set; } + public string Status { get; set; } + } +} \ No newline at end of file diff --git a/website-to-html/generate_summary_report_processed_url_output_path_conversion_status.cs b/website-to-html/generate_summary_report_processed_url_output_path_conversion_status.cs deleted file mode 100644 index 4e0b97a..0000000 --- a/website-to-html/generate_summary_report_processed_url_output_path_conversion_status.cs +++ /dev/null @@ -1,144 +0,0 @@ -// Generate a summary report listing each processed URL, output path, and conversion status. - -using System; -using System.IO; -using System.IO.Compression; -using System.Collections.Generic; -using System.Diagnostics; - -class Program -{ - static void Main() - { - try - { - // Paths and literals - string inputHtml = "sample.html"; - string outputHtml = "output.html"; - string resourceDirectory = "resources"; - string csvPath = "resources.csv"; - string zipPath = "sample.zip"; - string extractDirectory = "extracted"; - string outputPdfPath = "output.pdf"; - - // Ensure directories exist - Directory.CreateDirectory(resourceDirectory); - Directory.CreateDirectory(extractDirectory); - - // Create a minimal HTML file if it does not exist - if (!File.Exists(inputHtml)) - { - File.WriteAllText(inputHtml, "Sample

Hello Aspose.HTML

"); - } - - // Load HTML document - var document = new Aspose.Html.HTMLDocument(inputHtml); - - // Resource handler to capture saved resources - var resourceHandler = new MyResourceHandler(resourceDirectory); - var options = new Aspose.Html.Saving.HTMLSaveOptions(); - - // Save document and resources - document.Save(resourceHandler, options); - - // Write resources information to CSV - using (var csvWriter = new StreamWriter(csvPath, false)) - { - csvWriter.WriteLine("Type,URL,LocalPath"); - foreach (var resource in resourceHandler.Resources) - { - string type = resource.MimeType != null ? resource.MimeType.ToString() : "unknown"; - string url = resource.OriginalUrl != null ? resource.OriginalUrl.ToString() : string.Empty; - string localPath = resource.OutputUrl != null ? resource.OutputUrl.ToString() : string.Empty; - csvWriter.WriteLine($"{type},{url},{localPath}"); - } - } - - // Save the document to a separate HTML file - document.Save(outputHtml); - - // Create a ZIP archive containing the HTML file - using (var zipStream = File.Open(zipPath, FileMode.Create)) - using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create)) - { - var entry = archive.CreateEntry(Path.GetFileName(inputHtml)); - using (var entryStream = entry.Open()) - using (var fileStream = File.OpenRead(inputHtml)) - { - fileStream.CopyTo(entryStream); - } - } - - // Extract HTML files from the ZIP archive - using (var zipStream = File.OpenRead(zipPath)) - using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Read)) - { - foreach (var entry in archive.Entries) - { - if (entry.FullName.EndsWith(".html", StringComparison.OrdinalIgnoreCase) || - entry.FullName.EndsWith(".htm", StringComparison.OrdinalIgnoreCase)) - { - string entryPath = Path.Combine(extractDirectory, entry.FullName); - string entryFolder = Path.GetDirectoryName(entryPath); - if (!string.IsNullOrEmpty(entryFolder)) - Directory.CreateDirectory(entryFolder); - entry.ExtractToFile(entryPath, true); - } - } - } - - // Locate the extracted HTML file - string[] htmlFiles = Directory.GetFiles(extractDirectory, "*.html", SearchOption.AllDirectories); - if (htmlFiles.Length == 0) - htmlFiles = Directory.GetFiles(extractDirectory, "*.htm", SearchOption.AllDirectories); - if (htmlFiles.Length == 0) - throw new FileNotFoundException("No HTML file found after ZIP extraction."); - - // Configure network service with a custom message handler - var configuration = new Aspose.Html.Configuration(); - var networkService = configuration.GetService(); - networkService.MessageHandlers.Add(new MyMessageHandler()); - - // Convert the extracted HTML to PDF and measure time - var conversionTimer = Stopwatch.StartNew(); - using (var doc = new Aspose.Html.HTMLDocument(htmlFiles[0], configuration)) - using (var device = new Aspose.Html.Rendering.Pdf.PdfDevice(outputPdfPath)) - { - doc.RenderTo(device); - } - conversionTimer.Stop(); - - Console.WriteLine("Conversion completed in " + conversionTimer.Elapsed.TotalSeconds.ToString("F2") + " seconds."); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} - -// Custom resource handler that records saved resources -class MyResourceHandler : Aspose.Html.Saving.ResourceHandlers.FileSystemResourceHandler -{ - public List Resources = new List(); - - public MyResourceHandler(string directory) : base(directory) { } - - public override void HandleResource(Aspose.Html.Saving.Resource resource, Aspose.Html.Saving.ResourceHandlingContext context) - { - Resources.Add(resource); - base.HandleResource(resource, context); - } -} - -// Custom network message handler to log request duration -public sealed class MyMessageHandler : Aspose.Html.Net.MessageHandler -{ - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - var requestTimer = Stopwatch.StartNew(); - Next(context); - requestTimer.Stop(); - Console.WriteLine("Request: " + context.Request.RequestUri + " | " + requestTimer.ElapsedMilliseconds + " ms"); - } -} \ No newline at end of file diff --git a/website-to-html/implement-retry-logic-transient-network-failures-fetching-website-resources-during-conversion.cs b/website-to-html/implement-retry-logic-transient-network-failures-fetching-website-resources-during-conversion.cs new file mode 100644 index 0000000..9b0ce23 --- /dev/null +++ b/website-to-html/implement-retry-logic-transient-network-failures-fetching-website-resources-during-conversion.cs @@ -0,0 +1,57 @@ +// Implement retry logic for transient network failures when fetching website resources during conversion. + +using System; +using System.IO; +using System.Threading; + +class RetryMessageHandler : Aspose.Html.Net.MessageHandler +{ + private readonly int _maxRetries; + public RetryMessageHandler(int maxRetries) + { + _maxRetries = maxRetries; + } + + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + for (int attempt = 0; attempt <= _maxRetries; attempt++) + { + Next(context); + if ((int)context.Response.StatusCode < 500) + break; + } + } +} + +class Program +{ + static void Main() + { + try + { + string url = "https://example.com"; + string outputPath = "output.pdf"; + int maxRetries = 3; + + ConvertHtmlToPdfWithRetry(url, outputPath, maxRetries); + Console.WriteLine("Conversion completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + static void ConvertHtmlToPdfWithRetry(string url, string outputPath, int maxRetries) + { + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + Aspose.Html.Services.INetworkService network = configuration.GetService(); + network.MessageHandlers.Add(new RetryMessageHandler(maxRetries)); + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) + { + Aspose.Html.Saving.PdfSaveOptions options = new Aspose.Html.Saving.PdfSaveOptions(); + Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); + } + } +} \ No newline at end of file diff --git a/website-to-html/implement_retry_logic_for_transient_network_failures_when_fetching_website_resources_during_conversion.cs b/website-to-html/implement_retry_logic_for_transient_network_failures_when_fetching_website_resources_during_conversion.cs deleted file mode 100644 index e99fa8f..0000000 --- a/website-to-html/implement_retry_logic_for_transient_network_failures_when_fetching_website_resources_during_conversion.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Implement retry logic for transient network failures when fetching website resources during conversion. - -using System; -using System.IO; -using System.Net; -using System.Threading; - -class RetryMessageHandler : Aspose.Html.Net.MessageHandler -{ - private readonly int _maxRetries; - - public RetryMessageHandler(int maxRetries) - { - _maxRetries = maxRetries; - } - - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - for (int attempt = 0; attempt <= _maxRetries; attempt++) - { - Next(context); - if ((int)context.Response.StatusCode < 500) - break; - } - } -} - -class Program -{ - static void Main() - { - try - { - string inputPath = "sample.mht"; - string outputPath = "output.pdf"; - int maxAttempts = 3; - int retryDelayMs = 1000; - - // Ensure a minimal MHTML file exists - if (!File.Exists(inputPath)) - { - string minimalMhtml = @"From: -Subject: Sample -Date: Mon, 1 Jan 2024 00:00:00 +0000 -MIME-Version: 1.0 -Content-Type: multipart/related; boundary=""----=_NextPart_000_0000""; type=""text/html"" - -------=_NextPart_000_0000 -Content-Type: text/html; charset=""utf-8"" -Content-Transfer-Encoding: quoted-printable - -

Hello, MHTML!

- -------=_NextPart_000_0000--"; - File.WriteAllText(inputPath, minimalMhtml); - } - - // Configure Aspose.Html with retry handler - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - Aspose.Html.Services.INetworkService network = configuration.GetService(); - network.MessageHandlers.Add(new RetryMessageHandler(maxAttempts)); - - // Perform conversion with retry logic - ConvertMhtmlToPdfWithRetry(inputPath, outputPath, maxAttempts, retryDelayMs); - Console.WriteLine($"Conversion succeeded. PDF saved to '{outputPath}'."); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } - - static void ConvertMhtmlToPdfWithRetry(string inputPath, string outputPath, int maxAttempts, int delayMilliseconds) - { - Exception lastException = null; - - for (int attempt = 1; attempt <= maxAttempts; attempt++) - { - try - { - using (Stream stream = File.OpenRead(inputPath)) - { - var options = new Aspose.Html.Saving.PdfSaveOptions(); - Aspose.Html.Converters.Converter.ConvertMHTML(stream, options, outputPath); - } - // Success, exit method - return; - } - catch (IOException ioEx) - { - lastException = ioEx; - } - catch (UnauthorizedAccessException uaEx) - { - lastException = uaEx; - } - - // Wait before next attempt if not the last one - if (attempt < maxAttempts) - { - Thread.Sleep(delayMilliseconds); - } - } - - // All attempts failed - throw lastException ?? new Exception("Conversion failed without captured exception."); - } -} \ No newline at end of file diff --git a/website-to-html/include-external-images-base64-encoded-data-uris-generated-html-file.cs b/website-to-html/include-external-images-base64-encoded-data-uris-generated-html-file.cs new file mode 100644 index 0000000..224fd41 --- /dev/null +++ b/website-to-html/include-external-images-base64-encoded-data-uris-generated-html-file.cs @@ -0,0 +1,66 @@ +// Include external images as base64‑encoded data URIs within the generated HTML file. + +using System; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; +using Aspose.Html; + +class Program +{ + static async Task Main(string[] args) + { + try + { + string inputPath = "input.html"; + string outputPath = "output.html"; + + if (!File.Exists(inputPath)) + { + File.WriteAllText(inputPath, ""); + } + + using (var document = new Aspose.Html.HTMLDocument(inputPath)) + using (var httpClient = new HttpClient()) + { + Aspose.Html.Collections.HTMLCollection images = document.GetElementsByTagName("img"); + for (int i = 0; i < images.Length; i++) + { + Aspose.Html.Dom.Element imageElement = (Aspose.Html.Dom.Element)images[i]; + string src = imageElement.GetAttribute("src"); + if (string.IsNullOrWhiteSpace(src)) + { + continue; + } + + Uri baseUri = new Uri(document.BaseURI.ToString(), UriKind.Absolute); + Uri resolvedUri = new Uri(baseUri, src); + byte[] imageBytes = await httpClient.GetByteArrayAsync(resolvedUri.AbsoluteUri); + string mimeType = GetMimeType(Path.GetExtension(resolvedUri.AbsolutePath)); + string dataUri = "data:" + mimeType + ";base64," + Convert.ToBase64String(imageBytes); + imageElement.SetAttribute("src", dataUri); + } + + document.Save(outputPath); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } + + static string GetMimeType(string extension) + { + switch (extension.ToLowerInvariant()) + { + case ".png": return "image/png"; + case ".jpg": + case ".jpeg": return "image/jpeg"; + case ".gif": return "image/gif"; + case ".svg": return "image/svg+xml"; + case ".webp": return "image/webp"; + default: return "application/octet-stream"; + } + } +} \ No newline at end of file diff --git a/website-to-html/include_http_response_headers_as_comments_in_generated_html_for_debugging.cs b/website-to-html/include-http-response-headers-comments-in-generated-html-debugging.cs similarity index 69% rename from website-to-html/include_http_response_headers_as_comments_in_generated_html_for_debugging.cs rename to website-to-html/include-http-response-headers-comments-in-generated-html-debugging.cs index c2d39dd..c974c07 100644 --- a/website-to-html/include_http_response_headers_as_comments_in_generated_html_for_debugging.cs +++ b/website-to-html/include-http-response-headers-comments-in-generated-html-debugging.cs @@ -2,22 +2,22 @@ using System; using System.Collections.Generic; +using Aspose.Html; using Aspose.Html.Net; using Aspose.Html.Services; -using Aspose.Html; class HeaderCaptureHandler : Aspose.Html.Net.MessageHandler { - public static List CapturedHeaders = new List(); + public static List capturedHeaders = new List(); public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) { - base.Next(context); + Next(context); foreach (object headerItem in context.Response.Headers) { if (headerItem != null) { - CapturedHeaders.Add(headerItem.ToString()); + capturedHeaders.Add(headerItem.ToString()); } } } @@ -25,34 +25,29 @@ public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) class Program { - static void Main() + static void Main(string[] args) { try { - // Create configuration and attach the custom message handler Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); Aspose.Html.Services.INetworkService networkService = configuration.GetService(); networkService.MessageHandlers.Add(new HeaderCaptureHandler()); - // URL to load string url = "https://example.com"; - - // Load the document with the custom configuration using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) { - // If any headers were captured, insert them as a comment at the top of the document - if (HeaderCaptureHandler.CapturedHeaders.Count > 0) + if (HeaderCaptureHandler.capturedHeaders.Count > 0) { - string commentText = "\n" + string.Join("\n", HeaderCaptureHandler.CapturedHeaders) + "\n"; + string commentText = "\n" + string.Join("\n", HeaderCaptureHandler.capturedHeaders) + "\n"; var commentNode = document.CreateComment(commentText); document.InsertBefore(commentNode, document.DocumentElement); } - // Save the resulting HTML string outputPath = "output.html"; document.Save(outputPath); - Console.WriteLine($"Document saved to: {outputPath}"); } + + Console.WriteLine("HTML saved with headers as comments."); } catch (Exception ex) { diff --git a/website-to-html/integrate-conversion-library-aspnet-mvc-application-for-on-demand-website-rendering.cs b/website-to-html/integrate-conversion-library-aspnet-mvc-application-for-on-demand-website-rendering.cs new file mode 100644 index 0000000..2d6f356 --- /dev/null +++ b/website-to-html/integrate-conversion-library-aspnet-mvc-application-for-on-demand-website-rendering.cs @@ -0,0 +1,34 @@ +// Integrate the conversion library into an ASP.NET MVC application for on‑demand website rendering. + +using System; +using System.IO; + +class Program +{ + static void Main() + { + try + { + string sourcePath = "sample.mhtml"; + using (Stream stream = File.OpenRead(sourcePath)) + { + byte[] docxBytes = ConvertMhtmlToDocxBytes(stream); + string outputPath = "output.docx"; + File.WriteAllBytes(outputPath, docxBytes); + Console.WriteLine($"DOCX file saved to {outputPath}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + static byte[] ConvertMhtmlToDocxBytes(Stream inputStream) + { + string tempDocxPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".docx"); + var options = new Aspose.Html.Saving.DocSaveOptions(); + Aspose.Html.Converters.Converter.ConvertMHTML(inputStream, options, tempDocxPath); + return File.ReadAllBytes(tempDocxPath); + } +} \ No newline at end of file diff --git a/website-to-html/integrate_conversion_library_into_aspnet_mvc_application_for_on_demand_website_rendering.cs b/website-to-html/integrate_conversion_library_into_aspnet_mvc_application_for_on_demand_website_rendering.cs deleted file mode 100644 index 3a51b1f..0000000 --- a/website-to-html/integrate_conversion_library_into_aspnet_mvc_application_for_on_demand_website_rendering.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Integrate the conversion library into an ASP.NET MVC application for on‑demand website rendering. - -using System; -using System.IO; - -class Program -{ - static void Main() - { - try - { - // Create a sample markdown file and convert it to HTML - string markdownPath = "sample.md"; - File.WriteAllText(markdownPath, "# Sample Markdown\nThis is a test markdown file."); - string markdownOutput = "sample.html"; - Aspose.Html.Converters.Converter.ConvertMarkdown(markdownPath, markdownOutput); - Console.WriteLine($"Markdown converted to HTML: {markdownOutput}"); - - // Create a minimal MHTML file (simple HTML saved with .mhtml extension) - string mhtmlPath = "sample.mhtml"; - File.WriteAllText(mhtmlPath, "

MHTML Sample

Test content.

"); - - // Convert MHTML to DOCX using helper method - using (FileStream mhtmlStream = File.OpenRead(mhtmlPath)) - { - byte[] docxBytes = ConvertMhtmlToDocxBytes(mhtmlStream); - string docxOutput = "sample.docx"; - File.WriteAllBytes(docxOutput, docxBytes); - Console.WriteLine($"MHTML converted to DOCX: {docxOutput}"); - } - - // Convert MHTML to BMP image - string imageOutput = "sample.bmp"; - using (FileStream mhtmlStream = File.OpenRead(mhtmlPath)) - { - var imgOptions = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Bmp); - imgOptions.UseAntialiasing = true; - imgOptions.HorizontalResolution = 96; - imgOptions.VerticalResolution = 96; - Aspose.Html.Converters.Converter.ConvertMHTML(mhtmlStream, imgOptions, imageOutput); - Console.WriteLine($"MHTML converted to image: {imageOutput}"); - } - - // Convert MHTML to XPS - string xpsOutput = "sample.xps"; - using (FileStream mhtmlStream = File.OpenRead(mhtmlPath)) - { - var xpsOptions = new Aspose.Html.Saving.XpsSaveOptions(); - Aspose.Html.Converters.Converter.ConvertMHTML(mhtmlStream, xpsOptions, xpsOutput); - Console.WriteLine($"MHTML converted to XPS: {xpsOutput}"); - } - - // Convert HTML file to XPS (demonstrating ConvertHTML overload) - string htmlSource = markdownOutput; // using the HTML generated from markdown - string htmlXpsOutput = "html_output.xps"; - var htmlXpsOptions = new Aspose.Html.Saving.XpsSaveOptions(); - Aspose.Html.Converters.Converter.ConvertHTML(htmlSource, "", htmlXpsOptions, htmlXpsOutput); - Console.WriteLine($"HTML converted to XPS: {htmlXpsOutput}"); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } - - static byte[] ConvertMhtmlToDocxBytes(Stream inputStream) - { - string tempDocxPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".docx"); - var options = new Aspose.Html.Saving.DocSaveOptions(); - Aspose.Html.Converters.Converter.ConvertMHTML(inputStream, options, tempDocxPath); - byte[] result = File.ReadAllBytes(tempDocxPath); - // Clean up temporary file - try { File.Delete(tempDocxPath); } catch { } - return result; - } -} \ No newline at end of file diff --git a/website-to-html/load-website-url-convert-single-html-file-embedded-resources.cs b/website-to-html/load-website-url-convert-single-html-file-embedded-resources.cs new file mode 100644 index 0000000..dc1dbd0 --- /dev/null +++ b/website-to-html/load-website-url-convert-single-html-file-embedded-resources.cs @@ -0,0 +1,31 @@ +// Load a website URL and convert it to a single HTML file with embedded resources. + +using System; + +class Program +{ + static void Main(string[] args) + { + try + { + string inputUrl = "https://example.com"; + string outputPath = "output.html"; + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputUrl)) + { + Aspose.Html.Saving.HTMLSaveOptions options = new Aspose.Html.Saving.HTMLSaveOptions(); + options.ResourceHandlingOptions.MaxHandlingDepth = 5; + options.ResourceHandlingOptions.PageUrlRestriction = Aspose.Html.Saving.UrlRestriction.SameHost; + options.ResourceHandlingOptions.JavaScript = Aspose.Html.Saving.ResourceHandling.Embed; + + document.Save(outputPath, options); + } + + System.Console.WriteLine("Conversion completed successfully."); + } + catch (Exception ex) + { + System.Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/log-detailed-conversion-progress-errors-file-troubleshooting-batch-operations.cs b/website-to-html/log-detailed-conversion-progress-errors-file-troubleshooting-batch-operations.cs new file mode 100644 index 0000000..16eee5f --- /dev/null +++ b/website-to-html/log-detailed-conversion-progress-errors-file-troubleshooting-batch-operations.cs @@ -0,0 +1,93 @@ +// Log detailed conversion progress and errors to a file for troubleshooting batch operations. + +using System; +using System.IO; +using System.Diagnostics; + +public sealed class NetworkLogHandler : Aspose.Html.Net.MessageHandler +{ + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + Stopwatch requestTimer = Stopwatch.StartNew(); + Next(context); + requestTimer.Stop(); + Console.WriteLine("Request: " + context.Request.RequestUri + " | " + requestTimer.ElapsedMilliseconds + " ms"); + } +} + +public class Program +{ + public static void Main() + { + try + { + string inputFolder = "InputHtml"; + string outputFolder = "OutputPdf"; + string logPath = "conversion.log"; + + if (!Directory.Exists(inputFolder)) + Directory.CreateDirectory(inputFolder); + if (!Directory.Exists(outputFolder)) + Directory.CreateDirectory(outputFolder); + // Ensure log file exists + File.WriteAllText(logPath, $"Conversion started at {DateTime.Now}{Environment.NewLine}"); + + // Create a sample HTML file if none exist + string[] htmlFiles = Directory.GetFiles(inputFolder, "*.html", SearchOption.AllDirectories); + if (htmlFiles.Length == 0) + { + string samplePath = Path.Combine(inputFolder, "sample.html"); + File.WriteAllText(samplePath, "Sample

Hello, Aspose.HTML!

"); + htmlFiles = new string[] { samplePath }; + } + if (htmlFiles.Length == 0) + { + htmlFiles = Directory.GetFiles(inputFolder, "*.htm", SearchOption.AllDirectories); + } + if (htmlFiles.Length == 0) + throw new FileNotFoundException("No HTML files found for conversion."); + + int total = htmlFiles.Length; + int successCount = 0; + + for (int i = 0; i < total; i++) + { + string htmlPath = htmlFiles[i]; + string pdfPath = Path.Combine(outputFolder, Path.GetFileNameWithoutExtension(htmlPath) + ".pdf"); + try + { + File.AppendAllText(logPath, $"[{DateTime.Now}] Starting conversion: {htmlPath}{Environment.NewLine}"); + + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + Aspose.Html.Services.INetworkService networkService = configuration.GetService(); + networkService.MessageHandlers.Add(new NetworkLogHandler()); + + Stopwatch conversionTimer = Stopwatch.StartNew(); + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath, configuration)) + using (Aspose.Html.Rendering.Pdf.PdfDevice device = new Aspose.Html.Rendering.Pdf.PdfDevice(pdfPath)) + { + document.RenderTo(device); + } + + conversionTimer.Stop(); + File.AppendAllText(logPath, $"[{DateTime.Now}] Successfully converted to {pdfPath} in {conversionTimer.Elapsed.TotalSeconds:F2} seconds.{Environment.NewLine}"); + Console.WriteLine($"Converted {i + 1}/{total} ({(i + 1) * 100 / total}%)"); + successCount++; + } + catch (Exception ex) + { + File.AppendAllText(logPath, $"[{DateTime.Now}] Error converting {htmlPath}: {ex.Message}{Environment.NewLine}"); + Console.WriteLine($"Error converting file {Path.GetFileName(htmlPath)}: {ex.Message}"); + } + } + + File.AppendAllText(logPath, $"Conversion completed at {DateTime.Now}. Success: {successCount}/{total}{Environment.NewLine}"); + Console.WriteLine($"Batch conversion finished. {successCount} of {total} files converted successfully."); + } + catch (Exception ex) + { + Console.WriteLine("Fatal error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/log_detailed_conversion_progress_and_errors_to_file_troubleshooting_batch_operations.cs b/website-to-html/log_detailed_conversion_progress_and_errors_to_file_troubleshooting_batch_operations.cs deleted file mode 100644 index 81d1b23..0000000 --- a/website-to-html/log_detailed_conversion_progress_and_errors_to_file_troubleshooting_batch_operations.cs +++ /dev/null @@ -1,243 +0,0 @@ -// Log detailed conversion progress and errors to a file for troubleshooting batch operations. - -using System; -using System.IO; -using System.IO.Compression; -using System.Diagnostics; -using System.Drawing; - -public sealed class RequestTimingHandler : Aspose.Html.Net.MessageHandler -{ - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - Stopwatch requestTimer = Stopwatch.StartNew(); - Next(context); - requestTimer.Stop(); - Console.WriteLine("Request: " + context.Request.RequestUri + " | " + requestTimer.ElapsedMilliseconds + " ms"); - } -} - -public class LogHandler : Aspose.Html.Net.MessageHandler -{ - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - Next(context); - Console.WriteLine(context.Request.RequestUri + " | " + context.Response.StatusCode); - } -} - -public class CustomStreamProvider : Aspose.Html.IO.ICreateStreamProvider, IDisposable -{ - public System.Collections.Generic.List Streams { get; } = new System.Collections.Generic.List(); - - public Stream GetStream(string name, string extension) - { - MemoryStream ms = new MemoryStream(); - Streams.Add(ms); - return ms; - } - - public Stream GetStream(string name, string extension, int page) - { - MemoryStream ms = new MemoryStream(); - Streams.Add(ms); - return ms; - } - - public void ReleaseStream(Stream stream) - { - if (stream != null) - { - stream.Flush(); - } - } - - public void Dispose() - { - foreach (MemoryStream ms in Streams) - { - ms.Dispose(); - } - } -} - -public class Program -{ - public static void Main() - { - try - { - // 1. Extract ZIP and convert first HTML to PDF with request timing handler - string zipPath = "sample.zip"; - string extractDirectory = "extracted"; - string outputPdfPath = "output.pdf"; - - Directory.CreateDirectory(extractDirectory); - - // Create a sample ZIP with a simple HTML file if it does not exist - if (!File.Exists(zipPath)) - { - using (FileStream zipStream = new FileStream(zipPath, FileMode.Create)) - using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create)) - { - ZipArchiveEntry entry = archive.CreateEntry("index.html"); - using (Stream entryStream = entry.Open()) - using (StreamWriter writer = new StreamWriter(entryStream)) - { - writer.Write("

Hello from ZIP

"); - } - } - } - - using (FileStream zipStream = File.OpenRead(zipPath)) - using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Read)) - { - foreach (ZipArchiveEntry entry in archive.Entries) - { - if (entry.FullName.EndsWith(".html", StringComparison.OrdinalIgnoreCase) || - entry.FullName.EndsWith(".htm", StringComparison.OrdinalIgnoreCase)) - { - string entryPath = Path.Combine(extractDirectory, entry.FullName); - string entryFolder = Path.GetDirectoryName(entryPath); - if (!string.IsNullOrEmpty(entryFolder)) - Directory.CreateDirectory(entryFolder); - entry.ExtractToFile(entryPath, true); - } - } - } - - string[] htmlFiles = Directory.GetFiles(extractDirectory, "*.html", SearchOption.AllDirectories); - if (htmlFiles.Length == 0) - htmlFiles = Directory.GetFiles(extractDirectory, "*.htm", SearchOption.AllDirectories); - if (htmlFiles.Length == 0) - throw new FileNotFoundException("No HTML file found after ZIP extraction."); - - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - Aspose.Html.Services.INetworkService networkService = configuration.GetService(); - networkService.MessageHandlers.Add(new RequestTimingHandler()); - - Stopwatch conversionTimer = Stopwatch.StartNew(); - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlFiles[0], configuration)) - using (Aspose.Html.Rendering.Pdf.PdfDevice device = new Aspose.Html.Rendering.Pdf.PdfDevice(outputPdfPath)) - { - document.RenderTo(device); - } - conversionTimer.Stop(); - Console.WriteLine("Conversion completed in " + conversionTimer.Elapsed.TotalSeconds.ToString("F2") + " seconds."); - - // 2. Convert SVG files to PNG images - string inputFolder = "svg_input"; - string outputFolder = "svg_output"; - Directory.CreateDirectory(inputFolder); - Directory.CreateDirectory(outputFolder); - - // Create a sample SVG if none exist - string[] existingSvg = Directory.GetFiles(inputFolder, "*.svg"); - if (existingSvg.Length == 0) - { - string sampleSvgPath = Path.Combine(inputFolder, "sample.svg"); - File.WriteAllText(sampleSvgPath, - ""); - } - - string[] svgFiles = Directory.GetFiles(inputFolder, "*.svg"); - int total = svgFiles.Length; - for (int i = 0; i < total; i++) - { - string svgPath = svgFiles[i]; - string outputPath = Path.Combine(outputFolder, - Path.GetFileNameWithoutExtension(svgPath) + ".png"); - - using (Aspose.Html.Dom.Svg.SVGDocument document = new Aspose.Html.Dom.Svg.SVGDocument(svgPath)) - { - Aspose.Html.Saving.ImageSaveOptions options = new Aspose.Html.Saving.ImageSaveOptions(); - options.HorizontalResolution = 300; - options.VerticalResolution = 300; - options.BackgroundColor = Color.White; - options.UseAntialiasing = true; - Aspose.Html.Converters.Converter.ConvertSVG(document, options, outputPath); - } - - int percent = (i + 1) * 100 / total; - Console.WriteLine($"Converted {i + 1}/{total} ({percent}%) - {Path.GetFileName(outputPath)}"); - } - - // 3. Convert HTML files to PDF with request logging handler - string htmlInputDir = "html_input"; - Directory.CreateDirectory(htmlInputDir); - // Create a sample HTML file if none exist - if (Directory.GetFiles(htmlInputDir, "*.html").Length == 0) - { - string sampleHtml = Path.Combine(htmlInputDir, "sample.html"); - File.WriteAllText(sampleHtml, "

Sample HTML for logging.

"); - } - - foreach (string htmlPath in Directory.GetFiles(htmlInputDir, "*.html")) - { - Aspose.Html.Configuration cfg = new Aspose.Html.Configuration(); - Aspose.Html.Services.INetworkService net = cfg.GetService(); - net.MessageHandlers.Add(new LogHandler()); - - using (Aspose.Html.HTMLDocument doc = new Aspose.Html.HTMLDocument(htmlPath, cfg)) - { - string pdfPath = Path.ChangeExtension(htmlPath, ".pdf"); - Aspose.Html.Saving.PdfSaveOptions opts = new Aspose.Html.Saving.PdfSaveOptions(); - Aspose.Html.Converters.Converter.ConvertHTML(doc, opts, pdfPath); - } - } - - // 4. Simple XPath logging example - string logPath = "log.txt"; - File.AppendAllText(logPath, "Log start" + Environment.NewLine); - Aspose.Html.HTMLDocument docForXPath = new Aspose.Html.HTMLDocument(""); - File.AppendAllText(logPath, "Document created" + Environment.NewLine); - Aspose.Html.Dom.XPath.IXPathResult result = docForXPath.Evaluate("//img", docForXPath, docForXPath.CreateNSResolver(docForXPath), Aspose.Html.Dom.XPath.XPathResultType.Any, null); - File.AppendAllText(logPath, "XPath evaluated" + Environment.NewLine); - Aspose.Html.Dom.Node node; - while ((node = result.IterateNext()) != null) - { - Aspose.Html.HTMLImageElement img = (Aspose.Html.HTMLImageElement)node; - File.AppendAllText(logPath, img.Src + Environment.NewLine); - } - - // 5. Convert EPUB files to XPS using custom stream provider - string epubInputDir = "epub_input"; - string xpsOutputDir = "xps_output"; - Directory.CreateDirectory(epubInputDir); - Directory.CreateDirectory(xpsOutputDir); - // Note: No sample EPUB is created; conversion will be skipped if none found. - string[] epubFiles = Directory.GetFiles(epubInputDir, "*.epub"); - foreach (string inputPath in epubFiles) - { - try - { - using (Stream stream = File.OpenRead(inputPath)) - { - CustomStreamProvider streamProvider = new CustomStreamProvider(); - Aspose.Html.Saving.XpsSaveOptions opts = new Aspose.Html.Saving.XpsSaveOptions(); - Aspose.Html.Converters.Converter.ConvertEPUB(stream, opts, streamProvider); - if (streamProvider.Streams.Count > 0) - { - MemoryStream resultStream = streamProvider.Streams[0]; - resultStream.Position = 0; - string outPath = Path.Combine(xpsOutputDir, - Path.GetFileNameWithoutExtension(inputPath) + ".xps"); - using (Stream output = File.Create(outPath)) - { - resultStream.CopyTo(output); - } - } - } - } - catch (Exception ex) - { - Console.WriteLine("Failed to convert EPUB file " + Path.GetFileName(inputPath) + ": " + ex.Message); - } - } - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/website-to-html/option-retain-original-javascript-files-alongside-converted-html-interactive-pages.cs b/website-to-html/option-retain-original-javascript-files-alongside-converted-html-interactive-pages.cs new file mode 100644 index 0000000..c0842ef --- /dev/null +++ b/website-to-html/option-retain-original-javascript-files-alongside-converted-html-interactive-pages.cs @@ -0,0 +1,38 @@ +// Provide an option to retain original JavaScript files alongside converted HTML for interactive pages. + +using System; + +class Program +{ + static void Main() + { + try + { + string inputHtmlPath = "input.html"; + string jsPath = "script.js"; + + // Create a sample JavaScript file + System.IO.File.WriteAllText(jsPath, "function greet(){ alert('Hello'); }"); + + // Create a sample HTML file that references the JavaScript file + string htmlContent = ""; + System.IO.File.WriteAllText(inputHtmlPath, htmlContent); + + // Load the HTML document + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputHtmlPath); + + // Configure save options to retain original JavaScript files (link them) + Aspose.Html.Saving.HTMLSaveOptions options = new Aspose.Html.Saving.HTMLSaveOptions(); + options.ResourceHandlingOptions.JavaScript = Aspose.Html.Saving.ResourceHandling.Embed; + + string outputHtmlPath = "output.html"; + + // Save the document with the configured options + document.Save(outputHtmlPath, options); + } + catch (System.Exception ex) + { + System.Console.WriteLine(ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/preserve-original-meta-tags-seo-attributes-converting-website-pages-to-html.cs b/website-to-html/preserve-original-meta-tags-seo-attributes-converting-website-pages-to-html.cs new file mode 100644 index 0000000..b837a5a --- /dev/null +++ b/website-to-html/preserve-original-meta-tags-seo-attributes-converting-website-pages-to-html.cs @@ -0,0 +1,42 @@ +// Preserve original meta tags and SEO attributes when converting website pages to HTML. + +using System; +using System.IO; +using System.Text; +using Aspose.Html; +using Aspose.Html.Dom; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "Sample

Hello World

"; + byte[] bytes = Encoding.UTF8.GetBytes(htmlContent); + using (var inputStream = new MemoryStream(bytes)) + { + using (var document = new Aspose.Html.HTMLDocument(inputStream, "about:blank")) + { + var metaElements = document.GetElementsByTagName("meta"); + foreach (Aspose.Html.Dom.Element meta in metaElements) + { + // Preserve SEO attributes; ensure 'content' attribute is retained + string content = meta.GetAttribute("content"); + if (string.IsNullOrEmpty(content)) + { + meta.SetAttribute("content", "default"); + } + } + + string outputPath = "output.html"; + document.Save(outputPath); + } + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/save-converted-website-html-to-specified-output-directory-preserving-original-folder-structure.cs b/website-to-html/save-converted-website-html-to-specified-output-directory-preserving-original-folder-structure.cs new file mode 100644 index 0000000..39e33bb --- /dev/null +++ b/website-to-html/save-converted-website-html-to-specified-output-directory-preserving-original-folder-structure.cs @@ -0,0 +1,59 @@ +// Save the converted website HTML to a specified output directory preserving original folder structure. + +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +class Program +{ + static void Main() + { + try + { + // Input and output directories + string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "input"); + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "output"); + + // Ensure directories exist + Directory.CreateDirectory(inputFolder); + Directory.CreateDirectory(outputFolder); + + // Create a minimal sample HTML file if none exist + string sampleHtmlPath = Path.Combine(inputFolder, "index.html"); + if (!File.Exists(sampleHtmlPath)) + { + File.WriteAllText(sampleHtmlPath, "Sample

Hello, Aspose.HTML!

"); + } + + // Process all HTML files preserving folder structure + foreach (string htmlPath in Directory.GetFiles(inputFolder, "*.html", SearchOption.AllDirectories)) + { + // Compute relative path and corresponding output path with .mhtml extension + string relativePath = Path.GetRelativePath(inputFolder, htmlPath); + string outputRelativePath = Path.ChangeExtension(relativePath, ".mhtml"); + string outputPath = Path.Combine(outputFolder, outputRelativePath); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); + + // Load HTML document + using (HTMLDocument document = new HTMLDocument(htmlPath)) + { + // Configure MHTML save options + MHTMLSaveOptions options = new MHTMLSaveOptions(); + + // Convert and save + Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); + } + } + + Console.WriteLine("Conversion completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/save_converted_website_html_to_specified_output_directory_preserving_original_folder_structure.cs b/website-to-html/save_converted_website_html_to_specified_output_directory_preserving_original_folder_structure.cs deleted file mode 100644 index 8ee53af..0000000 --- a/website-to-html/save_converted_website_html_to_specified_output_directory_preserving_original_folder_structure.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Save the converted website HTML to a specified output directory preserving original folder structure. - -using System; -using System.IO; - -class Program -{ - static void Main() - { - try - { - // Prepare input folder and sample HTML file - string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "InputHtml"); - Directory.CreateDirectory(inputFolder); - string sampleHtmlPath = Path.Combine(inputFolder, "sample.html"); - if (!File.Exists(sampleHtmlPath)) - { - File.WriteAllText(sampleHtmlPath, "

Hello Aspose.HTML

"); - } - - // Prepare output folder for image conversion - string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "OutputImages"); - Directory.CreateDirectory(outputFolder); - - // Convert each HTML file to JPEG image - foreach (string htmlPath in Directory.GetFiles(inputFolder, "*.html")) - { - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath)) - { - Aspose.Html.Saving.ImageSaveOptions options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Jpeg); - string outputPath = Path.Combine(outputFolder, Path.GetFileNameWithoutExtension(htmlPath) + ".jpg"); - Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); - } - } - - // Additional conversion with custom resolution - string customOutputDir = Path.Combine(Directory.GetCurrentDirectory(), "CustomResolution"); - Directory.CreateDirectory(customOutputDir); - string[] inputs = new string[] { sampleHtmlPath }; - for (int i = 0; i < inputs.Length; i++) - { - string inputPath = inputs[i]; - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath)) - { - var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Jpeg); - options.HorizontalResolution = 300; - options.VerticalResolution = 300; - string outputPath = Path.Combine(customOutputDir, "custom_res.jpg"); - Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); - } - } - - // Convert to MHTML - string mhtmlOutputPath = Path.Combine(Directory.GetCurrentDirectory(), "output.mhtml"); - Aspose.Html.Saving.MHTMLSaveOptions mhtmlOptions = new Aspose.Html.Saving.MHTMLSaveOptions(); - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(sampleHtmlPath)) - { - Aspose.Html.Converters.Converter.ConvertHTML(document, mhtmlOptions, mhtmlOutputPath); - } - - // Convert to XPS - string xpsOutputPath = Path.Combine(Directory.GetCurrentDirectory(), "output.xps"); - Aspose.Html.Saving.XpsSaveOptions xpsOptions = new Aspose.Html.Saving.XpsSaveOptions(); - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(sampleHtmlPath)) - { - Aspose.Html.Converters.Converter.ConvertHTML(document, xpsOptions, xpsOutputPath); - } - - // Convert Markdown to HTML - string markdownPath = Path.Combine(Directory.GetCurrentDirectory(), "sample.md"); - File.WriteAllText(markdownPath, "# Markdown Title\n\nThis is a **markdown** sample."); - string markdownHtmlOutput = Path.Combine(Directory.GetCurrentDirectory(), "markdown_output.html"); - Aspose.Html.Converters.Converter.ConvertMarkdown(markdownPath, markdownHtmlOutput); - - Console.WriteLine("Conversions completed successfully."); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/website-to-html/set-character-encoding-utf8-all-generated-html-files-ensure-compatibility.cs b/website-to-html/set-character-encoding-utf8-all-generated-html-files-ensure-compatibility.cs new file mode 100644 index 0000000..267d021 --- /dev/null +++ b/website-to-html/set-character-encoding-utf8-all-generated-html-files-ensure-compatibility.cs @@ -0,0 +1,30 @@ +// Set character encoding to UTF‑8 for all generated HTML files to ensure compatibility. + +using System; +using System.Text; + +class Program +{ + static void Main() + { + try + { + string outputPath = "output.html"; + + string htmlContent = "Sample

Hello, world! Привет мир!

"; + + // Create HTMLDocument from inline content with a dummy base URI + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank")) + { + // Save the document; Aspose.HTML writes UTF-8 by default + document.Save(outputPath); + } + + Console.WriteLine("HTML file saved to: " + outputPath); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/set-maximum-crawl-depth-linked-pages-converting-website-html.cs b/website-to-html/set-maximum-crawl-depth-linked-pages-converting-website-html.cs new file mode 100644 index 0000000..e67f205 --- /dev/null +++ b/website-to-html/set-maximum-crawl-depth-linked-pages-converting-website-html.cs @@ -0,0 +1,26 @@ +// Set the maximum crawl depth for linked pages when converting an entire website to HTML. + +using System; + +class Program +{ + static void Main() + { + try + { + string sourceUrl = "https://example.com"; + string outputPath = "output.html"; + + var options = new Aspose.Html.Saving.HTMLSaveOptions(); + options.ResourceHandlingOptions.MaxHandlingDepth = 2; + + var document = new Aspose.Html.HTMLDocument(sourceUrl); + document.Save(outputPath, options); + Console.WriteLine("Conversion completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/set-maximum-file-size-limit-for-individual-html-outputs-to-manage-storage-constraints.cs b/website-to-html/set-maximum-file-size-limit-for-individual-html-outputs-to-manage-storage-constraints.cs new file mode 100644 index 0000000..c070900 --- /dev/null +++ b/website-to-html/set-maximum-file-size-limit-for-individual-html-outputs-to-manage-storage-constraints.cs @@ -0,0 +1,51 @@ +// Set a maximum file size limit for individual HTML outputs to manage storage constraints. + +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Saving; + +class Program +{ + static void Main(string[] args) + { + try + { + // Define input HTML content + string htmlContent = "Sample

Hello, Aspose.HTML!

"; + // Create HTML document from inline content + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Configure save options (optional settings) + Aspose.Html.Saving.HTMLSaveOptions options = new Aspose.Html.Saving.HTMLSaveOptions(); + // Example of setting a resource handling option (not related to size) + options.ResourceHandlingOptions.MaxHandlingDepth = 5; + + // Define output path + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "output.html"); + + // Save the document + document.Save(outputPath, options); + + // Define maximum allowed file size (e.g., 100 KB) + long maxFileSizeBytes = 100 * 1024; + + // Check the size of the saved file + FileInfo fileInfo = new FileInfo(outputPath); + if (fileInfo.Length > maxFileSizeBytes) + { + // Delete the file if it exceeds the limit + fileInfo.Delete(); + Console.WriteLine($"Saved file exceeded the maximum size of {maxFileSizeBytes} bytes and was removed."); + } + else + { + Console.WriteLine($"File saved successfully at '{outputPath}'. Size: {fileInfo.Length} bytes."); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/website-to-html/set_timeout_limit_for_loading_website_resources_to_prevent_excessively_long_conversions.cs b/website-to-html/set-timeout-limit-loading-website-resources-prevent-excessively-long-conversions.cs similarity index 50% rename from website-to-html/set_timeout_limit_for_loading_website_resources_to_prevent_excessively_long_conversions.cs rename to website-to-html/set-timeout-limit-loading-website-resources-prevent-excessively-long-conversions.cs index 52c8880..7eaaf5d 100644 --- a/website-to-html/set_timeout_limit_for_loading_website_resources_to_prevent_excessively_long_conversions.cs +++ b/website-to-html/set-timeout-limit-loading-website-resources-prevent-excessively-long-conversions.cs @@ -1,41 +1,29 @@ // Set a timeout limit for loading website resources to prevent excessively long conversions. -using System; -using System.IO; - -class Program +public sealed class Program { - static void Main() + public static void Main() { try { - // Define the URL to load and the output file path string url = "https://example.com"; string outputPath = "output.html"; - // Create a request message with a timeout Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(url); request.Timeout = System.TimeSpan.FromSeconds(10); - // Load the HTML document from the request using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(request)) { - // Optional: retrieve the outer HTML of the document - string html = ((Aspose.Html.HTMLElement)document.DocumentElement).OuterHTML; - Console.WriteLine($"Document loaded. Length: {html.Length}"); - - // Configure save options Aspose.Html.Saving.HTMLSaveOptions options = new Aspose.Html.Saving.HTMLSaveOptions(); options.ResourceHandlingOptions.MaxHandlingDepth = 5; - - // Save the document to the specified file document.Save(outputPath, options); - Console.WriteLine($"Document saved to: {Path.GetFullPath(outputPath)}"); } + + System.Console.WriteLine("Conversion completed successfully."); } - catch (Exception ex) + catch (System.Exception ex) { - Console.WriteLine($"Error: {ex.Message}"); + System.Console.WriteLine("Error: " + ex.Message); } } } \ No newline at end of file diff --git a/website-to-html/set_character_encoding_utf8_all_generated_html_files_ensure_compatibility.cs b/website-to-html/set_character_encoding_utf8_all_generated_html_files_ensure_compatibility.cs deleted file mode 100644 index 6f4c7a7..0000000 --- a/website-to-html/set_character_encoding_utf8_all_generated_html_files_ensure_compatibility.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Set character encoding to UTF‑8 for all generated HTML files to ensure compatibility. - -using System; -using System.IO; -using System.Text; - -class Program -{ - static void Main() - { - try - { - // Define input and output paths - string sourcePath = "sample.html"; - string outputPath = "output.pdf"; - - // Create a minimal HTML file if it does not exist - if (!File.Exists(sourcePath)) - { - string minimalHtml = "Sample

Hello Aspose.HTML!

"; - File.WriteAllText(sourcePath, minimalHtml, Encoding.UTF8); - } - - // Read HTML content from the file - string htmlContent = File.ReadAllText(sourcePath, Encoding.GetEncoding("utf-8")); - - // Load the HTML content into an Aspose.Html.HTMLDocument - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); - - // Set PDF save options (default options are sufficient for this example) - Aspose.Html.Saving.PdfSaveOptions options = new Aspose.Html.Saving.PdfSaveOptions(); - - // Convert the HTML document to PDF and save to the output path - Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); - - Console.WriteLine($"Conversion succeeded. PDF saved to '{outputPath}'."); - } - catch (Exception ex) - { - Console.WriteLine("An error occurred during conversion:"); - Console.WriteLine(ex.Message); - } - } -} \ No newline at end of file diff --git a/website-to-html/set_maximum_file_size_limit_for_individual_html_outputs_to_manage_storage_constraints.cs b/website-to-html/set_maximum_file_size_limit_for_individual_html_outputs_to_manage_storage_constraints.cs deleted file mode 100644 index d75ae7a..0000000 --- a/website-to-html/set_maximum_file_size_limit_for_individual_html_outputs_to_manage_storage_constraints.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Set a maximum file size limit for individual HTML outputs to manage storage constraints. - -using System; -using System.IO; -using System.Drawing; - -class Program -{ - static void Main() - { - try - { - // Prepare sample HTML content - string inputPath = "sample.html"; - string htmlContent = @" - - - Sample - - -

Hello, Aspose.HTML!

-

This is a test document.

- -"; - File.WriteAllText(inputPath, htmlContent); - - // Load the HTML document - var document = new Aspose.Html.HTMLDocument(inputPath); - - // Set HTML save options with resource handling depth - var htmlSaveOptions = new Aspose.Html.Saving.HTMLSaveOptions(); - htmlSaveOptions.ResourceHandlingOptions.MaxHandlingDepth = 5; - htmlSaveOptions.ResourceHandlingOptions.PageUrlRestriction = Aspose.Html.Saving.UrlRestriction.SameHost; - - // Save as HTML - string htmlOutputPath = "output.html"; - document.Save(htmlOutputPath, htmlSaveOptions); - Console.WriteLine($"HTML saved to: {Path.GetFullPath(htmlOutputPath)}"); - - // Convert to MHTML using Converter - var mhtmlOptions = new Aspose.Html.Saving.MHTMLSaveOptions(); - mhtmlOptions.ResourceHandlingOptions.MaxHandlingDepth = 5; - - string mhtmlOutputPath = "output.mhtml"; - Aspose.Html.Converters.Converter.ConvertHTML(inputPath, mhtmlOptions, mhtmlOutputPath); - Console.WriteLine($"MHTML saved to: {Path.GetFullPath(mhtmlOutputPath)}"); - } - catch (Exception ex) - { - Console.WriteLine("An error occurred: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/website-to-html/specify-output-file-naming-conventions-based-on-source-url-host-and-path-segments.cs b/website-to-html/specify-output-file-naming-conventions-based-on-source-url-host-and-path-segments.cs new file mode 100644 index 0000000..c09125c --- /dev/null +++ b/website-to-html/specify-output-file-naming-conventions-based-on-source-url-host-and-path-segments.cs @@ -0,0 +1,48 @@ +// Specify output file naming conventions based on source URL host and path segments. + +using System; +using System.IO; + +class Program +{ + static void Main() + { + try + { + // Prepare output directory + string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output"); + Directory.CreateDirectory(outputDir); + + // Source URL and HTML content + string sourceUrl = "https://example.com/path/to/page.html"; + string htmlContent = "

Hello World

"; + + // Create HTML document with base URI + using (var document = new Aspose.Html.HTMLDocument(htmlContent, sourceUrl)) + { + // Configure image save options + var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Jpeg); + options.HorizontalResolution = 300; + options.VerticalResolution = 300; + + // Build output file name based on URL host and path segments + Uri uri = new Uri(sourceUrl); + string host = uri.Host; + string[] pathSegments = uri.AbsolutePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); + string safePath = string.Join("_", pathSegments); + string fileName = $"{host}_{safePath}.jpg"; + + string outputPath = Path.Combine(outputDir, fileName); + + // Convert HTML to image + Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); + } + + Console.WriteLine("Conversion completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/website-to-html/specify-user-agent-string-to-mimic-particular-browser-during-website-retrieval.cs b/website-to-html/specify-user-agent-string-to-mimic-particular-browser-during-website-retrieval.cs new file mode 100644 index 0000000..3bfcd2e --- /dev/null +++ b/website-to-html/specify-user-agent-string-to-mimic-particular-browser-during-website-retrieval.cs @@ -0,0 +1,65 @@ +// Specify a user-agent string to mimic a particular browser during website retrieval. + +using System; +using System.Threading; + +class UserAgentHandler : Aspose.Html.Net.MessageHandler +{ + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + context.Request.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0 Safari/537.36"; + Next(context); + } +} + +class Program +{ + static void Main() + { + try + { + string url = "https://example.com"; + + // Configure network service with custom User-Agent handler + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + Aspose.Html.Services.INetworkService network = configuration.GetService(); + network.MessageHandlers.Add(new UserAgentHandler()); + + // Load the document from the URL using the configuration + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) + { + string htmlResult = string.Empty; + + // If the document is already loaded, capture the HTML immediately + if (document.ReadyState == "complete") + { + htmlResult = document.DocumentElement != null ? document.DocumentElement.OuterHTML : string.Empty; + } + else + { + // Otherwise wait for the document to finish loading + using (AutoResetEvent resetEvent = new AutoResetEvent(false)) + { + document.OnReadyStateChange += (sender, e) => + { + if (document.ReadyState == "complete") + { + htmlResult = document.DocumentElement != null ? document.DocumentElement.OuterHTML : string.Empty; + resetEvent.Set(); + } + }; + + // Wait for the load to complete (timeout to avoid indefinite block) + resetEvent.WaitOne(TimeSpan.FromSeconds(30)); + } + } + + Console.WriteLine(htmlResult); + } + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/website-to-html/throttle-network-requests-avoid-overwhelming-target-server-during-large-scale-website-conversion.cs b/website-to-html/throttle-network-requests-avoid-overwhelming-target-server-during-large-scale-website-conversion.cs new file mode 100644 index 0000000..6883184 --- /dev/null +++ b/website-to-html/throttle-network-requests-avoid-overwhelming-target-server-during-large-scale-website-conversion.cs @@ -0,0 +1,51 @@ +// Throttle network requests to avoid overwhelming the target server during large‑scale website conversion. + +using System; +using System.Threading; + +class Program +{ + static void Main() + { + try + { + // Create configuration and add throttling handler + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + Aspose.Html.Services.INetworkService networkService = configuration.GetService(); + networkService.MessageHandlers.Add(new ThrottleHandler()); + + // Prepare request to the target website + Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage("https://example.com"); + + // Load the document using the request and configuration + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(request, configuration)) + { + // Set save options (MHTML format) + Aspose.Html.Saving.MHTMLSaveOptions options = new Aspose.Html.Saving.MHTMLSaveOptions(); + + // Define output path + string outputPath = "output.mhtml"; + + // Convert and save + Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); + } + + Console.WriteLine("Conversion completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} + +// Message handler that introduces a delay between network requests +class ThrottleHandler : Aspose.Html.Net.MessageHandler +{ + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + // Throttle: wait 200 milliseconds before proceeding + Thread.Sleep(200); + Next(context); + } +} \ No newline at end of file diff --git a/website-to-html/throttle_network_requests_avoid_overwhelming_target_server_large_scale_website_conversion.cs b/website-to-html/throttle_network_requests_avoid_overwhelming_target_server_large_scale_website_conversion.cs deleted file mode 100644 index c8f5cc3..0000000 --- a/website-to-html/throttle_network_requests_avoid_overwhelming_target_server_large_scale_website_conversion.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Throttle network requests to avoid overwhelming the target server during large‑scale website conversion. - -using System; - -class ExcludeUrlHandler : Aspose.Html.Net.MessageHandler -{ - private readonly System.Text.RegularExpressions.Regex _excludeRegex = - new System.Text.RegularExpressions.Regex(@"^https?://.*\.png$", System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase); - - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - string url = context.Request.RequestUri.ToString(); - if (_excludeRegex.IsMatch(url)) - { - return; - } - Next(context); - } -} - -class TimeoutHandler : Aspose.Html.Net.MessageHandler -{ - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - context.Request.Timeout = System.TimeSpan.FromSeconds(5); - Next(context); - } -} - -class Program -{ - static void Main() - { - try - { - // Create configuration and obtain network service - var configuration = new Aspose.Html.Configuration(); - var networkService = configuration.GetService(); - - // Add custom message handlers - networkService.MessageHandlers.Add(new ExcludeUrlHandler()); - networkService.MessageHandlers.Add(new TimeoutHandler()); - - // Sample HTML content - string htmlContent = "Sample

Hello, Aspose.HTML!

"; - - // Load document using the configuration - using (var document = new Aspose.Html.HTMLDocument(htmlContent, configuration)) - { - // Set up MHTML save options - var options = new Aspose.Html.Saving.MHTMLSaveOptions(); - - // Output file path - string outputPath = "output.mhtml"; - - // Convert and save - Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); - - Console.WriteLine($"MHTML file saved to: {outputPath}"); - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/website-to-html/use-asynchronous-loading-improve-performance-converting-multiple-websites-concurrently.cs b/website-to-html/use-asynchronous-loading-improve-performance-converting-multiple-websites-concurrently.cs new file mode 100644 index 0000000..5d812f7 --- /dev/null +++ b/website-to-html/use-asynchronous-loading-improve-performance-converting-multiple-websites-concurrently.cs @@ -0,0 +1,64 @@ +// Use asynchronous loading to improve performance when converting multiple websites concurrently. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +class Program +{ + static async Task Main(string[] args) + { + try + { + string[] urls = new string[] + { + "https://example.com", + "https://example.org", + "https://example.net" + }; + + Task[] loadTasks = urls.Select(url => LoadHtmlAsync(url)).ToArray(); + + string[] results = await Task.WhenAll(loadTasks); + + for (int i = 0; i < urls.Length; i++) + { + Console.WriteLine($"Content from {urls[i]}:"); + Console.WriteLine(results[i]); + Console.WriteLine(new string('-', 80)); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + private static Task LoadHtmlAsync(string url) + { + return Task.Run(() => + { + using (System.Threading.AutoResetEvent resetEvent = new System.Threading.AutoResetEvent(false)) + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument()) + { + string htmlResult = string.Empty; + + document.OnReadyStateChange += (sender, e) => + { + if (document.ReadyState == "complete") + { + htmlResult = document.DocumentElement != null ? document.DocumentElement.TextContent : string.Empty; + resetEvent.Set(); + } + }; + + document.Navigate(url); + resetEvent.WaitOne(); + + return htmlResult; + } + }); + } +} \ No newline at end of file diff --git a/website-to-html/use_asynchronous_loading_improve_performance_converting_multiple_websites_concurrently.cs b/website-to-html/use_asynchronous_loading_improve_performance_converting_multiple_websites_concurrently.cs deleted file mode 100644 index 0f9b666..0000000 --- a/website-to-html/use_asynchronous_loading_improve_performance_converting_multiple_websites_concurrently.cs +++ /dev/null @@ -1,198 +0,0 @@ -// Use asynchronous loading to improve performance when converting multiple websites concurrently. - -using System; -using System.IO; -using System.Threading; -using System.Diagnostics; -using System.Collections.Generic; -using System.IO.Compression; - -public class CustomStreamProvider : Aspose.Html.IO.ICreateStreamProvider, IDisposable -{ - private readonly List _streams = new List(); - - public Stream GetStream(string name, string extension) - { - var ms = new MemoryStream(); - _streams.Add(ms); - return ms; - } - - public Stream GetStream(string name, string extension, int page) - { - var ms = new MemoryStream(); - _streams.Add(ms); - return ms; - } - - public void ReleaseStream(Stream stream) - { - // No action needed for in‑memory streams - } - - public void Dispose() - { - foreach (var ms in _streams) - { - ms.Dispose(); - } - _streams.Clear(); - } - - public IReadOnlyList Streams => _streams.AsReadOnly(); -} - -class Program -{ - static void Main() - { - try - { - // Prepare temporary working directory - string tempDir = Path.Combine(Path.GetTempPath(), "AsposeHtmlExample"); - Directory.CreateDirectory(tempDir); - - // 1. Navigate to a URL and print page text - string url = "about:blank"; - using (AutoResetEvent resetEvent = new AutoResetEvent(false)) - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument()) - { - string htmlResult = string.Empty; - document.OnReadyStateChange += (sender, e) => - { - if (document.ReadyState == "complete") - { - htmlResult = document.DocumentElement != null - ? document.DocumentElement.TextContent - : string.Empty; - resetEvent.Set(); - } - }; - document.Navigate(url); - resetEvent.WaitOne(); - Console.WriteLine("Navigated page text: " + htmlResult); - } - - // 2. Prepare a dummy EPUB file - string epubPath = Path.Combine(tempDir, "sample.epub"); - File.WriteAllBytes(epubPath, new byte[0]); // empty file for demo - Stream stream = File.OpenRead(epubPath); - Aspose.Html.Saving.XpsSaveOptions xpsOptions = new Aspose.Html.Saving.XpsSaveOptions(); - - // 3. Custom stream provider for conversion output - CustomStreamProvider provider = new CustomStreamProvider(); - - // 4. Convert EPUB to XPS (may fail with empty file, but we capture timing) - Stopwatch sw = Stopwatch.StartNew(); - try - { - Aspose.Html.Converters.Converter.ConvertEPUB(stream, xpsOptions, provider); - } - catch (Exception ex) - { - Console.WriteLine("ConvertEPUB failed (expected with dummy file): " + ex.Message); - } - sw.Stop(); - Console.WriteLine($"EPUB conversion elapsed: {sw.Elapsed}"); - - // 5. Write first generated stream to file if any - if (provider.Streams.Count > 0) - { - string outputXpsPath = Path.Combine(tempDir, "output.xps"); - using (var outFile = File.Create(outputXpsPath)) - { - provider.Streams[0].Position = 0; - provider.Streams[0].CopyTo(outFile); - } - Console.WriteLine("First XPS stream written to: " + outputXpsPath); - } - - // 6. Create a simple HTML file and save with resource handling options - string htmlFilePath = Path.Combine(tempDir, "sample.html"); - File.WriteAllText(htmlFilePath, "

Hello World

"); - using (Aspose.Html.HTMLDocument htmlDoc = new Aspose.Html.HTMLDocument(htmlFilePath)) - { - Aspose.Html.Saving.HTMLSaveOptions htmlSaveOptions = new Aspose.Html.Saving.HTMLSaveOptions(); - htmlSaveOptions.ResourceHandlingOptions.MaxHandlingDepth = 5; - htmlSaveOptions.ResourceHandlingOptions.PageUrlRestriction = Aspose.Html.Saving.UrlRestriction.SameHost; - string savedHtmlPath = Path.Combine(tempDir, "saved.html"); - htmlDoc.Save(savedHtmlPath, htmlSaveOptions); - Console.WriteLine("HTML saved to: " + savedHtmlPath); - } - - // 7. Create a zip containing a target file - string zipPath = Path.Combine(tempDir, "sample.zip"); - using (FileStream zipToCreate = new FileStream(zipPath, FileMode.Create)) - using (ZipArchive archive = new ZipArchive(zipToCreate, ZipArchiveMode.Update)) - { - var entry = archive.CreateEntry("target.txt"); - using (var entryStream = entry.Open()) - using (var writer = new StreamWriter(entryStream)) - { - writer.Write("Content inside zip"); - } - } - - // 8. Extract specific entries from zip - string extractDir = Path.Combine(Path.GetTempPath(), "AsposeHtmlExtract"); - Directory.CreateDirectory(extractDir); - using (FileStream zipStream = File.OpenRead(zipPath)) - using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Read)) - { - foreach (ZipArchiveEntry entry in archive.Entries) - { - if (entry.FullName.EndsWith("target.txt", StringComparison.OrdinalIgnoreCase)) - { - string entryPath = Path.Combine(extractDir, entry.FullName); - Directory.CreateDirectory(Path.GetDirectoryName(entryPath)); - entry.ExtractToFile(entryPath, true); - Console.WriteLine("Extracted: " + entryPath); - } - } - } - - // 9. Configure network timeout handler - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - Aspose.Html.Services.INetworkService network = configuration.GetService(); - network.MessageHandlers.Add(new TimeoutHandler()); - - // 10. Load extracted HTML (we'll treat target.txt as HTML for demo) - string htmlPath = Directory.GetFiles(extractDir, "target.txt", SearchOption.AllDirectories)[0]; - using (Aspose.Html.HTMLDocument doc = new Aspose.Html.HTMLDocument(htmlPath, configuration)) - { - string pdfPath = Path.Combine(tempDir, "output.pdf"); - Aspose.Html.Rendering.Pdf.PdfDevice device = new Aspose.Html.Rendering.Pdf.PdfDevice(pdfPath); - doc.RenderTo(device); - Console.WriteLine("Rendered PDF to: " + pdfPath); - } - - // 11. Create a document from a request message - string requestUrl = "about:blank"; - Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(requestUrl); - request.Timeout = TimeSpan.FromSeconds(10); - using (Aspose.Html.HTMLDocument requestDoc = new Aspose.Html.HTMLDocument(request)) - { - string outerHtml = ((Aspose.Html.HTMLElement)requestDoc.DocumentElement).OuterHTML; - Console.WriteLine("OuterHTML from request document: " + outerHtml); - } - - // Cleanup - provider.Dispose(); - stream.Dispose(); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } - - // Custom timeout handler as required - class TimeoutHandler : Aspose.Html.Net.MessageHandler - { - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - context.Request.Timeout = TimeSpan.FromSeconds(15); - Next(context); - } - } -} \ No newline at end of file diff --git a/website-to-html/validate_generated_html_against_w3c_standards_and_report_compliance_issues.cs b/website-to-html/validate-generated-html-against-w3c-standards-report-compliance-issues.cs similarity index 71% rename from website-to-html/validate_generated_html_against_w3c_standards_and_report_compliance_issues.cs rename to website-to-html/validate-generated-html-against-w3c-standards-report-compliance-issues.cs index e71122e..ee5ace7 100644 --- a/website-to-html/validate_generated_html_against_w3c_standards_and_report_compliance_issues.cs +++ b/website-to-html/validate-generated-html-against-w3c-standards-report-compliance-issues.cs @@ -1,7 +1,6 @@ // Validate generated HTML against W3C standards and report any compliance issues found. using System; -using System.IO; class Program { @@ -9,29 +8,20 @@ static void Main() { try { - // Prepare a minimal HTML file - string htmlContent = "Test

Hello

"; - string inputPath = Path.Combine(Directory.GetCurrentDirectory(), "sample.html"); - File.WriteAllText(inputPath, htmlContent); + string htmlContent = "Test

Sample

"; + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); - // Load the HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath); - - // Create WebAccessibility and validator Aspose.Html.Accessibility.WebAccessibility webAccessibility = new Aspose.Html.Accessibility.WebAccessibility(); Aspose.Html.Accessibility.AccessibilityValidator validator = webAccessibility.CreateValidator(Aspose.Html.Accessibility.ValidationBuilder.All); - - // Perform validation Aspose.Html.Accessibility.Results.ValidationResult validationResult = validator.Validate(document); - // Output validation results if (!validationResult.Success) { foreach (Aspose.Html.Accessibility.Results.RuleValidationResult detail in validationResult.Details) { if (!detail.Success) { - Console.WriteLine($"{detail.Rule.Code} - {detail.Rule.Description}"); + Console.WriteLine(detail.Rule.Code + ": " + detail.Rule.Description); foreach (Aspose.Html.Accessibility.ITechniqueResult techResult in detail.Errors) { Aspose.Html.Accessibility.IError error = techResult.Error; @@ -47,12 +37,12 @@ static void Main() } else { - Console.WriteLine("Accessibility validation succeeded with no errors."); + Console.WriteLine("HTML is compliant with W3C standards."); } } catch (Exception ex) { - Console.WriteLine($"Error: {ex.Message}"); + Console.WriteLine("Error: " + ex.Message); } } } \ No newline at end of file