From 69d0cfc1e5a3c893b90797bf0031665af9c4f4ba Mon Sep 17 00:00:00 2001 From: agent-aspose-html-examples Date: Fri, 2 Oct 2026 02:24:45 +0500 Subject: [PATCH 1/2] =?UTF-8?q?feat(extract-svg-from-website):=20Add=2026?= =?UTF-8?q?=20and=20remove=2026=20renamed=20Aspose.HTML=20.NET=20C#=20exam?= =?UTF-8?q?ples=20for=20Extract=20Svg=20From=20Website=20=E2=80=94=20Aspos?= =?UTF-8?q?e.HTML=20for=20.NET=2026.8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...eader-configuration-httpclient-requests.cs | 37 +++++++ ...eader_configuration_httpclient_requests.cs | 45 --------- ...oping-list-applying-extraction-workflow.cs | 83 ++++++++++++++++ ...oping_list_applying_extraction_workflow.cs | 78 --------------- ...ocally-avoid-redundant-network-requests.cs | 77 +++++++++++++++ ...ocally_avoid_redundant_network_requests.cs | 52 ---------- ...nore-script-errors-during-page-loading.cs} | 14 +-- ...rl-returns-extracted-inline-svg-strings.cs | 43 ++++++++ ...ns_list_of_extracted_inline_svg_strings.cs | 37 ------- ...-outerhtml-strings-before-writing-files.cs | 58 +++++++++++ ..._outerhtml_strings_before_writing_files.cs | 60 ----------- ...g-files-httpclient-async-getasync-calls.cs | 45 +++++++++ ..._httpclient_asynchronous_getasync_calls.cs | 40 -------- ...s-for-all-extracted-svgs-from-given-url.cs | 53 ++++++++++ ...s_for_all_extracted_svgs_from_given_url.cs | 60 ----------- ...nline-svg-markup-via-outerhtml-property.cs | 41 ++++++++ ...ct_inline_svg_markup_outerhtml_property.cs | 43 -------- ...ents-whose-src-attribute-ends-with-svg.cs} | 30 +++--- ...type-inline-or-external-saved-file-name.cs | 57 +++++++++++ ...vg_type_inline_external_saved_file_name.cs | 95 ------------------ ...fy-img-elements-dom-via-document-images.cs | 25 +++++ ...ll_img_elements_dom_via_document_images.cs | 40 -------- ...traction-routine-to-improve-scalability.cs | 99 +++++++++++++++++++ ...raction-when-html-page-cannot-be-loaded.cs | 36 +++++++ ...ownloads-fail-transient-network-errors.cs} | 47 +++++---- ...traction_routine_to_improve_scalability.cs | 99 ------------------- ...raction_when_html_page_cannot_be_loaded.cs | 33 ------- ...> iterate-over-returned-svg-collection.cs} | 20 +++- ...rom-url-using-aspose-html-htmldocument.cs} | 14 +-- ...log-count-external-svgs-processed-page.cs} | 22 +++-- ...line-svgs-found-on-each-processed-page.cs} | 18 ++-- ...ttern-with-source-page-domain-and-index.cs | 52 ++++++++++ ..._including_source_page_domain_and_index.cs | 50 ---------- ...gainst-page-base-url-before-downloading.cs | 33 +++++++ ...gainst_page_base_url_before_downloading.cs | 42 -------- ...ents-with-document-getelementsbytagname.cs | 35 +++++++ ...svg_elements_using_getelementsbytagname.cs | 29 ------ ...up-to-separate-svg-file-using-system-io.cs | 48 +++++++++ ...up_to_separate_svg_file_using_system_io.cs | 45 --------- ...t-prevent-hanging-external-svg-download.cs | 26 +++++ ...nt_hanging_during_external_svg_download.cs | 52 ---------- ...fallback-when-httpclient-download-fails.cs | 58 +++++++++++ ...fallback_when_httpclient_download_fails.cs | 48 --------- ...erms-before-reusing-extracted-svg-files.cs | 60 +++++++++++ ...erms_before_reusing_extracted_svg_files.cs | 70 ------------- 45 files changed, 1061 insertions(+), 1088 deletions(-) create mode 100644 extract-svg-from-website/allow-custom-user-agent-header-configuration-httpclient-requests.cs delete mode 100644 extract-svg-from-website/allow_custom_user_agent_header_configuration_httpclient_requests.cs create mode 100644 extract-svg-from-website/batch-process-multiple-page-urls-looping-list-applying-extraction-workflow.cs delete mode 100644 extract-svg-from-website/batch_process_multiple_page_urls_looping_list_applying_extraction_workflow.cs create mode 100644 extract-svg-from-website/cache-external-svg-files-locally-avoid-redundant-network-requests.cs delete mode 100644 extract-svg-from-website/cache_downloaded_external_svg_files_locally_avoid_redundant_network_requests.cs rename extract-svg-from-website/{configure_html_document_ignore_script_errors_page_loading.cs => configure-htmldocument-ignore-script-errors-during-page-loading.cs} (57%) create mode 100644 extract-svg-from-website/create-reusable-method-accepts-page-url-returns-extracted-inline-svg-strings.cs delete mode 100644 extract-svg-from-website/create_reusable_method_accepts_page_url_returns_list_of_extracted_inline_svg_strings.cs create mode 100644 extract-svg-from-website/detect-skip-duplicate-svg-markup-comparing-outerhtml-strings-before-writing-files.cs delete mode 100644 extract-svg-from-website/detect_and_skip_duplicate_svg_markup_comparing_outerhtml_strings_before_writing_files.cs create mode 100644 extract-svg-from-website/download-svg-files-httpclient-async-getasync-calls.cs delete mode 100644 extract-svg-from-website/download_external_svg_files_httpclient_asynchronous_getasync_calls.cs create mode 100644 extract-svg-from-website/expose-public-api-method-returns-collection-of-file-paths-for-all-extracted-svgs-from-given-url.cs delete mode 100644 extract-svg-from-website/expose_public_api_method_returns_collection_of_file_paths_for_all_extracted_svgs_from_given_url.cs create mode 100644 extract-svg-from-website/extract-inline-svg-markup-via-outerhtml-property.cs delete mode 100644 extract-svg-from-website/extract_inline_svg_markup_outerhtml_property.cs rename extract-svg-from-website/{filter_img_collection_keep_elements_src_attribute_ends_with_svg.cs => filter-img-collection-keep-only-elements-whose-src-attribute-ends-with-svg.cs} (54%) create mode 100644 extract-svg-from-website/generate-summary-csv-file-listing-source-page-url-svg-type-inline-or-external-saved-file-name.cs delete mode 100644 extract-svg-from-website/generate_summary_csv_listing_source_page_url_svg_type_inline_external_saved_file_name.cs create mode 100644 extract-svg-from-website/identify-img-elements-dom-via-document-images.cs delete mode 100644 extract-svg-from-website/identify_all_img_elements_dom_via_document_images.cs create mode 100644 extract-svg-from-website/implement-asynchronous-version-of-extraction-routine-to-improve-scalability.cs create mode 100644 extract-svg-from-website/implement-error-handling-skip-extraction-when-html-page-cannot-be-loaded.cs rename extract-svg-from-website/{implement_retry_logic_for_external_svg_downloads_transient_network_errors.cs => implement-retry-logic-external-svg-downloads-fail-transient-network-errors.cs} (52%) delete mode 100644 extract-svg-from-website/implement_asynchronous_extraction_routine_to_improve_scalability.cs delete mode 100644 extract-svg-from-website/implement_error_handling_skip_extraction_when_html_page_cannot_be_loaded.cs rename extract-svg-from-website/{iterate_over_returned_svg_collection.cs => iterate-over-returned-svg-collection.cs} (52%) rename extract-svg-from-website/{load_html_page_from_url_using_aspose_html_htmldocument_class.cs => load-html-page-from-url-using-aspose-html-htmldocument.cs} (50%) rename extract-svg-from-website/{log_count_external_svgs_found_each_processed_page.cs => log-count-external-svgs-processed-page.cs} (51%) rename extract-svg-from-website/{log_inline_svg_count_per_processed_page.cs => log-count-of-inline-svgs-found-on-each-processed-page.cs} (58%) create mode 100644 extract-svg-from-website/option-rename-saved-svg-files-using-pattern-with-source-page-domain-and-index.cs delete mode 100644 extract-svg-from-website/provide_option_rename_saved_svg_files_pattern_including_source_page_domain_and_index.cs create mode 100644 extract-svg-from-website/resolve-relative-svg-urls-against-page-base-url-before-downloading.cs delete mode 100644 extract-svg-from-website/resolve_relative_svg_urls_against_page_base_url_before_downloading.cs create mode 100644 extract-svg-from-website/retrieve-all-inline-svg-elements-with-document-getelementsbytagname.cs delete mode 100644 extract-svg-from-website/retrieve_all_inline_svg_elements_using_getelementsbytagname.cs create mode 100644 extract-svg-from-website/save-each-extracted-inline-svg-markup-to-separate-svg-file-using-system-io.cs delete mode 100644 extract-svg-from-website/save_each_extracted_inline_svg_markup_to_separate_svg_file_using_system_io.cs create mode 100644 extract-svg-from-website/set-timeout-httpclient-prevent-hanging-external-svg-download.cs delete mode 100644 extract-svg-from-website/set_timeout_on_httpclient_to_prevent_hanging_during_external_svg_download.cs create mode 100644 extract-svg-from-website/use-webclient-fallback-when-httpclient-download-fails.cs delete mode 100644 extract-svg-from-website/use_webclient_fallback_when_httpclient_download_fails.cs create mode 100644 extract-svg-from-website/verify-copyright-usage-terms-before-reusing-extracted-svg-files.cs delete mode 100644 extract-svg-from-website/verify_copyright_usage_terms_before_reusing_extracted_svg_files.cs diff --git a/extract-svg-from-website/allow-custom-user-agent-header-configuration-httpclient-requests.cs b/extract-svg-from-website/allow-custom-user-agent-header-configuration-httpclient-requests.cs new file mode 100644 index 0000000..884dde4 --- /dev/null +++ b/extract-svg-from-website/allow-custom-user-agent-header-configuration-httpclient-requests.cs @@ -0,0 +1,37 @@ +// Allow custom User-Agent header configuration for HttpClient requests. + +using System; + +class UserAgentHandler : Aspose.Html.Net.MessageHandler +{ + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + context.Request.Headers["User-Agent"] = "MyCustomUserAgent/1.0"; + Next(context); + } +} + +class Program +{ + static void Main() + { + try + { + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + Aspose.Html.Services.INetworkService network = configuration.GetService(); + network.MessageHandlers.Add(new UserAgentHandler()); + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument("https://example.com", configuration)) + { + Aspose.Html.Saving.PdfSaveOptions options = new Aspose.Html.Saving.PdfSaveOptions(); + Aspose.Html.Converters.Converter.ConvertHTML(document, options, "output.pdf"); + } + + Console.WriteLine("Conversion completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/allow_custom_user_agent_header_configuration_httpclient_requests.cs b/extract-svg-from-website/allow_custom_user_agent_header_configuration_httpclient_requests.cs deleted file mode 100644 index 4a6da98..0000000 --- a/extract-svg-from-website/allow_custom_user_agent_header_configuration_httpclient_requests.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Allow custom User-Agent header configuration for HttpClient requests. - -using System; -using Aspose.Html; -using Aspose.Html.Net; -using Aspose.Html.Services; -using Aspose.Html.Saving; -using Aspose.Html.Converters; - -class UserAgentHandler : Aspose.Html.Net.MessageHandler -{ - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - context.Request.Headers["User-Agent"] = "MyCustomUserAgent/1.0"; - Next(context); - } -} - -class Program -{ - static void Main(string[] args) - { - try - { - // Create configuration and add custom User-Agent handler - var configuration = new Aspose.Html.Configuration(); - var network = configuration.GetService(); - network.MessageHandlers.Add(new UserAgentHandler()); - - // Load HTML document from a URL using the custom configuration - using var document = new Aspose.Html.HTMLDocument("https://example.com", configuration); - - // Convert the document to PDF - var options = new Aspose.Html.Saving.PdfSaveOptions(); - string outputPath = "output.pdf"; - 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/extract-svg-from-website/batch-process-multiple-page-urls-looping-list-applying-extraction-workflow.cs b/extract-svg-from-website/batch-process-multiple-page-urls-looping-list-applying-extraction-workflow.cs new file mode 100644 index 0000000..246db49 --- /dev/null +++ b/extract-svg-from-website/batch-process-multiple-page-urls-looping-list-applying-extraction-workflow.cs @@ -0,0 +1,83 @@ +// Batch process multiple page URLs by looping through a list and applying the extraction workflow. + +using System; +using System.IO; +using System.Collections.Generic; +using System.Text.Json; +using Aspose.Html; +using Aspose.Html.Dom; +using Aspose.Html.Collections; +using Aspose.Html.IO; + +class OutlineNode +{ + public string Text { get; set; } + public int Level { get; set; } + public List Children { get; set; } +} + +class Program +{ + static void Main() + { + try + { + string inputFolder = "InputHtml"; + string outputFolder = "OutputJson"; + + if (!Directory.Exists(inputFolder)) + Directory.CreateDirectory(inputFolder); + if (!Directory.Exists(outputFolder)) + Directory.CreateDirectory(outputFolder); + + // Create a sample HTML file if none exist + string[] existingFiles = Directory.GetFiles(inputFolder, "*.html"); + if (existingFiles.Length == 0) + { + string samplePath = Path.Combine(inputFolder, "sample.html"); + string sampleContent = "

Title

Section

Subsection

"; + File.WriteAllText(samplePath, sampleContent); + } + + foreach (string htmlPath in Directory.GetFiles(inputFolder, "*.html")) + { + HTMLDocument document = new HTMLDocument(htmlPath); + var headings = document.QuerySelectorAll("h1, h2, h3, h4, h5, h6"); + var root = new List(); + var stack = new Stack(); + + for (int i = 0; i < headings.Length; i++) + { + HTMLElement element = (HTMLElement)headings[i]; + string tag = element.TagName.ToLower(); + int level = int.Parse(tag.Substring(1)); + + OutlineNode node = new OutlineNode + { + Text = element.TextContent.Trim(), + Level = level, + Children = new List() + }; + + while (stack.Count > 0 && stack.Peek().Level >= level) + stack.Pop(); + + if (stack.Count == 0) + root.Add(node); + else + stack.Peek().Children.Add(node); + + stack.Push(node); + } + + string json = JsonSerializer.Serialize(root, new JsonSerializerOptions { WriteIndented = true }); + string jsonPath = Path.Combine(outputFolder, Path.GetFileNameWithoutExtension(htmlPath) + ".json"); + File.WriteAllText(jsonPath, json); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/batch_process_multiple_page_urls_looping_list_applying_extraction_workflow.cs b/extract-svg-from-website/batch_process_multiple_page_urls_looping_list_applying_extraction_workflow.cs deleted file mode 100644 index 638869f..0000000 --- a/extract-svg-from-website/batch_process_multiple_page_urls_looping_list_applying_extraction_workflow.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Batch process multiple page URLs by looping through a list and applying the extraction workflow. - -using System; -using System.IO; -using System.Collections.Generic; -using System.Text.Json; -using Aspose.Html; - -class OutlineNode -{ - public string Text { get; set; } - public int Level { get; set; } - public List Children { get; set; } -} - -class Program -{ - static void Main() - { - try - { - string outputFolder = "Output"; - if (!Directory.Exists(outputFolder)) - Directory.CreateDirectory(outputFolder); - - string[] urls = new string[] - { - "https://example.com/page1.html", - "https://example.com/page2.html" - }; - - for (int index = 0; index < urls.Length; index++) - { - string url = urls[index]; - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url)) - { - var headings = document.QuerySelectorAll("h1, h2, h3, h4, h5, h6"); - var root = new List(); - var stack = new Stack(); - - for (int i = 0; i < headings.Length; i++) - { - Aspose.Html.HTMLElement element = (Aspose.Html.HTMLElement)headings[i]; - string tag = element.TagName.ToLower(); - int level = int.Parse(tag.Substring(1)); - - var node = new OutlineNode - { - Text = element.TextContent.Trim(), - Level = level, - Children = new List() - }; - - while (stack.Count > 0 && stack.Peek().Level >= level) - stack.Pop(); - - if (stack.Count == 0) - root.Add(node); - else - stack.Peek().Children.Add(node); - - stack.Push(node); - } - - string json = JsonSerializer.Serialize(root, new JsonSerializerOptions { WriteIndented = true }); - string jsonPath = Path.Combine(outputFolder, $"outline_{index + 1}.json"); - File.WriteAllText(jsonPath, json); - } - } - - Console.WriteLine("Processing completed successfully."); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/cache-external-svg-files-locally-avoid-redundant-network-requests.cs b/extract-svg-from-website/cache-external-svg-files-locally-avoid-redundant-network-requests.cs new file mode 100644 index 0000000..6be60c6 --- /dev/null +++ b/extract-svg-from-website/cache-external-svg-files-locally-avoid-redundant-network-requests.cs @@ -0,0 +1,77 @@ +// Cache downloaded external SVG files locally to avoid redundant network requests. + +using System; +using System.IO; +using System.Net.Http; +using Aspose.Html.Dom.Svg; +using Aspose.Html.Saving; +using Aspose.Html.Converters; +using Aspose.Html.Rendering.Image; + +class Program +{ + static void Main() + { + try + { + // Sample SVG URLs + string[] svgUrls = new string[] + { + "https://upload.wikimedia.org/wikipedia/commons/6/6b/Bitmap_VS_SVG.svg", + "https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/acid.svg" + }; + + // Cache directory + string cacheDir = Path.Combine(Directory.GetCurrentDirectory(), "svgCache"); + Directory.CreateDirectory(cacheDir); + + // HttpClient for downloading + using (HttpClient httpClient = new HttpClient()) + { + foreach (string url in svgUrls) + { + // Determine local file name + string fileName = Path.GetFileName(new Uri(url).AbsolutePath); + if (string.IsNullOrEmpty(fileName)) + { + fileName = Guid.NewGuid().ToString() + ".svg"; + } + + string localPath = Path.Combine(cacheDir, fileName); + + // Download if not cached + if (!File.Exists(localPath)) + { + byte[] data = httpClient.GetByteArrayAsync(url).Result; + File.WriteAllBytes(localPath, data); + Console.WriteLine($"Downloaded and cached: {url}"); + } + else + { + Console.WriteLine($"Using cached file for: {url}"); + } + + // Load SVG content + string svgContent = File.ReadAllText(localPath); + string baseUri = new Uri(localPath).AbsoluteUri; + + // Prepare output image path + string outputImagePath = Path.Combine(Directory.GetCurrentDirectory(), + Path.GetFileNameWithoutExtension(fileName) + ".png"); + + // Set image save options + ImageSaveOptions options = new ImageSaveOptions(); + options.Format = ImageFormat.Png; + + // Convert SVG to PNG + Aspose.Html.Converters.Converter.ConvertSVG(svgContent, baseUri, options, outputImagePath); + Console.WriteLine($"Converted to PNG: {outputImagePath}"); + } + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/cache_downloaded_external_svg_files_locally_avoid_redundant_network_requests.cs b/extract-svg-from-website/cache_downloaded_external_svg_files_locally_avoid_redundant_network_requests.cs deleted file mode 100644 index 3e36ba0..0000000 --- a/extract-svg-from-website/cache_downloaded_external_svg_files_locally_avoid_redundant_network_requests.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Cache downloaded external SVG files locally to avoid redundant network requests. - -using System; -using System.IO; -using System.Net.Http; -using Aspose.Html.Dom.Svg; - -class Program -{ - static void Main() - { - try - { - // URL of the external SVG - string svgUrl = "https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg"; - - // Local cache folder - string cacheFolder = "Cache"; - Directory.CreateDirectory(cacheFolder); - - // Local cached file path - string cachedFileName = "cached.svg"; - string cachedFilePath = Path.Combine(cacheFolder, cachedFileName); - - // Download and cache the SVG if not already cached - if (!File.Exists(cachedFilePath)) - { - using (HttpClient client = new HttpClient()) - { - byte[] data = client.GetByteArrayAsync(svgUrl).Result; - File.WriteAllBytes(cachedFilePath, data); - } - } - - // Base URI for the SVG document (folder containing the cached file) - string baseUri = new Uri(Path.GetFullPath(cacheFolder) + Path.DirectorySeparatorChar).AbsoluteUri; - - // Load the SVG document using the cached file and base URI - using (SVGDocument doc = new SVGDocument(cachedFilePath, baseUri)) - { - // Save the SVG to an output file - string outputPath = "output.svg"; - doc.Save(outputPath); - Console.WriteLine("SVG saved to: " + Path.GetFullPath(outputPath)); - } - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/configure_html_document_ignore_script_errors_page_loading.cs b/extract-svg-from-website/configure-htmldocument-ignore-script-errors-during-page-loading.cs similarity index 57% rename from extract-svg-from-website/configure_html_document_ignore_script_errors_page_loading.cs rename to extract-svg-from-website/configure-htmldocument-ignore-script-errors-during-page-loading.cs index dbdce26..3a6bfca 100644 --- a/extract-svg-from-website/configure_html_document_ignore_script_errors_page_loading.cs +++ b/extract-svg-from-website/configure-htmldocument-ignore-script-errors-during-page-loading.cs @@ -8,24 +8,24 @@ static void Main() { try { - string inputPath = "input.html"; + string inputPath = "sample.html"; string outputPath = "output.html"; - // Create a minimal HTML file with a script that throws an error if (!System.IO.File.Exists(inputPath)) { - System.IO.File.WriteAllText(inputPath, - "

Hello World

"); + string sampleHtml = "Test

Hello World

"; + System.IO.File.WriteAllText(inputPath, sampleHtml); } - // Configure the HTML engine to allow script execution (errors will be ignored) Aspose.Html.Configuration config = new Aspose.Html.Configuration(); config.Security |= Aspose.Html.Sandbox.Scripts; - // Load the document with the configured settings Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath, config); - // Save the processed document + var bodyCollection = document.GetElementsByTagName("body"); + var body = (Aspose.Html.HTMLElement)bodyCollection[0]; + body.Style.BackgroundColor = "lightgray"; + document.Save(outputPath); } catch (System.Exception ex) diff --git a/extract-svg-from-website/create-reusable-method-accepts-page-url-returns-extracted-inline-svg-strings.cs b/extract-svg-from-website/create-reusable-method-accepts-page-url-returns-extracted-inline-svg-strings.cs new file mode 100644 index 0000000..792ef36 --- /dev/null +++ b/extract-svg-from-website/create-reusable-method-accepts-page-url-returns-extracted-inline-svg-strings.cs @@ -0,0 +1,43 @@ +// Create a reusable method that accepts a page URL and returns a list of extracted inline SVG strings. + +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Html; + +class Program +{ + static void Main() + { + try + { + string htmlPath = "sample.html"; + string htmlContent = ""; + File.WriteAllText(htmlPath, htmlContent); + + List svgs = ExtractInlineSvgs(htmlPath); + Console.WriteLine($"Extracted {svgs.Count} SVG(s)."); + foreach (string svg in svgs) + { + Console.WriteLine(svg); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + static List ExtractInlineSvgs(string pageUrl) + { + var document = new Aspose.Html.HTMLDocument(pageUrl); + var svgs = document.GetElementsByTagName("svg"); + var result = new List(); + for (int i = 0; i < svgs.Length; i++) + { + var svgElement = (Aspose.Html.HTMLElement)svgs[i]; + result.Add(svgElement.OuterHTML); + } + return result; + } +} \ No newline at end of file diff --git a/extract-svg-from-website/create_reusable_method_accepts_page_url_returns_list_of_extracted_inline_svg_strings.cs b/extract-svg-from-website/create_reusable_method_accepts_page_url_returns_list_of_extracted_inline_svg_strings.cs deleted file mode 100644 index f137a5e..0000000 --- a/extract-svg-from-website/create_reusable_method_accepts_page_url_returns_list_of_extracted_inline_svg_strings.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Create a reusable method that accepts a page URL and returns a list of extracted inline SVG strings. - -public class Program -{ - public static void Main() - { - try - { - string url = "https://example.com"; - var svgs = ExtractInlineSvgs(url); - System.Console.WriteLine($"Extracted {svgs.Count} SVG(s) from {url}"); - for (int i = 0; i < svgs.Count; i++) - { - System.Console.WriteLine($"SVG {i}:"); - System.Console.WriteLine(svgs[i]); - } - } - catch (System.Exception ex) - { - System.Console.WriteLine($"Error: {ex.Message}"); - } - } - - public static System.Collections.Generic.List ExtractInlineSvgs(string pageUrl) - { - var svgList = new System.Collections.Generic.List(); - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(pageUrl); - Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); - for (int i = 0; i < svgs.Length; i++) - { - Aspose.Html.HTMLElement svgElement = (Aspose.Html.HTMLElement)svgs[i]; - string markup = svgElement.OuterHTML; - svgList.Add(markup); - } - return svgList; - } -} \ No newline at end of file diff --git a/extract-svg-from-website/detect-skip-duplicate-svg-markup-comparing-outerhtml-strings-before-writing-files.cs b/extract-svg-from-website/detect-skip-duplicate-svg-markup-comparing-outerhtml-strings-before-writing-files.cs new file mode 100644 index 0000000..6842d8f --- /dev/null +++ b/extract-svg-from-website/detect-skip-duplicate-svg-markup-comparing-outerhtml-strings-before-writing-files.cs @@ -0,0 +1,58 @@ +// Detect and skip duplicate SVG markup by comparing OuterHTML strings before writing files. + +using System; + +class Program +{ + static void Main() + { + try + { + // Sample HTML containing duplicate SVG markup + string htmlContent = "" + + "" + + "

Some text

" + + "" + // duplicate + "" + + ""; + + // Load HTML from inline content using two‑argument constructor + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Get all SVG elements + Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); + + // Track seen SVG markup to skip duplicates + System.Collections.Generic.HashSet seenMarkups = new System.Collections.Generic.HashSet(); + + // Prepare output directory + string outputDir = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "output"); + System.IO.Directory.CreateDirectory(outputDir); + + int savedIndex = 0; + + for (int i = 0; i < svgs.Length; i++) + { + Aspose.Html.HTMLElement svgElement = (Aspose.Html.HTMLElement)svgs[i]; + string markup = svgElement.OuterHTML; + + // Skip if this markup has already been processed + if (!seenMarkups.Add(markup)) + { + continue; + } + + string outputPath = System.IO.Path.Combine(outputDir, $"svg_{savedIndex}.svg"); + Aspose.Html.Dom.Svg.SVGDocument svgDoc = new Aspose.Html.Dom.Svg.SVGDocument(markup, "about:blank"); + svgDoc.Save(outputPath); + savedIndex++; + } + + Console.WriteLine($"Extracted {savedIndex} unique SVG(s) to \"{outputDir}\"."); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/detect_and_skip_duplicate_svg_markup_comparing_outerhtml_strings_before_writing_files.cs b/extract-svg-from-website/detect_and_skip_duplicate_svg_markup_comparing_outerhtml_strings_before_writing_files.cs deleted file mode 100644 index 10e6b5d..0000000 --- a/extract-svg-from-website/detect_and_skip_duplicate_svg_markup_comparing_outerhtml_strings_before_writing_files.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Detect and skip duplicate SVG markup by comparing OuterHTML strings before writing files. - -using System; -using System.IO; -using System.Collections.Generic; -using Aspose.Html; -using Aspose.Html.Collections; -using Aspose.Html.Dom.Svg; - -class Program -{ - static void Main(string[] args) - { - try - { - // Sample HTML containing SVG elements (some duplicates) - string htmlContent = "" + - "" + - "" + - "" + - ""; - - // Load HTML document - HTMLDocument document = new HTMLDocument(htmlContent); - - // Get all SVG elements - HTMLCollection svgs = document.GetElementsByTagName("svg"); - - // Track seen SVG markup to skip duplicates - HashSet seenMarkups = new HashSet(); - - // Ensure output directory exists - string outputDir = "output_svgs"; - Directory.CreateDirectory(outputDir); - - // Iterate through SVG elements - for (int i = 0; i < svgs.Length; i++) - { - HTMLElement svgElement = (HTMLElement)svgs[i]; - string markup = svgElement.OuterHTML; - - // Skip if this markup has already been processed - if (!seenMarkups.Add(markup)) - continue; - - // Define output file path - string fileName = $"svg_{i}.svg"; - string outputPath = Path.Combine(outputDir, fileName); - - // Create SVG document from markup and save - SVGDocument svgDoc = new SVGDocument(markup, ""); - svgDoc.Save(outputPath); - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/download-svg-files-httpclient-async-getasync-calls.cs b/extract-svg-from-website/download-svg-files-httpclient-async-getasync-calls.cs new file mode 100644 index 0000000..ee819eb --- /dev/null +++ b/extract-svg-from-website/download-svg-files-httpclient-async-getasync-calls.cs @@ -0,0 +1,45 @@ +// Download external SVG files using HttpClient with asynchronous GetAsync calls. + +using System; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +class Program +{ + static async Task Main(string[] args) + { + try + { + HttpClient httpClient = new HttpClient(); + + string[] svgUrls = new string[] + { + "https://example.com/sample1.svg", + "https://example.com/sample2.svg" + }; + + for (int i = 0; i < svgUrls.Length; i++) + { + HttpResponseMessage response = await httpClient.GetAsync(svgUrls[i]); + response.EnsureSuccessStatusCode(); + + string svgContent = await response.Content.ReadAsStringAsync(); + string baseUri = svgUrls[i]; + + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), $"output{i}.pdf"); + PdfSaveOptions options = new PdfSaveOptions(); + + Aspose.Html.Converters.Converter.ConvertSVG(svgContent, baseUri, options, outputPath); + + Console.WriteLine($"Saved PDF to {outputPath}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/download_external_svg_files_httpclient_asynchronous_getasync_calls.cs b/extract-svg-from-website/download_external_svg_files_httpclient_asynchronous_getasync_calls.cs deleted file mode 100644 index 9b9f8b9..0000000 --- a/extract-svg-from-website/download_external_svg_files_httpclient_asynchronous_getasync_calls.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Download external SVG files using HttpClient with asynchronous GetAsync calls. - -using System; -using System.IO; -using System.Net.Http; - -class Program -{ - static void Main() - { - try - { - string[] svgUrls = new string[] - { - "https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/acid.svg", - "https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/helloworld.svg" - }; - - using (HttpClient client = new HttpClient()) - { - for (int i = 0; i < svgUrls.Length; i++) - { - string url = svgUrls[i]; - string svgContent = client.GetStringAsync(url).GetAwaiter().GetResult(); - string baseUri = url; - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), $"output_{i}.pdf"); - - Aspose.Html.Saving.PdfSaveOptions options = new Aspose.Html.Saving.PdfSaveOptions(); - Aspose.Html.Converters.Converter.ConvertSVG(svgContent, baseUri, options, outputPath); - } - } - - Console.WriteLine("SVG files downloaded and converted successfully."); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/expose-public-api-method-returns-collection-of-file-paths-for-all-extracted-svgs-from-given-url.cs b/extract-svg-from-website/expose-public-api-method-returns-collection-of-file-paths-for-all-extracted-svgs-from-given-url.cs new file mode 100644 index 0000000..cae598c --- /dev/null +++ b/extract-svg-from-website/expose-public-api-method-returns-collection-of-file-paths-for-all-extracted-svgs-from-given-url.cs @@ -0,0 +1,53 @@ +// Expose a public API method that returns a collection of file paths for all extracted SVGs from a given URL. + +using System; +using System.Collections.Generic; +using System.IO; + +class Program +{ + static void Main() + { + try + { + string url = "https://example.com"; + string outputFolder = "SvgsOutput"; + List svgFiles = ExtractSvgs(url, outputFolder); + Console.WriteLine("Extracted SVG files:"); + foreach (string file in svgFiles) + { + Console.WriteLine(file); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + public static List ExtractSvgs(string url, string outputFolder) + { + if (!Directory.Exists(outputFolder)) + { + Directory.CreateDirectory(outputFolder); + } + + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url); + Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); + List result = new List(); + + for (int i = 0; i < svgs.Length; i++) + { + Aspose.Html.HTMLElement svgElement = svgs[i] as Aspose.Html.HTMLElement; + if (svgElement == null) + continue; + + string svgContent = svgElement.OuterHTML; + string filePath = Path.Combine(outputFolder, $"{i}.svg"); + File.WriteAllText(filePath, svgContent); + result.Add(filePath); + } + + return result; + } +} \ No newline at end of file diff --git a/extract-svg-from-website/expose_public_api_method_returns_collection_of_file_paths_for_all_extracted_svgs_from_given_url.cs b/extract-svg-from-website/expose_public_api_method_returns_collection_of_file_paths_for_all_extracted_svgs_from_given_url.cs deleted file mode 100644 index 3ee78a4..0000000 --- a/extract-svg-from-website/expose_public_api_method_returns_collection_of_file_paths_for_all_extracted_svgs_from_given_url.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Expose a public API method that returns a collection of file paths for all extracted SVGs from a given URL. - -using System; -using System.Collections.Generic; -using System.IO; -using Aspose.Html; -using Aspose.Html.Collections; -using Aspose.Html.Dom; - -class Program -{ - static void Main() - { - try - { - string url = "https://example.com/sample.html"; - string outputFolder = "ExtractedSvgs"; - - List svgFiles = ExtractSvgFiles(url, outputFolder); - - Console.WriteLine("Extracted SVG files:"); - foreach (string path in svgFiles) - { - Console.WriteLine(path); - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } - - public static List ExtractSvgFiles(string url, string outputFolder) - { - if (!Directory.Exists(outputFolder)) - { - Directory.CreateDirectory(outputFolder); - } - - var document = new Aspose.Html.HTMLDocument(url); - HTMLCollection svgs = document.GetElementsByTagName("svg"); - - var result = new List(); - - for (int i = 0; i < svgs.Length; i++) - { - var element = svgs[i] as Aspose.Html.HTMLElement; - if (element == null) - continue; - - string svgContent = element.OuterHTML; - string fileName = $"{i}.svg"; - string filePath = Path.Combine(outputFolder, fileName); - File.WriteAllText(filePath, svgContent); - result.Add(filePath); - } - - return result; - } -} \ No newline at end of file diff --git a/extract-svg-from-website/extract-inline-svg-markup-via-outerhtml-property.cs b/extract-svg-from-website/extract-inline-svg-markup-via-outerhtml-property.cs new file mode 100644 index 0000000..c82fd31 --- /dev/null +++ b/extract-svg-from-website/extract-inline-svg-markup-via-outerhtml-property.cs @@ -0,0 +1,41 @@ +// Extract each inline SVG's markup via the OuterHTML property. + +using System; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "" + + "" + + "" + + "" + + "

Sample paragraph.

" + + "" + + "" + + "" + + ""; + + // Load HTML from inline content + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Get all inline SVG elements + Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); + + for (int i = 0; i < svgs.Length; i++) + { + Aspose.Html.HTMLElement svgElement = (Aspose.Html.HTMLElement)svgs[i]; + string markup = svgElement.OuterHTML; + System.Console.WriteLine($"--- SVG {i} markup ---"); + System.Console.WriteLine(markup); + System.Console.WriteLine(); + } + } + catch (Exception ex) + { + System.Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/extract_inline_svg_markup_outerhtml_property.cs b/extract-svg-from-website/extract_inline_svg_markup_outerhtml_property.cs deleted file mode 100644 index 0c12f56..0000000 --- a/extract-svg-from-website/extract_inline_svg_markup_outerhtml_property.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Extract each inline SVG's markup via the OuterHTML property. - -using System; - -public class Program -{ - public static void Main() - { - try - { - // Create a sample HTML file with inline SVGs - string htmlPath = "sample.html"; - string htmlContent = "" + - "" + - "" + - ""; - System.IO.File.WriteAllText(htmlPath, htmlContent); - - // Load the HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath); - - // Get all inline SVG elements - Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); - - for (int i = 0; i < svgs.Length; i++) - { - Aspose.Html.HTMLElement svgElement = (Aspose.Html.HTMLElement)svgs[i]; - string markup = svgElement.OuterHTML; - string outputPath = $"svg_{i}.svg"; - - // Create an SVG document from the markup and save it - Aspose.Html.Dom.Svg.SVGDocument svgDoc = new Aspose.Html.Dom.Svg.SVGDocument(markup, ""); - svgDoc.Save(outputPath); - } - - System.Console.WriteLine("SVG extraction completed."); - } - catch (System.Exception ex) - { - System.Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/filter_img_collection_keep_elements_src_attribute_ends_with_svg.cs b/extract-svg-from-website/filter-img-collection-keep-only-elements-whose-src-attribute-ends-with-svg.cs similarity index 54% rename from extract-svg-from-website/filter_img_collection_keep_elements_src_attribute_ends_with_svg.cs rename to extract-svg-from-website/filter-img-collection-keep-only-elements-whose-src-attribute-ends-with-svg.cs index 97aeed7..74e9997 100644 --- a/extract-svg-from-website/filter_img_collection_keep_elements_src_attribute_ends_with_svg.cs +++ b/extract-svg-from-website/filter-img-collection-keep-only-elements-whose-src-attribute-ends-with-svg.cs @@ -2,6 +2,9 @@ using System; using System.IO; +using Aspose.Html; +using Aspose.Html.Dom; +using Aspose.Html.Collections; class Program { @@ -9,40 +12,35 @@ static void Main() { try { - string htmlPath = "input.html"; - string outputPath = "output.html"; - - // Create a minimal sample HTML file if it does not exist + string htmlPath = "sample.html"; if (!File.Exists(htmlPath)) { - string sampleHtml = "" + - "" + - "" + - "" + + string sampleHtml = "" + + "" + + "" + + "" + + "" + ""; File.WriteAllText(htmlPath, sampleHtml); } - // Load the HTML document Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath); - // Get all elements Aspose.Html.Collections.HTMLCollection images = document.GetElementsByTagName("img"); - // Iterate backwards to safely remove elements for (int i = images.Length - 1; i >= 0; i--) { - Aspose.Html.Dom.Element imgElement = (Aspose.Html.Dom.Element)images[i]; - string src = imgElement.GetAttribute("src"); + Aspose.Html.Dom.Element img = images[i]; + string src = img.GetAttribute("src"); if (src == null || !src.EndsWith(".svg", StringComparison.OrdinalIgnoreCase)) { - // Remove elements whose src does not end with .svg - imgElement.ParentNode.RemoveChild(imgElement); + img.ParentNode.RemoveChild(img); } } - // Save the modified document + string outputPath = "output.html"; document.Save(outputPath); + Console.WriteLine("Filtered HTML saved to: " + outputPath); } catch (Exception ex) { diff --git a/extract-svg-from-website/generate-summary-csv-file-listing-source-page-url-svg-type-inline-or-external-saved-file-name.cs b/extract-svg-from-website/generate-summary-csv-file-listing-source-page-url-svg-type-inline-or-external-saved-file-name.cs new file mode 100644 index 0000000..00104e9 --- /dev/null +++ b/extract-svg-from-website/generate-summary-csv-file-listing-source-page-url-svg-type-inline-or-external-saved-file-name.cs @@ -0,0 +1,57 @@ +// Generate a summary CSV file that lists source page URL, SVG type (inline or external), and saved file name. + +using System; +using System.IO; + +class Program +{ + static void Main() + { + try + { + // Prepare sample HTML with an inline SVG + string htmlContent = ""; + string htmlFilePath = "sample.html"; + File.WriteAllText(htmlFilePath, htmlContent); + + // Load the HTML document + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlFilePath, "about:blank"); + + // Get all SVG elements + Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); + + // Prepare CSV summary file + string csvPath = "summary.csv"; + using (StreamWriter csvWriter = new StreamWriter(csvPath, false)) + { + // Write CSV header + csvWriter.WriteLine("SourcePageUrl,SVGType,FileName"); + + string sourceUrl = Path.GetFullPath(htmlFilePath); + + for (int i = 0; i < svgs.Length; i++) + { + Aspose.Html.HTMLElement svgElement = (Aspose.Html.HTMLElement)svgs[i]; + string svgContent = svgElement.OuterHTML; + string fileName = $"svg_{i}.svg"; + + // Save SVG to file + Aspose.Html.Dom.Svg.SVGDocument svgDoc = new Aspose.Html.Dom.Svg.SVGDocument(svgContent, "about:blank"); + svgDoc.Save(fileName); + + // Determine SVG type (inline in this example) + string svgType = "inline"; + + // Write CSV line + csvWriter.WriteLine($"{sourceUrl},{svgType},{fileName}"); + } + } + + Console.WriteLine("SVG extraction and CSV summary completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/generate_summary_csv_listing_source_page_url_svg_type_inline_external_saved_file_name.cs b/extract-svg-from-website/generate_summary_csv_listing_source_page_url_svg_type_inline_external_saved_file_name.cs deleted file mode 100644 index 2a6bedb..0000000 --- a/extract-svg-from-website/generate_summary_csv_listing_source_page_url_svg_type_inline_external_saved_file_name.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Generate a summary CSV file that lists source page URL, SVG type (inline or external), and saved file name. - -using System; -using System.IO; -using System.Net.Http; -using Aspose.Html; -using Aspose.Html.Collections; -using Aspose.Html.Dom.Svg; - -class Program -{ - static void Main() - { - try - { - // Prepare sample HTML and external SVG files - string outputDir = "output"; - Directory.CreateDirectory(outputDir); - - string htmlPath = Path.Combine(outputDir, "sample.html"); - string externalSvgPath = Path.Combine(outputDir, "external.svg"); - - string htmlContent = @" - - -Sample - -

Inline SVG

- - - -

External SVG

- External SVG - -"; - File.WriteAllText(htmlPath, htmlContent); - - string externalSvgContent = @""; - File.WriteAllText(externalSvgPath, externalSvgContent); - - // Load the HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath); - - // Prepare CSV writer - string csvPath = Path.Combine(outputDir, "summary.csv"); - using (System.IO.StreamWriter csvWriter = new System.IO.StreamWriter(csvPath, false)) - { - csvWriter.WriteLine("SourceUrl,SvgType,FileName"); - - // Process inline SVG elements - Aspose.Html.Collections.HTMLCollection inlineSvgs = document.GetElementsByTagName("svg"); - for (int i = 0; i < inlineSvgs.Length; i++) - { - Aspose.Html.HTMLElement svgElement = (Aspose.Html.HTMLElement)inlineSvgs[i]; - string svgContent = svgElement.OuterHTML; - string fileName = $"inline_{i}.svg"; - string filePath = Path.Combine(outputDir, fileName); - - Aspose.Html.Dom.Svg.SVGDocument svgDoc = new Aspose.Html.Dom.Svg.SVGDocument(svgContent, string.Empty); - svgDoc.Save(filePath); - - csvWriter.WriteLine($"{htmlPath},Inline,{fileName}"); - } - - // Process external SVG references (e.g., ) - Aspose.Html.Collections.HTMLCollection imgElements = document.GetElementsByTagName("img"); - for (int i = 0; i < imgElements.Length; i++) - { - Aspose.Html.HTMLElement imgElement = (Aspose.Html.HTMLElement)imgElements[i]; - string src = imgElement.GetAttribute("src"); - if (string.IsNullOrEmpty(src)) - continue; - if (!src.EndsWith(".svg", StringComparison.OrdinalIgnoreCase)) - continue; - - string externalUrl = Path.Combine(outputDir, src); - if (!File.Exists(externalUrl)) - continue; - - string fileName = $"external_{i}.svg"; - string destPath = Path.Combine(outputDir, fileName); - File.Copy(externalUrl, destPath, true); - - csvWriter.WriteLine($"{htmlPath},External,{fileName}"); - } - } - - Console.WriteLine("SVG extraction and CSV summary completed successfully."); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/identify-img-elements-dom-via-document-images.cs b/extract-svg-from-website/identify-img-elements-dom-via-document-images.cs new file mode 100644 index 0000000..4452da6 --- /dev/null +++ b/extract-svg-from-website/identify-img-elements-dom-via-document-images.cs @@ -0,0 +1,25 @@ +// Identify all elements in the DOM via document.Images. + +using System; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "

Sample

First

Text

"; + var document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + Aspose.Html.Collections.HTMLCollection images = document.Images; + foreach (Aspose.Html.Dom.Element img in images) + { + string src = img.GetAttribute("src"); + Console.WriteLine("Image src: " + src); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/identify_all_img_elements_dom_via_document_images.cs b/extract-svg-from-website/identify_all_img_elements_dom_via_document_images.cs deleted file mode 100644 index 1b4f9e2..0000000 --- a/extract-svg-from-website/identify_all_img_elements_dom_via_document_images.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Identify all elements in the DOM via document.Images. - -using System; -using System.IO; - -class Program -{ - static void Main() - { - try - { - // Sample HTML content containing elements - string htmlContent = "

Sample text

"; - string inputFile = "sample.html"; - - // Write the sample HTML to a file - File.WriteAllText(inputFile, htmlContent); - - // Load the HTML document - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputFile)) - { - // Get all elements via the Images collection - Aspose.Html.Collections.HTMLCollection images = document.Images; - - Console.WriteLine($"Found {images.Length} element(s) in the document."); - - foreach (Aspose.Html.Dom.Element img in images) - { - // Retrieve the 'src' attribute of each image - string src = img.GetAttribute("src"); - Console.WriteLine($"Image src: {src}"); - } - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/implement-asynchronous-version-of-extraction-routine-to-improve-scalability.cs b/extract-svg-from-website/implement-asynchronous-version-of-extraction-routine-to-improve-scalability.cs new file mode 100644 index 0000000..d664c26 --- /dev/null +++ b/extract-svg-from-website/implement-asynchronous-version-of-extraction-routine-to-improve-scalability.cs @@ -0,0 +1,99 @@ +// Implement an asynchronous version of the extraction routine to improve scalability. + +using System; +using System.IO; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Diagnostics; + +class MemoryStreamProvider : Aspose.Html.IO.ICreateStreamProvider, IDisposable +{ + private readonly List _streams = new List(); + + public IReadOnlyList Streams => _streams.AsReadOnly(); + + 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) + { + if (stream != null) + { + stream.Flush(); + } + } + + public void Dispose() + { + foreach (var ms in _streams) + { + ms.Dispose(); + } + _streams.Clear(); + } +} + +class Program +{ + static async Task Main() + { + try + { + string inputPath = "sample.epub"; + string outputPath = "output.xps"; + string logPath = "log.txt"; + + // Ensure log file exists + File.AppendAllText(logPath, $"Conversion started at {DateTime.Now}{Environment.NewLine}"); + + // Open input stream + using (Stream inputStream = File.OpenRead(inputPath)) + { + var options = new Aspose.Html.Saving.XpsSaveOptions(); + + using (var provider = new MemoryStreamProvider()) + { + var start = DateTime.Now; + + await Task.Run(() => + Aspose.Html.Converters.Converter.ConvertEPUB(inputStream, options, provider) + ); + + var end = DateTime.Now; + var elapsed = end - start; + File.AppendAllText(logPath, $"Conversion finished in {elapsed.TotalSeconds} seconds{Environment.NewLine}"); + + if (provider.Streams.Count > 0) + { + var firstStream = provider.Streams[0]; + firstStream.Position = 0; + using (var fileStream = File.Create(outputPath)) + { + firstStream.CopyTo(fileStream); + } + File.AppendAllText(logPath, $"First stream saved to {outputPath}{Environment.NewLine}"); + } + else + { + File.AppendAllText(logPath, "No streams were generated by the conversion." + Environment.NewLine); + } + } + } + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/implement-error-handling-skip-extraction-when-html-page-cannot-be-loaded.cs b/extract-svg-from-website/implement-error-handling-skip-extraction-when-html-page-cannot-be-loaded.cs new file mode 100644 index 0000000..51975c4 --- /dev/null +++ b/extract-svg-from-website/implement-error-handling-skip-extraction-when-html-page-cannot-be-loaded.cs @@ -0,0 +1,36 @@ +// Implement error handling to skip extraction when the HTML page cannot be loaded. + +using System; +using System.Threading; + +class Program +{ + static void Main(string[] args) + { + try + { + string url = "https://example.com/nonexistent.html"; + Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(url); + request.Timeout = System.TimeSpan.FromSeconds(10); + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(request)) + { + Aspose.Html.HTMLElement body = document.Body; + string content = body.TextContent; + Console.WriteLine("Page content:"); + Console.WriteLine(content); + } + } + catch (System.Exception ex) + { + if (ex.Message.Contains("cannot be loaded")) + { + Console.WriteLine("Skipping extraction: page could not be loaded."); + } + else + { + Console.WriteLine(ex.Message); + } + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/implement_retry_logic_for_external_svg_downloads_transient_network_errors.cs b/extract-svg-from-website/implement-retry-logic-external-svg-downloads-fail-transient-network-errors.cs similarity index 52% rename from extract-svg-from-website/implement_retry_logic_for_external_svg_downloads_transient_network_errors.cs rename to extract-svg-from-website/implement-retry-logic-external-svg-downloads-fail-transient-network-errors.cs index 7c75b4e..a234c08 100644 --- a/extract-svg-from-website/implement_retry_logic_for_external_svg_downloads_transient_network_errors.cs +++ b/extract-svg-from-website/implement-retry-logic-external-svg-downloads-fail-transient-network-errors.cs @@ -1,21 +1,6 @@ // Implement retry logic for external SVG downloads that fail due to transient network errors. using System; -using System.IO; - -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 { @@ -23,24 +8,44 @@ static void Main() { try { - string svgContent = ""; - string baseUri = "https://example.com/"; + string svgContent = ""; + string baseUri = "about:blank"; string outputPath = "output.pdf"; Aspose.Html.Saving.PdfSaveOptions options = new Aspose.Html.Saving.PdfSaveOptions(); Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); Aspose.Html.Services.INetworkService network = configuration.GetService(); - network.MessageHandlers.Add(new RetryMessageHandler(3)); + network.MessageHandlers.Add(new RetryHandler(3)); - // Perform conversion (the retry handler will be applied to any network operations during conversion) + // Perform the conversion; the retry handler will intercept network operations. Aspose.Html.Converters.Converter.ConvertSVG(svgContent, baseUri, options, outputPath); - Console.WriteLine("Conversion completed successfully. Output saved to: " + Path.GetFullPath(outputPath)); + Console.WriteLine("SVG successfully converted to PDF."); } catch (Exception ex) { - Console.WriteLine("An error occurred: " + ex.Message); + Console.WriteLine($"Conversion failed: {ex.Message}"); + } + } +} + +class RetryHandler : Aspose.Html.Net.MessageHandler +{ + private readonly int _maxRetries; + + public RetryHandler(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; } } } \ No newline at end of file diff --git a/extract-svg-from-website/implement_asynchronous_extraction_routine_to_improve_scalability.cs b/extract-svg-from-website/implement_asynchronous_extraction_routine_to_improve_scalability.cs deleted file mode 100644 index 1fbda9c..0000000 --- a/extract-svg-from-website/implement_asynchronous_extraction_routine_to_improve_scalability.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Implement an asynchronous version of the extraction routine to improve scalability. - -using System; -using System.IO; -using System.Collections.Generic; -using System.Threading.Tasks; -using System.Diagnostics; - -public class MemoryStreamProvider : Aspose.Html.IO.ICreateStreamProvider, IDisposable -{ - private readonly List _streams = new List(); - - public IReadOnlyList Streams => _streams; - - 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(); - } - } -} - -public class Program -{ - private const string InputPath = "sample.epub"; - private const string OutputPath = "output.xps"; - private const string LogPath = "conversion.log"; - - public static async Task Main(string[] args) - { - try - { - await PerformConversionAsync(InputPath, OutputPath, LogPath); - Console.WriteLine("Conversion completed successfully."); - } - catch (Exception ex) - { - Console.Error.WriteLine($"Error: {ex.Message}"); - } - } - - private static async Task PerformConversionAsync(string inputPath, string outputPath, string logPath) - { - // Ensure input file exists (create a placeholder if missing) - if (!File.Exists(inputPath)) - { - File.WriteAllBytes(inputPath, new byte[0]); - } - - using (Stream stream = File.OpenRead(inputPath)) - { - var options = new Aspose.Html.Saving.XpsSaveOptions(); - var provider = new MemoryStreamProvider(); - - var stopwatch = Stopwatch.StartNew(); - - await Task.Run(() => - { - Aspose.Html.Converters.Converter.ConvertEPUB(stream, options, provider); - }); - - stopwatch.Stop(); - - File.AppendAllText(logPath, $"Conversion duration: {stopwatch.Elapsed}" + Environment.NewLine); - - if (provider.Streams.Count > 0) - { - var firstStream = provider.Streams[0]; - firstStream.Position = 0; - using (var fileStream = File.Create(outputPath)) - { - firstStream.CopyTo(fileStream); - } - } - - provider.Dispose(); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/implement_error_handling_skip_extraction_when_html_page_cannot_be_loaded.cs b/extract-svg-from-website/implement_error_handling_skip_extraction_when_html_page_cannot_be_loaded.cs deleted file mode 100644 index b06d93e..0000000 --- a/extract-svg-from-website/implement_error_handling_skip_extraction_when_html_page_cannot_be_loaded.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Implement error handling to skip extraction when the HTML page cannot be loaded. - -using System; -using Aspose.Html; -using Aspose.Html.Net; - -class Program -{ - static void Main(string[] args) - { - try - { - string url = "https://example.com"; - RequestMessage request = new RequestMessage(url); - request.Timeout = TimeSpan.FromSeconds(10); - HTMLDocument document = new HTMLDocument(request); - HTMLElement body = document.Body; - string content = body.TextContent; - Console.WriteLine(content); - } - catch (Exception ex) - { - if (ex.Message.Contains("timed out")) - { - Console.WriteLine("Skipping extraction due to load failure."); - } - else - { - Console.WriteLine(ex.Message); - } - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/iterate_over_returned_svg_collection.cs b/extract-svg-from-website/iterate-over-returned-svg-collection.cs similarity index 52% rename from extract-svg-from-website/iterate_over_returned_svg_collection.cs rename to extract-svg-from-website/iterate-over-returned-svg-collection.cs index a1e306b..f2ea916 100644 --- a/extract-svg-from-website/iterate_over_returned_svg_collection.cs +++ b/extract-svg-from-website/iterate-over-returned-svg-collection.cs @@ -2,6 +2,9 @@ using System; using System.IO; +using Aspose.Html; +using Aspose.Html.Collections; +using Aspose.Html.Dom; class Program { @@ -11,7 +14,10 @@ static void Main() { // Create a minimal HTML file with SVG elements string htmlPath = "sample.html"; - string htmlContent = "
text
"; + string htmlContent = "" + + "" + + "" + + ""; File.WriteAllText(htmlPath, htmlContent); // Load the HTML document @@ -23,8 +29,16 @@ static void Main() // Iterate over the SVG collection for (int i = 0; i < svgs.Length; i++) { - var node = svgs[i]; - Console.WriteLine($"SVG {i}: NodeName = {node.NodeName}"); + // Cast to HTMLElement to access properties + Aspose.Html.HTMLElement element = svgs[i] as Aspose.Html.HTMLElement; + if (element != null) + { + Console.WriteLine($"SVG {i}: TagName = {element.TagName}"); + } + else + { + Console.WriteLine($"SVG {i}: Unable to cast element."); + } } } catch (Exception ex) diff --git a/extract-svg-from-website/load_html_page_from_url_using_aspose_html_htmldocument_class.cs b/extract-svg-from-website/load-html-page-from-url-using-aspose-html-htmldocument.cs similarity index 50% rename from extract-svg-from-website/load_html_page_from_url_using_aspose_html_htmldocument_class.cs rename to extract-svg-from-website/load-html-page-from-url-using-aspose-html-htmldocument.cs index d447e6f..96fdc76 100644 --- a/extract-svg-from-website/load_html_page_from_url_using_aspose_html_htmldocument_class.cs +++ b/extract-svg-from-website/load-html-page-from-url-using-aspose-html-htmldocument.cs @@ -1,23 +1,23 @@ // Load an HTML page from a URL using Aspose.HTML's HtmlDocument class. +using System; + class Program { static void Main() { try { - string url = "https://www.example.com"; - Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(url); - request.Timeout = System.TimeSpan.FromSeconds(30); - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(request)) + string url = "https://example.com"; + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url)) { string html = document.DocumentElement != null ? document.DocumentElement.OuterHTML : string.Empty; - System.Console.WriteLine(html); + Console.WriteLine(html); } } - catch (System.Exception ex) + catch (Exception ex) { - System.Console.WriteLine(ex.Message); + Console.WriteLine(ex.Message); } } } \ No newline at end of file diff --git a/extract-svg-from-website/log_count_external_svgs_found_each_processed_page.cs b/extract-svg-from-website/log-count-external-svgs-processed-page.cs similarity index 51% rename from extract-svg-from-website/log_count_external_svgs_found_each_processed_page.cs rename to extract-svg-from-website/log-count-external-svgs-processed-page.cs index cf6ffb6..d281694 100644 --- a/extract-svg-from-website/log_count_external_svgs_found_each_processed_page.cs +++ b/extract-svg-from-website/log-count-external-svgs-processed-page.cs @@ -9,24 +9,32 @@ static void Main() { try { - string inputFolder = "input_html"; + string inputFolder = "InputHtml"; if (!Directory.Exists(inputFolder)) Directory.CreateDirectory(inputFolder); - string[] htmlFiles = Directory.GetFiles(inputFolder, "*.html"); - if (htmlFiles.Length == 0) + // Create sample HTML files + string[] sampleFiles = { "page1.html", "page2.html" }; + string[] sampleContents = { + "", + "
No SVG here
" + }; + + for (int i = 0; i < sampleFiles.Length; i++) { - string samplePath = Path.Combine(inputFolder, "sample.html"); - File.WriteAllText(samplePath, ""); - htmlFiles = new string[] { samplePath }; + string filePath = Path.Combine(inputFolder, sampleFiles[i]); + if (!File.Exists(filePath)) + File.WriteAllText(filePath, sampleContents[i]); } + // Process each HTML file and log SVG count + string[] htmlFiles = Directory.GetFiles(inputFolder, "*.html"); foreach (string htmlPath in htmlFiles) { Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath); Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); int count = svgs.Length; - Console.WriteLine($"File '{Path.GetFileName(htmlPath)}' contains {count} external SVG(s)."); + Console.WriteLine($"File {Path.GetFileName(htmlPath)} contains {count} external SVG(s)."); } } catch (Exception ex) diff --git a/extract-svg-from-website/log_inline_svg_count_per_processed_page.cs b/extract-svg-from-website/log-count-of-inline-svgs-found-on-each-processed-page.cs similarity index 58% rename from extract-svg-from-website/log_inline_svg_count_per_processed_page.cs rename to extract-svg-from-website/log-count-of-inline-svgs-found-on-each-processed-page.cs index 0d9a241..127ae99 100644 --- a/extract-svg-from-website/log_inline_svg_count_per_processed_page.cs +++ b/extract-svg-from-website/log-count-of-inline-svgs-found-on-each-processed-page.cs @@ -1,25 +1,25 @@ // Log the count of inline SVGs found on each processed page. -using System; - class Program { static void Main() { try { - string[] htmlPages = new string[] + string[] pages = new string[] { - "", - "

No SVG here

", - "" + "", + "
No SVG here
", + "" }; - for (int i = 0; i < htmlPages.Length; i++) + for (int i = 0; i < pages.Length; i++) { - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPages[i]); + string htmlContent = pages[i]; + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); - System.Console.WriteLine($"Page {i + 1}: Found {svgs.Length} inline SVG(s)."); + int count = svgs.Length; + System.Console.WriteLine($"Page {i + 1}: Found {count} inline SVG(s)."); } } catch (System.Exception ex) diff --git a/extract-svg-from-website/option-rename-saved-svg-files-using-pattern-with-source-page-domain-and-index.cs b/extract-svg-from-website/option-rename-saved-svg-files-using-pattern-with-source-page-domain-and-index.cs new file mode 100644 index 0000000..417cda0 --- /dev/null +++ b/extract-svg-from-website/option-rename-saved-svg-files-using-pattern-with-source-page-domain-and-index.cs @@ -0,0 +1,52 @@ +// Provide an option to rename saved SVG files using a pattern that includes the source page domain and an index. + +using System; +using System.IO; +using Aspose.Html.Dom.Svg; + +class Program +{ + static void Main() + { + try + { + // Sample source page URLs + string[] sourceUrls = new string[] + { + "https://example.com/page1", + "https://sample.org/gallery" + }; + + // Simple SVG content to be saved + string svgContent = ""; + + // Output directory + string outputDir = "output"; + System.IO.Directory.CreateDirectory(outputDir); + + for (int i = 0; i < sourceUrls.Length; i++) + { + string sourceUrl = sourceUrls[i]; + // Extract domain from URL + string domain = new Uri(sourceUrl).Host; + + // Build output file name using domain and index + string fileName = $"{domain}_svg_{i + 1}.svg"; + string outputPath = System.IO.Path.Combine(outputDir, fileName); + + // Load SVG document with base URI (source page) + using (SVGDocument doc = new SVGDocument(svgContent, sourceUrl)) + { + // Save SVG to the generated path + doc.Save(outputPath); + } + + Console.WriteLine($"Saved SVG for '{domain}' as '{outputPath}'."); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/provide_option_rename_saved_svg_files_pattern_including_source_page_domain_and_index.cs b/extract-svg-from-website/provide_option_rename_saved_svg_files_pattern_including_source_page_domain_and_index.cs deleted file mode 100644 index e9bd6e3..0000000 --- a/extract-svg-from-website/provide_option_rename_saved_svg_files_pattern_including_source_page_domain_and_index.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Provide an option to rename saved SVG files using a pattern that includes the source page domain and an index. - -using System; -using System.IO; - -class Program -{ - static void Main() - { - try - { - string[] sourceUrls = new string[] - { - "https://example.com/page1", - "https://sample.org/graphics", - "https://test.net/diagram" - }; - - string[] svgContents = new string[] - { - "", - "", - "" - }; - - string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output"); - Directory.CreateDirectory(outputDir); - - for (int i = 0; i < sourceUrls.Length; i++) - { - string url = sourceUrls[i]; - string svgContent = svgContents[i]; - string domain = new Uri(url).Host.Replace(".", "_"); - string fileName = $"{domain}_{i + 1}.svg"; - string outputPath = Path.Combine(outputDir, fileName); - - using (Aspose.Html.Dom.Svg.SVGDocument doc = new Aspose.Html.Dom.Svg.SVGDocument(svgContent, url)) - { - doc.Save(outputPath); - } - - Console.WriteLine($"Saved SVG to: {outputPath}"); - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/resolve-relative-svg-urls-against-page-base-url-before-downloading.cs b/extract-svg-from-website/resolve-relative-svg-urls-against-page-base-url-before-downloading.cs new file mode 100644 index 0000000..7bfbbad --- /dev/null +++ b/extract-svg-from-website/resolve-relative-svg-urls-against-page-base-url-before-downloading.cs @@ -0,0 +1,33 @@ +// Resolve relative SVG URLs against the page's base URL before downloading. + +using System; + +class Program +{ + static void Main() + { + try + { + // Base URL of the HTML page + string baseUrl = "https://example.com/pages/"; + // Relative SVG URL found in the page + string relativeSvg = "images/sample.svg"; + + // Resolve the relative URL against the base URL + string absoluteSvgUrl = new Uri(new Uri(baseUrl), relativeSvg).ToString(); + + // Load the SVG document using the resolved absolute URL + Aspose.Html.Dom.Svg.SVGDocument svgDoc = new Aspose.Html.Dom.Svg.SVGDocument(absoluteSvgUrl, baseUrl); + + // Save the SVG to a local file + string outputPath = "resolved.svg"; + svgDoc.Save(outputPath); + + Console.WriteLine($"SVG saved to {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/resolve_relative_svg_urls_against_page_base_url_before_downloading.cs b/extract-svg-from-website/resolve_relative_svg_urls_against_page_base_url_before_downloading.cs deleted file mode 100644 index f6e6216..0000000 --- a/extract-svg-from-website/resolve_relative_svg_urls_against_page_base_url_before_downloading.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Resolve relative SVG URLs against the page's base URL before downloading. - -using System; - -class Program -{ - static void Main() - { - try - { - // Sample HTML containing an SVG with a relative image URL - string htmlContent = ""; - - // Base URL of the page - Aspose.Html.Url baseUri = new Aspose.Html.Url("https://example.com/page/"); - - // Resolve the relative URL against the base URL (demonstration) - Aspose.Html.Url resolvedUrl = new Aspose.Html.Url(baseUri.ToString(), "images/pic.png"); - Console.WriteLine("Resolved URL: " + resolvedUrl.ToString()); - - // Load HTML document with base URL - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, baseUri); - - // Save the document as a temporary SVG file - string tempSvgPath = "temp.svg"; - document.Save(tempSvgPath); - - // Load the saved SVG - Aspose.Html.Dom.Svg.SVGDocument svgDoc = new Aspose.Html.Dom.Svg.SVGDocument(tempSvgPath); - - // Save the final SVG to output path - string outputPath = "output.svg"; - svgDoc.Save(outputPath); - - Console.WriteLine("SVG saved to: " + outputPath); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/retrieve-all-inline-svg-elements-with-document-getelementsbytagname.cs b/extract-svg-from-website/retrieve-all-inline-svg-elements-with-document-getelementsbytagname.cs new file mode 100644 index 0000000..b501a20 --- /dev/null +++ b/extract-svg-from-website/retrieve-all-inline-svg-elements-with-document-getelementsbytagname.cs @@ -0,0 +1,35 @@ +// Retrieve all inline elements with document.GetElementsByTagName("svg"). + +using System; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "" + + "

Sample

" + + "" + + "

Text

" + + "" + + ""; + + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); + + for (int i = 0; i < svgs.Length; i++) + { + Aspose.Html.HTMLElement svgElement = (Aspose.Html.HTMLElement)svgs[i]; + string markup = svgElement.OuterHTML; + Console.WriteLine($"SVG #{i}:"); + Console.WriteLine(markup); + Console.WriteLine(); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/retrieve_all_inline_svg_elements_using_getelementsbytagname.cs b/extract-svg-from-website/retrieve_all_inline_svg_elements_using_getelementsbytagname.cs deleted file mode 100644 index 3f29af6..0000000 --- a/extract-svg-from-website/retrieve_all_inline_svg_elements_using_getelementsbytagname.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Retrieve all inline elements with document.GetElementsByTagName("svg"). - -class Program -{ - static void Main() - { - try - { - string currentDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); - string htmlPath = System.IO.Path.Combine(currentDir, "sample.html"); - string htmlContent = "

Sample

"; - System.IO.File.WriteAllText(htmlPath, htmlContent); - - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath); - Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); - - for (int i = 0; i < svgs.Length; i++) - { - Aspose.Html.HTMLElement svgElement = (Aspose.Html.HTMLElement)svgs[i]; - string markup = svgElement.OuterHTML; - System.Console.WriteLine($"SVG {i}: {markup}"); - } - } - catch (System.Exception ex) - { - System.Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/save-each-extracted-inline-svg-markup-to-separate-svg-file-using-system-io.cs b/extract-svg-from-website/save-each-extracted-inline-svg-markup-to-separate-svg-file-using-system-io.cs new file mode 100644 index 0000000..441944c --- /dev/null +++ b/extract-svg-from-website/save-each-extracted-inline-svg-markup-to-separate-svg-file-using-system-io.cs @@ -0,0 +1,48 @@ +// Save each extracted inline SVG markup to a separate .svg file using System.IO. + +using System; + +class Program +{ + static void Main() + { + try + { + // Sample HTML content with inline SVG elements + string htmlContent = "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; + + // Load HTML document from inline content + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Get all SVG elements + Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); + + for (int i = 0; i < svgs.Length; i++) + { + Aspose.Html.HTMLElement svgElement = (Aspose.Html.HTMLElement)svgs[i]; + string markup = svgElement.OuterHTML; + + string fileName = $"svg_{i}.svg"; + string outputPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName); + + using (Aspose.Html.Dom.Svg.SVGDocument svgDoc = new Aspose.Html.Dom.Svg.SVGDocument(markup, "about:blank")) + { + svgDoc.Save(outputPath); + } + + System.Console.WriteLine($"Saved SVG #{i} to: {outputPath}"); + } + } + catch (Exception ex) + { + System.Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/save_each_extracted_inline_svg_markup_to_separate_svg_file_using_system_io.cs b/extract-svg-from-website/save_each_extracted_inline_svg_markup_to_separate_svg_file_using_system_io.cs deleted file mode 100644 index 014546c..0000000 --- a/extract-svg-from-website/save_each_extracted_inline_svg_markup_to_separate_svg_file_using_system_io.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Save each extracted inline SVG markup to a separate .svg file using System.IO. - -using System; -using System.IO; - -class Program -{ - static void Main(string[] args) - { - try - { - // Sample HTML with inline SVG elements - string htmlContent = "" + - "" + - "" + - ""; - - // Load HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent); - - // Get all SVG elements - Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); - - // Extract each SVG and save to a separate .svg file - for (int i = 0; i < svgs.Length; i++) - { - Aspose.Html.HTMLElement svgElement = (Aspose.Html.HTMLElement)svgs[i]; - string markup = svgElement.OuterHTML; - string fileName = $"svg_{i}.svg"; - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), fileName); - - using (Aspose.Html.Dom.Svg.SVGDocument svgDoc = new Aspose.Html.Dom.Svg.SVGDocument(markup, "")) - { - svgDoc.Save(outputPath); - } - - Console.WriteLine($"Saved SVG #{i} to: {outputPath}"); - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/set-timeout-httpclient-prevent-hanging-external-svg-download.cs b/extract-svg-from-website/set-timeout-httpclient-prevent-hanging-external-svg-download.cs new file mode 100644 index 0000000..16733bd --- /dev/null +++ b/extract-svg-from-website/set-timeout-httpclient-prevent-hanging-external-svg-download.cs @@ -0,0 +1,26 @@ +// Set a timeout on HttpClient to prevent hanging during external SVG download. + +using System; + +class Program +{ + static void Main() + { + try + { + string url = "https://example.com/sample.svg"; + Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(url); + request.Timeout = System.TimeSpan.FromSeconds(5); + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(request)) + { + string outputPath = "sample.svg"; + document.Save(outputPath); + System.Console.WriteLine($"SVG saved to {outputPath}"); + } + } + catch (System.Exception ex) + { + System.Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/set_timeout_on_httpclient_to_prevent_hanging_during_external_svg_download.cs b/extract-svg-from-website/set_timeout_on_httpclient_to_prevent_hanging_during_external_svg_download.cs deleted file mode 100644 index eb7993e..0000000 --- a/extract-svg-from-website/set_timeout_on_httpclient_to_prevent_hanging_during_external_svg_download.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Set a timeout on HttpClient to prevent hanging during external SVG download. - -using System; - -class Program -{ - static void Main(string[] args) - { - try - { - // URL of the HTML page containing external SVGs - string url = "https://example.com/sample.html"; - - // Create a request with a timeout to avoid hanging - Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(url); - request.Timeout = System.TimeSpan.FromSeconds(10); - - // Load the HTML document using the request - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(request); - - // Get all SVG elements in the document - Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); - - for (int i = 0; i < svgs.Length; i++) - { - // Extract the outer HTML of the SVG element - string svgHtml = ((Aspose.Html.HTMLElement)svgs[i]).OuterHTML; - - // Save the SVG markup to a temporary file - string tempSvgPath = $"svg_{i}.svg"; - System.IO.File.WriteAllText(tempSvgPath, svgHtml); - - // Load the saved SVG as an SVGDocument - Aspose.Html.Dom.Svg.SVGDocument svgDoc = new Aspose.Html.Dom.Svg.SVGDocument(tempSvgPath); - - // Define save options (default options) - Aspose.Html.Dom.Svg.Saving.SVGSaveOptions options = new Aspose.Html.Dom.Svg.Saving.SVGSaveOptions(); - - // Save the SVG document (could be converted to another format if needed) - string outputSvgPath = $"svg_{i}_saved.svg"; - svgDoc.Save(outputSvgPath, options); - } - - // Clean up - document.Dispose(); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/use-webclient-fallback-when-httpclient-download-fails.cs b/extract-svg-from-website/use-webclient-fallback-when-httpclient-download-fails.cs new file mode 100644 index 0000000..c35fdbe --- /dev/null +++ b/extract-svg-from-website/use-webclient-fallback-when-httpclient-download-fails.cs @@ -0,0 +1,58 @@ +// Use WebClient as a fallback when HttpClient download fails. + +using System; +using System.Net.Http; +using System.Net; +using System.Text; +using Aspose.Html; +using Aspose.Html.Net; + +class Program +{ + static void Main() + { + try + { + string url = "https://example.com"; + byte[] contentBytes = null; + + // Try downloading with HttpClient + try + { + using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient()) + { + System.Threading.Tasks.Task responseTask = httpClient.GetAsync(url); + responseTask.Wait(); + System.Net.Http.HttpResponseMessage response = responseTask.Result; + response.EnsureSuccessStatusCode(); + System.Threading.Tasks.Task readTask = response.Content.ReadAsByteArrayAsync(); + readTask.Wait(); + contentBytes = readTask.Result; + } + } + catch (Exception) + { + // Fallback to WebClient + using (System.Net.WebClient webClient = new System.Net.WebClient()) + { + contentBytes = webClient.DownloadData(url); + } + } + + if (contentBytes == null || contentBytes.Length == 0) + { + Console.WriteLine("Failed to download content."); + return; + } + + string htmlContent = System.Text.Encoding.UTF8.GetString(contentBytes); + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + string outerHtml = ((Aspose.Html.HTMLElement)document.DocumentElement).OuterHTML; + Console.WriteLine(outerHtml); + } + catch (System.Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/use_webclient_fallback_when_httpclient_download_fails.cs b/extract-svg-from-website/use_webclient_fallback_when_httpclient_download_fails.cs deleted file mode 100644 index 54f3081..0000000 --- a/extract-svg-from-website/use_webclient_fallback_when_httpclient_download_fails.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Use WebClient as a fallback when HttpClient download fails. - -using System; -using System.Net; -using System.Net.Http; -using Aspose.Html; -using Aspose.Html.Net; - -class Program -{ - static void Main() - { - try - { - string url = "https://example.com"; - string htmlContent = null; - - try - { - using (HttpClient httpClient = new HttpClient()) - { - httpClient.Timeout = TimeSpan.FromSeconds(30); - htmlContent = httpClient.GetStringAsync(url).GetAwaiter().GetResult(); - } - } - catch (Exception) - { - using (WebClient webClient = new WebClient()) - { - htmlContent = webClient.DownloadString(url); - } - } - - // Use Aspose.Html to load the document from the URL - RequestMessage request = new RequestMessage(url); - request.Timeout = TimeSpan.FromSeconds(30); - using (HTMLDocument document = new HTMLDocument(request)) - { - string html = ((HTMLElement)document.DocumentElement).OuterHTML; - Console.WriteLine(html); - } - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/extract-svg-from-website/verify-copyright-usage-terms-before-reusing-extracted-svg-files.cs b/extract-svg-from-website/verify-copyright-usage-terms-before-reusing-extracted-svg-files.cs new file mode 100644 index 0000000..56d1e86 --- /dev/null +++ b/extract-svg-from-website/verify-copyright-usage-terms-before-reusing-extracted-svg-files.cs @@ -0,0 +1,60 @@ +// Verify copyright and usage terms before reusing extracted SVG files. + +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Html; +using Aspose.Html.Collections; +using Aspose.Html.Dom.Svg; + +class Program +{ + static void Main() + { + try + { + // Sample HTML containing SVG elements + string htmlContent = "" + + "" + + "" + + "" + // duplicate + ""; + + // Load HTML document from inline content + string baseUri = "about:blank"; + HTMLDocument document = new HTMLDocument(htmlContent, baseUri); + + // Get all SVG elements + HTMLCollection svgs = document.GetElementsByTagName("svg"); + + // Track unique SVG markup + HashSet seenMarkups = new HashSet(); + + // Ensure output directory exists + string outputDir = "ExtractedSvgs"; + Directory.CreateDirectory(outputDir); + + for (int i = 0; i < svgs.Length; i++) + { + // Cast to HTMLElement to access OuterHTML + HTMLElement svgElement = (HTMLElement)svgs[i]; + string markup = svgElement.OuterHTML; + + // Skip duplicates + if (!seenMarkups.Add(markup)) + continue; + + // Save each unique SVG to a file + string outputPath = Path.Combine(outputDir, $"svg_{i}.svg"); + SVGDocument svgDoc = new SVGDocument(markup, baseUri); + svgDoc.Save(outputPath); + + Console.WriteLine($"Saved SVG to {outputPath}"); + } + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/verify_copyright_usage_terms_before_reusing_extracted_svg_files.cs b/extract-svg-from-website/verify_copyright_usage_terms_before_reusing_extracted_svg_files.cs deleted file mode 100644 index 69a3d21..0000000 --- a/extract-svg-from-website/verify_copyright_usage_terms_before_reusing_extracted_svg_files.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Verify copyright and usage terms before reusing extracted SVG files. - -using System; -using System.IO; -using System.Collections.Generic; -using Aspose.Html; -using Aspose.Html.Collections; -using Aspose.Html.Dom.Svg; - -class Program -{ - static void Main() - { - try - { - // Sample HTML content containing SVG elements - string htmlContent = "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - ""; - - // Load HTML document from the string - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent); - - // Get all SVG elements - Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); - - // Prepare output directory - string outputDir = "output"; - System.IO.Directory.CreateDirectory(outputDir); - - // Track processed SVG markup to avoid duplicates - System.Collections.Generic.HashSet seenMarkups = new System.Collections.Generic.HashSet(); - - for (int i = 0; i < svgs.Length; i++) - { - Aspose.Html.HTMLElement svgElement = (Aspose.Html.HTMLElement)svgs[i]; - string markup = svgElement.OuterHTML; - - // Skip duplicate SVGs - if (!seenMarkups.Add(markup)) - continue; - - // Verify copyright or usage terms in the SVG markup - if (!markup.Contains("copyright")) - { - // Skip SVGs without explicit copyright information - continue; - } - - // Save each verified SVG to a separate file - string outputPath = System.IO.Path.Combine(outputDir, $"svg_{i}.svg"); - Aspose.Html.Dom.Svg.SVGDocument svgDoc = new Aspose.Html.Dom.Svg.SVGDocument(markup, ""); - svgDoc.Save(outputPath); - } - - Console.WriteLine("SVG extraction and verification completed successfully."); - } - catch (Exception ex) - { - Console.WriteLine("An error occurred: " + ex.Message); - } - } -} \ No newline at end of file From ffc5d0e21604a4f9e4025609042195c51d56efd8 Mon Sep 17 00:00:00 2001 From: agent-aspose-html-examples Date: Fri, 2 Oct 2026 23:23:27 +0500 Subject: [PATCH 2/2] =?UTF-8?q?feat(extract-svg-from-website):=20Add=204?= =?UTF-8?q?=20Aspose.HTML=20.NET=20C#=20examples=20for=20Extract=20Svg=20F?= =?UTF-8?q?rom=20Website=20=E2=80=94=20Aspose.HTML=20for=20.NET=2026.9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...-to-correctly-resolve-relative-svg-urls.cs | 62 +++++++++++++++++++ ...local-file-preserving-original-filename.cs | 56 +++++++++++++++++ ...-in-dictionary-keyed-by-source-page-url.cs | 58 +++++++++++++++++ ...coding-when-loading-non-utf8-html-pages.cs | 38 ++++++++++++ 4 files changed, 214 insertions(+) create mode 100644 extract-svg-from-website/parse-base-tag-in-html-document-to-correctly-resolve-relative-svg-urls.cs create mode 100644 extract-svg-from-website/save-each-downloaded-external-svg-to-local-file-preserving-original-filename.cs create mode 100644 extract-svg-from-website/store-file-paths-of-saved-svgs-in-dictionary-keyed-by-source-page-url.cs create mode 100644 extract-svg-from-website/use-htmlloadoptions-specify-correct-encoding-when-loading-non-utf8-html-pages.cs diff --git a/extract-svg-from-website/parse-base-tag-in-html-document-to-correctly-resolve-relative-svg-urls.cs b/extract-svg-from-website/parse-base-tag-in-html-document-to-correctly-resolve-relative-svg-urls.cs new file mode 100644 index 0000000..9288992 --- /dev/null +++ b/extract-svg-from-website/parse-base-tag-in-html-document-to-correctly-resolve-relative-svg-urls.cs @@ -0,0 +1,62 @@ +// Parse the tag in the HTML document to correctly resolve relative SVG URLs. + +using System; + +class Program +{ + static void Main() + { + try + { + // Sample HTML with tag and an SVG image referencing a relative URL + string htmlContent = @" + + + + + + + + + +"; + + // Load HTML document (inline content) with a dummy base URI + var htmlDoc = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Retrieve the element and its href attribute + var baseElements = htmlDoc.GetElementsByTagName("base"); + string baseHref = ""; + if (baseElements.Length > 0) + { + var baseElem = (Aspose.Html.HTMLElement)baseElements[0]; + baseHref = baseElem.GetAttribute("href"); + } + + // Retrieve the element inside the SVG and its href attribute + var imageElements = htmlDoc.GetElementsByTagName("image"); + string relativeUrl = ""; + if (imageElements.Length > 0) + { + var imageElem = (Aspose.Html.HTMLElement)imageElements[0]; + relativeUrl = imageElem.GetAttribute("href"); + } + + // Resolve the relative URL against the base href + string resolvedUrl = ""; + if (!string.IsNullOrEmpty(baseHref) && !string.IsNullOrEmpty(relativeUrl)) + { + resolvedUrl = new Uri(new Uri(baseHref), relativeUrl).ToString(); + } + + // Output the resolved URL + Console.WriteLine("Base href: " + baseHref); + Console.WriteLine("Relative URL: " + relativeUrl); + Console.WriteLine("Resolved URL: " + resolvedUrl); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/save-each-downloaded-external-svg-to-local-file-preserving-original-filename.cs b/extract-svg-from-website/save-each-downloaded-external-svg-to-local-file-preserving-original-filename.cs new file mode 100644 index 0000000..0bb511b --- /dev/null +++ b/extract-svg-from-website/save-each-downloaded-external-svg-to-local-file-preserving-original-filename.cs @@ -0,0 +1,56 @@ +// Save each downloaded external SVG to a local .svg file preserving the original file name. + +using System; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; +using Aspose.Html; +using Aspose.Html.Collections; +using Aspose.Html; + +class Program +{ + static void Main(string[] args) + { + try + { + string htmlContent = "svg1png"; + HTMLDocument document = new HTMLDocument(htmlContent, "about:blank"); + Aspose.Html.Collections.NodeList svgElements = document.QuerySelectorAll("img[src$='.svg']"); + + for (int i = 0; i < svgElements.Length; i++) + { + HTMLElement imgElement = (HTMLElement)svgElements[i]; + string src = imgElement.GetAttribute("src"); + if (string.IsNullOrEmpty(src)) + continue; + + using (HttpClient client = new HttpClient()) + { + Task responseTask = client.GetAsync(src); + responseTask.Wait(); + HttpResponseMessage response = responseTask.Result; + response.EnsureSuccessStatusCode(); + + Task bytesTask = response.Content.ReadAsByteArrayAsync(); + bytesTask.Wait(); + byte[] data = bytesTask.Result; + + string fileName = Path.GetFileName(new Uri(src).LocalPath); + if (string.IsNullOrEmpty(fileName)) + fileName = "downloaded.svg"; + + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), fileName); + File.WriteAllBytes(outputPath, data); + Console.WriteLine($"Saved SVG to {outputPath}"); + } + } + + document.Save("output.html"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/store-file-paths-of-saved-svgs-in-dictionary-keyed-by-source-page-url.cs b/extract-svg-from-website/store-file-paths-of-saved-svgs-in-dictionary-keyed-by-source-page-url.cs new file mode 100644 index 0000000..4bb524f --- /dev/null +++ b/extract-svg-from-website/store-file-paths-of-saved-svgs-in-dictionary-keyed-by-source-page-url.cs @@ -0,0 +1,58 @@ +// Store the file paths of saved SVGs in a dictionary keyed by the source page URL. + +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Html; + +class Program +{ + static void Main() + { + try + { + // Prepare sample HTML files + string baseDir = Path.Combine(Directory.GetCurrentDirectory(), "SampleHtml"); + Directory.CreateDirectory(baseDir); + + var htmlFiles = new List(); + for (int i = 1; i <= 2; i++) + { + string filePath = Path.Combine(baseDir, $"page{i}.html"); + File.WriteAllText(filePath, $"

Sample Page {i}

"); + htmlFiles.Add(filePath); + } + + // Dictionary to store SVG paths keyed by source page URL (file path) + var svgPaths = new Dictionary(); + + foreach (string htmlPath in htmlFiles) + { + // Load HTML document from file + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath)) + { + // Determine SVG output path + string svgPath = Path.ChangeExtension(htmlPath, ".svg"); + + // Save as SVG + document.Save(svgPath); + + // Store in dictionary + svgPaths[htmlPath] = svgPath; + } + } + + // Output results + foreach (var kvp in svgPaths) + { + Console.WriteLine($"Source: {kvp.Key}"); + Console.WriteLine($"Saved SVG: {kvp.Value}"); + Console.WriteLine(); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/extract-svg-from-website/use-htmlloadoptions-specify-correct-encoding-when-loading-non-utf8-html-pages.cs b/extract-svg-from-website/use-htmlloadoptions-specify-correct-encoding-when-loading-non-utf8-html-pages.cs new file mode 100644 index 0000000..5656695 --- /dev/null +++ b/extract-svg-from-website/use-htmlloadoptions-specify-correct-encoding-when-loading-non-utf8-html-pages.cs @@ -0,0 +1,38 @@ +// Use HtmlLoadOptions to specify the correct encoding when loading non-UTF-8 HTML pages. + +using System; +using System.IO; +using System.Text; +using Aspose.Html; + +class Program +{ + static void Main() + { + try + { + // Define file paths + string sourcePath = "sample_nonutf8.html"; + string outputPath = "converted.html"; + + // Create a sample HTML file encoded in Windows-1251 + string htmlContent = "Пример

Тестовый текст.

"; + File.WriteAllText(sourcePath, htmlContent, Encoding.GetEncoding("windows-1251")); + + // Read the HTML content using the correct encoding + string readContent = File.ReadAllText(sourcePath, Encoding.GetEncoding("windows-1251")); + + // Load the HTML document from the string (inline content) with a placeholder base URI + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(readContent, "about:blank"); + + // Save the document (will be saved as UTF-8 by default) + document.Save(outputPath); + + Console.WriteLine("HTML document loaded with specified encoding and saved successfully."); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file