diff --git a/index.json b/index.json index b6c963d38..3fc6185be 100644 --- a/index.json +++ b/index.json @@ -2339,11 +2339,211 @@ "file": "verify-that-the-merged-workbook-contains-the-expected-number-of-worksheets-after-combination.cs", "title": "Verify that the merged workbook contains the expected number of worksheets after combination." }, + { + "category": "working-with-images", + "file": "attach-the-jpeg-chart-image-to-an-email-body-using-inline-html-to-display-within-the-message.cs", + "title": "Attach the JPEG chart image to an email body using inline HTML to display within the message." + }, + { + "category": "working-with-images", + "file": "batch-convert-all-excel-files-in-a-directory-to-individual-tiff-images-using-default-rendering-settings.cs", + "title": "Batch convert all Excel files in a directory to individual TIFF images using default rendering settings." + }, + { + "category": "working-with-images", + "file": "compress-the-svg-worksheet-file-using-gzip-before-transmitting-it-over-the-network-for-efficiency.cs", + "title": "Compress the SVG worksheet file using GZip before transmitting it over the network for efficiency." + }, + { + "category": "working-with-images", + "file": "convert-a-workbook-to-tiff-using-eightbit-color-depth-for-smaller-output-files.cs", + "title": "Convert a workbook to TIFF using eight\u2011bit color depth for smaller output files." + }, + { + "category": "working-with-images", + "file": "convert-a-workbook-to-tiff-using-twentyfourbit-color-depth-for-highquality-images.cs", + "title": "Convert a workbook to TIFF using twenty\u2011four\u2011bit color depth for high\u2011quality images." + }, + { + "category": "working-with-images", + "file": "convert-a-worksheet-to-png-and-embed-the-resulting-image-as-a-base64-string-in-json.cs", + "title": "Convert a worksheet to PNG and embed the resulting image as a base64 string in JSON." + }, + { + "category": "working-with-images", + "file": "convert-a-worksheet-to-svg-with-the-viewbox-attribute-enabled-for-scalable-rendering.cs", + "title": "Convert a worksheet to SVG with the viewBox attribute enabled for scalable rendering." + }, { "category": "working-with-images", "file": "convert-an-entire-workbook-to-a-multipage-tiff-using-default-rendering-options.cs", "title": "Convert an entire workbook to a multi\u2011page TIFF using default rendering options." }, + { + "category": "working-with-images", + "file": "convert-the-first-worksheet-of-a-workbook-to-png-using-default-resolution-for-quick-preview.cs", + "title": "Convert the first worksheet of a workbook to PNG using default resolution for quick preview." + }, + { + "category": "working-with-images", + "file": "convert-the-workbook-tiff-to-pdf-by-invoking-a-thirdparty-converter-after-image-generation.cs", + "title": "Convert the workbook TIFF to PDF by invoking a third\u2011party converter after image generation." + }, + { + "category": "working-with-images", + "file": "embed-the-generated-svg-worksheet-file-into-an-html-document-using-the-object-tag-for-display.cs", + "title": "Embed the generated SVG worksheet file into an HTML document using the object tag for display." + }, + { + "category": "working-with-images", + "file": "embed-the-resulting-tiff-image-into-an-html-page-using-an-img-tag-with-appropriate-source-attribute.cs", + "title": "Embed the resulting TIFF image into an HTML page using an img tag with appropriate source attribute." + }, + { + "category": "working-with-images", + "file": "export-a-chart-to-svg-with-viewbox-attribute-for-responsive-scaling-in-modern-browsers.cs", + "title": "Export a chart to SVG with viewBox attribute for responsive scaling in modern browsers." + }, + { + "category": "working-with-images", + "file": "export-a-worksheet-to-svg-without-the-viewbox-attribute-to-produce-fixedsize-vector-output.cs", + "title": "Export a worksheet to SVG without the viewBox attribute to produce fixed\u2011size vector output." + }, + { + "category": "working-with-images", + "file": "export-the-worksheet-named-chart-to-bmp-at-96-dpi-resolution-for-legacy-image-compatibility.cs", + "title": "Export the worksheet named Chart to BMP at 96 DPI resolution for legacy image compatibility." + }, + { + "category": "working-with-images", + "file": "extract-every-chart-from-a-workbook-and-export-them-as-svg-files-into-a-designated-subfolder.cs", + "title": "Extract every chart from a workbook and export them as SVG files into a designated subfolder." + }, + { + "category": "working-with-images", + "file": "generate-a-jpeg-image-from-a-worksheet-with-custom-image-quality-set-to-80-percent.cs", + "title": "Generate a JPEG image from a worksheet with custom image quality set to 80 percent." + }, + { + "category": "working-with-images", + "file": "generate-a-multipage-tiff-from-the-first-three-worksheets-of-a-loaded-workbook.cs", + "title": "Generate a multi\u2011page TIFF from the first three worksheets of a loaded workbook." + }, + { + "category": "working-with-images", + "file": "include-the-svg-chart-file-in-a-web-page-to-allow-interactive-zoom-and-pan-features.cs", + "title": "Include the SVG chart file in a web page to allow interactive zoom and pan features." + }, + { + "category": "working-with-images", + "file": "iterate-through-each-worksheet-in-a-workbook-and-save-each-as-a-separate-png-file.cs", + "title": "Iterate through each worksheet in a workbook and save each as a separate PNG file." + }, + { + "category": "working-with-images", + "file": "measure-conversion-duration-using-stopwatch-and-log-elapsed-time-for-performance-analysis.cs", + "title": "Measure conversion duration using Stopwatch and log elapsed time for performance analysis." + }, + { + "category": "working-with-images", + "file": "perform-pixelbypixel-comparison-between-the-generated-png-worksheet-image-and-a-baseline-reference.cs", + "title": "Perform pixel\u2011by\u2011pixel comparison between the generated PNG worksheet image and a baseline reference." + }, + { + "category": "working-with-images", + "file": "preserve-data-labels-visibility-when-converting-a-chart-to-png-to-retain-informational-context.cs", + "title": "Preserve data labels visibility when converting a chart to PNG to retain informational context." + }, + { + "category": "working-with-images", + "file": "render-a-chart-object-from-the-workbook-to-a-png-image-using-the-chartrender-api.cs", + "title": "Render a chart object from the workbook to a PNG image using the ChartRender API." + }, + { + "category": "working-with-images", + "file": "render-a-workbook-as-tiff-using-300-dpi-resolution-to-improve-image-clarity.cs", + "title": "Render a workbook as TIFF using 300 DPI resolution to improve image clarity." + }, + { + "category": "working-with-images", + "file": "render-a-workbook-to-tiff-and-write-the-result-into-a-memory-stream-for-further-processing.cs", + "title": "Render a workbook to TIFF and write the result into a memory stream for further processing." + }, + { + "category": "working-with-images", + "file": "render-a-workbook-to-tiff-with-horizontal-and-vertical-resolutions-set-to-150-dpi.cs", + "title": "Render a workbook to TIFF with horizontal and vertical resolutions set to 150 DPI." + }, + { + "category": "working-with-images", + "file": "render-a-worksheet-to-jpeg-and-upload-the-image-file-to-a-cloud-storage-bucket.cs", + "title": "Render a worksheet to JPEG and upload the image file to a cloud storage bucket." + }, + { + "category": "working-with-images", + "file": "render-a-worksheet-to-jpeg-with-gridlines-hidden-by-setting-isgridlinesvisible-to-false.cs", + "title": "Render a worksheet to JPEG with gridlines hidden by setting IsGridLinesVisible to false." + }, + { + "category": "working-with-images", + "file": "render-the-svg-worksheet-image-in-a-wpf-image-control-for-display-within-a-desktop-application.cs", + "title": "Render the SVG worksheet image in a WPF Image control for display within a desktop application." + }, + { + "category": "working-with-images", + "file": "save-a-generated-tiff-file-directly-to-a-network-share-path-after-converting-the-workbook.cs", + "title": "Save a generated TIFF file directly to a network share path after converting the workbook." + }, + { + "category": "working-with-images", + "file": "save-the-svg-worksheet-image-to-a-svg-file-with-utf8-encoding-to-preserve-character-data.cs", + "title": "Save the SVG worksheet image to a .svg file with UTF\u20118 encoding to preserve character data." + }, + { + "category": "working-with-images", + "file": "send-the-png-worksheet-image-via-http-post-to-a-rest-endpoint-for-downstream-processing.cs", + "title": "Send the PNG worksheet image via HTTP POST to a REST endpoint for downstream processing." + }, + { + "category": "working-with-images", + "file": "set-chart-image-resolution-to-300-dpi-during-png-conversion-to-achieve-highdefinition-output.cs", + "title": "Set chart image resolution to 300 DPI during PNG conversion to achieve high\u2011definition output." + }, + { + "category": "working-with-images", + "file": "set-custom-page-margins-in-imageorprintoptions-before-converting-workbook-to-tiff-for-layout-control.cs", + "title": "Set custom page margins in ImageOrPrintOptions before converting workbook to TIFF for layout control." + }, + { + "category": "working-with-images", + "file": "specify-a-white-background-color-in-imageorprintoptions-when-rendering-workbook-to-tiff-to-ensure-consistency.cs", + "title": "Specify a white background color in ImageOrPrintOptions when rendering workbook to TIFF to ensure consistency." + }, + { + "category": "working-with-images", + "file": "split-a-multipage-tiff-workbook-output-into-individual-singlepage-tiff-files-for-separate-handling.cs", + "title": "Split a multi\u2011page TIFF workbook output into individual single\u2011page TIFF files for separate handling." + }, + { + "category": "working-with-images", + "file": "store-the-png-worksheet-image-in-azure-blob-storage-with-custom-metadata-for-categorization.cs", + "title": "Store the PNG worksheet image in Azure Blob Storage with custom metadata for categorization." + }, + { + "category": "working-with-images", + "file": "track-workbooktotiff-conversion-progress-by-handling-the-conversion-progress-event-and-logging-percentages.cs", + "title": "Track workbook\u2011to\u2011TIFF conversion progress by handling the conversion progress event and logging percentages." + }, + { + "category": "working-with-images", + "file": "use-the-svg-worksheet-graphic-as-a-vector-element-when-generating-a-pdf-document-with-itextsharp.cs", + "title": "Use the SVG worksheet graphic as a vector element when generating a PDF document with iTextSharp." + }, + { + "category": "working-with-images", + "file": "validate-the-svg-worksheet-file-against-the-svg-schema-to-ensure-structural-correctness.cs", + "title": "Validate the SVG worksheet file against the SVG schema to ensure structural correctness." + }, { "category": "working-with-json", "file": "apply-a-custom-culture-setting-to-format-dates-in-json-according-to-iso-8601-standard.cs", diff --git a/working-with-images/agents.md b/working-with-images/agents.md new file mode 100644 index 000000000..9e9af2be0 --- /dev/null +++ b/working-with-images/agents.md @@ -0,0 +1,97 @@ +# Working With Images Examples + +This folder contains **Aspose.Cells for .NET** code examples related to: + +Working With Images + + +## Purpose + +These examples demonstrate common **Aspose.Cells APIs** used when working with: + +- Workbooks +- Worksheets +- Cells +- Formulas +- Charts +- Data operations + + +## Example Files + +Each `.cs` file demonstrates a specific task related to **Working With Images**. + +Example: + +create-a-workbook.cs + + +## Required Namespaces + +Most examples will require: + +using Aspose.Cells; + + +## Common Pattern + +Typical Aspose.Cells workflow: + +Workbook workbook = new Workbook(); + +Worksheet sheet = workbook.Worksheets[0]; + +Cells cells = sheet.Cells; + + +## Output + +Examples may generate: + +- XLSX files +- PDF files +- CSV files +- Images + +Output files are written to the working directory. +- convert-an-entire-workbook-to-a-multipage-tiff-using-default-rendering-options.cs +- render-a-workbook-as-tiff-using-300-dpi-resolution-to-improve-image-clarity.cs +- render-a-workbook-to-tiff-with-horizontal-and-vertical-resolutions-set-to-150-dpi.cs +- convert-a-workbook-to-tiff-using-eightbit-color-depth-for-smaller-output-files.cs +- convert-a-workbook-to-tiff-using-twentyfourbit-color-depth-for-highquality-images.cs +- generate-a-multipage-tiff-from-the-first-three-worksheets-of-a-loaded-workbook.cs +- track-workbooktotiff-conversion-progress-by-handling-the-conversion-progress-event-and-logging-percentages.cs +- render-a-workbook-to-tiff-and-write-the-result-into-a-memory-stream-for-further-processing.cs +- save-a-generated-tiff-file-directly-to-a-network-share-path-after-converting-the-workbook.cs +- embed-the-resulting-tiff-image-into-an-html-page-using-an-img-tag-with-appropriate-source-attribute.cs +- measure-conversion-duration-using-stopwatch-and-log-elapsed-time-for-performance-analysis.cs +- set-custom-page-margins-in-imageorprintoptions-before-converting-workbook-to-tiff-for-layout-control.cs +- specify-a-white-background-color-in-imageorprintoptions-when-rendering-workbook-to-tiff-to-ensure-consistency.cs +- convert-the-first-worksheet-of-a-workbook-to-png-using-default-resolution-for-quick-preview.cs +- export-the-worksheet-named-chart-to-bmp-at-96-dpi-resolution-for-legacy-image-compatibility.cs +- render-a-worksheet-to-jpeg-with-gridlines-hidden-by-setting-isgridlinesvisible-to-false.cs +- generate-a-jpeg-image-from-a-worksheet-with-custom-image-quality-set-to-80-percent.cs +- convert-a-worksheet-to-png-and-embed-the-resulting-image-as-a-base64-string-in-json.cs +- render-a-worksheet-to-jpeg-and-upload-the-image-file-to-a-cloud-storage-bucket.cs +- store-the-png-worksheet-image-in-azure-blob-storage-with-custom-metadata-for-categorization.cs +- send-the-png-worksheet-image-via-http-post-to-a-rest-endpoint-for-downstream-processing.cs +- perform-pixelbypixel-comparison-between-the-generated-png-worksheet-image-and-a-baseline-reference.cs +- convert-a-worksheet-to-svg-with-the-viewbox-attribute-enabled-for-scalable-rendering.cs +- export-a-worksheet-to-svg-without-the-viewbox-attribute-to-produce-fixedsize-vector-output.cs +- embed-the-generated-svg-worksheet-file-into-an-html-document-using-the-object-tag-for-display.cs +- save-the-svg-worksheet-image-to-a-svg-file-with-utf8-encoding-to-preserve-character-data.cs +- compress-the-svg-worksheet-file-using-gzip-before-transmitting-it-over-the-network-for-efficiency.cs +- validate-the-svg-worksheet-file-against-the-svg-schema-to-ensure-structural-correctness.cs +- render-the-svg-worksheet-image-in-a-wpf-image-control-for-display-within-a-desktop-application.cs +- use-the-svg-worksheet-graphic-as-a-vector-element-when-generating-a-pdf-document-with-itextsharp.cs +- render-a-chart-object-from-the-workbook-to-a-png-image-using-the-chartrender-api.cs +- export-a-chart-to-svg-with-viewbox-attribute-for-responsive-scaling-in-modern-browsers.cs +- attach-the-jpeg-chart-image-to-an-email-body-using-inline-html-to-display-within-the-message.cs +- include-the-svg-chart-file-in-a-web-page-to-allow-interactive-zoom-and-pan-features.cs +- preserve-data-labels-visibility-when-converting-a-chart-to-png-to-retain-informational-context.cs +- set-chart-image-resolution-to-300-dpi-during-png-conversion-to-achieve-highdefinition-output.cs +- batch-convert-all-excel-files-in-a-directory-to-individual-tiff-images-using-default-rendering-settings.cs +- iterate-through-each-worksheet-in-a-workbook-and-save-each-as-a-separate-png-file.cs +- extract-every-chart-from-a-workbook-and-export-them-as-svg-files-into-a-designated-subfolder.cs +- split-a-multipage-tiff-workbook-output-into-individual-singlepage-tiff-files-for-separate-handling.cs +- convert-the-workbook-tiff-to-pdf-by-invoking-a-thirdparty-converter-after-image-generation.cs diff --git a/working-with-images/attach-the-jpeg-chart-image-to-an-email-body-using-inline-html-to-display-within-the-message.cs b/working-with-images/attach-the-jpeg-chart-image-to-an-email-body-using-inline-html-to-display-within-the-message.cs new file mode 100644 index 000000000..841b16c50 --- /dev/null +++ b/working-with-images/attach-the-jpeg-chart-image-to-an-email-body-using-inline-html-to-display-within-the-message.cs @@ -0,0 +1,77 @@ +using System; +using System.IO; +using System.Net; +using System.Net.Mail; +using Aspose.Cells; +using Aspose.Cells.Charts; +using Aspose.Cells.Drawing; + +class ChartEmailExample +{ + static void Main() + { + // 1. Create a workbook and add sample data + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["A2"].PutValue("Apple"); + sheet.Cells["A3"].PutValue("Orange"); + sheet.Cells["A4"].PutValue("Banana"); + + sheet.Cells["B1"].PutValue("Value"); + sheet.Cells["B2"].PutValue(120); + sheet.Cells["B3"].PutValue(80); + sheet.Cells["B4"].PutValue(150); + + // 2. Add a column chart + int chartIndex = sheet.Charts.Add(ChartType.Column, 5, 0, 20, 8); + Chart chart = sheet.Charts[chartIndex]; + chart.NSeries.Add("B2:B4", true); + chart.NSeries.CategoryData = "A2:A4"; + + // 3. Render the chart to a JPEG image in memory + using (MemoryStream imgStream = new MemoryStream()) + { + chart.ToImage(imgStream, ImageType.Jpeg); // Use Aspose.Cells Chart.ToImage(Stream, ImageType) + + // 4. Convert the image bytes to a Base64 string + string base64Image = Convert.ToBase64String(imgStream.ToArray()); + + // 5. Build the HTML body with an inline image + string htmlBody = $@" + + +

Sales Chart

+ Chart + + "; + + // 6. Prepare the email message + MailMessage message = new MailMessage(); + message.From = new MailAddress("sender@example.com"); // TODO: replace with actual sender + message.To.Add("recipient@example.com"); // TODO: replace with actual recipient + message.Subject = "Chart Embedded in Email"; + message.Body = htmlBody; + message.IsBodyHtml = true; + + // 7. Configure SMTP client (replace placeholders with real values) + SmtpClient smtp = new SmtpClient("smtp.example.com", 587) // TODO: SMTP server + { + Credentials = new NetworkCredential("username", "password"), // TODO: credentials + EnableSsl = true + }; + + // 8. Send the email + try + { + smtp.Send(message); + Console.WriteLine("Email sent successfully."); + } + catch (Exception ex) + { + Console.WriteLine("Error sending email: " + ex.Message); + } + } + } +} \ No newline at end of file diff --git a/working-with-images/batch-convert-all-excel-files-in-a-directory-to-individual-tiff-images-using-default-rendering-settings.cs b/working-with-images/batch-convert-all-excel-files-in-a-directory-to-individual-tiff-images-using-default-rendering-settings.cs new file mode 100644 index 000000000..acb15895d --- /dev/null +++ b/working-with-images/batch-convert-all-excel-files-in-a-directory-to-individual-tiff-images-using-default-rendering-settings.cs @@ -0,0 +1,63 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; + +namespace BatchExcelToTiff +{ + class Program + { + static void Main() + { + // Directory containing source Excel files + string sourceDir = @"C:\ExcelFiles"; + // Directory where TIFF images will be saved + string outputDir = @"C:\TiffOutput"; + + // Ensure the output directory exists + Directory.CreateDirectory(outputDir); + + // Get all Excel files (xls, xlsx, xlsm, etc.) in the source directory + string[] excelFiles = Directory.GetFiles(sourceDir, "*.xls*"); + + foreach (string excelPath in excelFiles) + { + try + { + // Load the workbook from the Excel file + Workbook workbook = new Workbook(excelPath); + + // Iterate through each worksheet in the workbook + for (int sheetIndex = 0; sheetIndex < workbook.Worksheets.Count; sheetIndex++) + { + Worksheet sheet = workbook.Worksheets[sheetIndex]; + + // Configure image rendering options for TIFF output + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Tiff, // Ensure TIFF format + OnePagePerSheet = true // Render the whole sheet as one page + }; + + // Create a SheetRender instance for the current worksheet + SheetRender renderer = new SheetRender(sheet, options); + + // Build the output file name: OriginalName_Sheet0.tiff, etc. + string tiffFileName = $"{Path.GetFileNameWithoutExtension(excelPath)}_Sheet{sheetIndex}.tiff"; + string tiffPath = Path.Combine(outputDir, tiffFileName); + + // Render the worksheet to a TIFF file + renderer.ToTiff(tiffPath); + } + + Console.WriteLine($"Successfully converted '{Path.GetFileName(excelPath)}' to TIFF images."); + } + catch (Exception ex) + { + Console.WriteLine($"Error processing file '{excelPath}': {ex.Message}"); + } + } + } + } +} \ No newline at end of file diff --git a/working-with-images/compress-the-svg-worksheet-file-using-gzip-before-transmitting-it-over-the-network-for-efficiency.cs b/working-with-images/compress-the-svg-worksheet-file-using-gzip-before-transmitting-it-over-the-network-for-efficiency.cs new file mode 100644 index 000000000..19a087aef --- /dev/null +++ b/working-with-images/compress-the-svg-worksheet-file-using-gzip-before-transmitting-it-over-the-network-for-efficiency.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +namespace AsposeCellsSvgGzipDemo +{ + class Program + { + static void Main() + { + try + { + // 1. Create a new workbook and populate it with sample data + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Product"); + sheet.Cells["B1"].PutValue("Quantity"); + sheet.Cells["A2"].PutValue("Apple"); + sheet.Cells["B2"].PutValue(150); + sheet.Cells["A3"].PutValue("Orange"); + sheet.Cells["B3"].PutValue(250); + + // 2. Set up SVG rendering options (ImageFormat is implicit for SVG) + SvgImageOptions svgOptions = new SvgImageOptions + { + FitToViewPort = true // make SVG fit the viewport + }; + + // 3. Render the first worksheet to an SVG file + SheetRender renderer = new SheetRender(sheet, svgOptions); + string svgPath = "worksheet.svg"; + renderer.ToImage(0, svgPath); + + // 4. Read the generated SVG file into a byte array (ensure it exists) + if (!File.Exists(svgPath)) + throw new FileNotFoundException($"SVG file not found: {svgPath}"); + + byte[] svgBytes = File.ReadAllBytes(svgPath); + + // 5. Compress the SVG bytes using GZip + string gzPath = "worksheet.svg.gz"; + using (FileStream gzFile = new FileStream(gzPath, FileMode.Create, FileAccess.Write)) + using (GZipStream gzip = new GZipStream(gzFile, CompressionMode.Compress)) + { + gzip.Write(svgBytes, 0, svgBytes.Length); + } + + // 6. Output information about the compression result + Console.WriteLine($"Original SVG size: {svgBytes.Length} bytes"); + Console.WriteLine($"Compressed GZip size: {new FileInfo(gzPath).Length} bytes"); + Console.WriteLine("SVG file has been compressed and saved as " + gzPath); + } + catch (Exception ex) + { + Console.WriteLine("An error occurred: " + ex.Message); + } + } + } +} \ No newline at end of file diff --git a/working-with-images/convert-a-workbook-to-tiff-using-eightbit-color-depth-for-smaller-output-files.cs b/working-with-images/convert-a-workbook-to-tiff-using-eightbit-color-depth-for-smaller-output-files.cs new file mode 100644 index 000000000..7ca310ba9 --- /dev/null +++ b/working-with-images/convert-a-workbook-to-tiff-using-eightbit-color-depth-for-smaller-output-files.cs @@ -0,0 +1,36 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; +using Aspose.Cells.Rendering; // for ImageOrPrintOptions, ColorDepth, TiffCompression + +namespace AsposeCellsTiffConversion +{ + class Program + { + static void Main() + { + // Load the source Excel workbook (replace with your actual file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Configure image rendering options for TIFF output + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Tiff, // Set output format to TIFF + TiffColorDepth = ColorDepth.Format8bpp, // Use 8‑bit color depth for smaller file size + TiffCompression = TiffCompression.CompressionLZW // Optional: apply LZW compression + }; + + // Create a renderer for the whole workbook with the specified options + WorkbookRender renderer = new WorkbookRender(workbook, options); + + // Render the workbook to a multi‑page TIFF file using the 8‑bit color depth setting + renderer.ToImage("output_8bpp.tiff"); + + // Clean up resources + renderer.Dispose(); + + Console.WriteLine("Workbook successfully converted to 8‑bit TIFF: output_8bpp.tiff"); + } + } +} \ No newline at end of file diff --git a/working-with-images/convert-a-workbook-to-tiff-using-twentyfourbit-color-depth-for-highquality-images.cs b/working-with-images/convert-a-workbook-to-tiff-using-twentyfourbit-color-depth-for-highquality-images.cs new file mode 100644 index 000000000..4cc5ffc3a --- /dev/null +++ b/working-with-images/convert-a-workbook-to-tiff-using-twentyfourbit-color-depth-for-highquality-images.cs @@ -0,0 +1,38 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; +using Aspose.Cells.Rendering; // for ImageOrPrintOptions, ColorDepth, TiffCompression + +namespace AsposeCellsTiffDemo +{ + class Program + { + static void Main() + { + // 1. Create a new workbook (lifecycle create rule) + Workbook workbook = new Workbook(); + + // 2. Add some sample data to the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Aspose.Cells TIFF 24‑bit Demo"); + sheet.Cells["A2"].PutValue(DateTime.Now); + sheet.Cells["B1"].PutValue(12345); + sheet.Cells["B2"].PutValue(67890); + + // 3. Configure image rendering options for TIFF with 24‑bit color depth + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Tiff, // Specify TIFF output + TiffColorDepth = ColorDepth.Format24bpp, // 24‑bit color depth + TiffCompression = TiffCompression.CompressionLZW // Optional: LZW compression + }; + + // 4. Render the entire workbook to a multi‑page TIFF file (save rule) + WorkbookRender renderer = new WorkbookRender(workbook, options); + renderer.ToImage("Workbook_24bit.tiff"); + + Console.WriteLine("Workbook successfully rendered to 24‑bit TIFF: Workbook_24bit.tiff"); + } + } +} \ No newline at end of file diff --git a/working-with-images/convert-a-worksheet-to-png-and-embed-the-resulting-image-as-a-base64-string-in-json.cs b/working-with-images/convert-a-worksheet-to-png-and-embed-the-resulting-image-as-a-base64-string-in-json.cs new file mode 100644 index 000000000..b9b993f27 --- /dev/null +++ b/working-with-images/convert-a-worksheet-to-png-and-embed-the-resulting-image-as-a-base64-string-in-json.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using System.Text.Json; +using Aspose.Cells; +using Aspose.Cells.Drawing; +using Aspose.Cells.Rendering; + +class Program +{ + static void Main() + { + // Load the workbook (replace with your actual file path) + Workbook workbook = new Workbook("input.xlsx"); + Worksheet worksheet = workbook.Worksheets[0]; + + // Configure rendering options for PNG output + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Png, + OnePagePerSheet = true + }; + + // Create a SheetRender instance for the worksheet + SheetRender sheetRender = new SheetRender(worksheet, options); + + // Render the first page of the worksheet to a memory stream + using (MemoryStream imageStream = new MemoryStream()) + { + sheetRender.ToImage(0, imageStream); // Uses SheetRender.ToImage(int, Stream) rule + byte[] imageBytes = imageStream.ToArray(); + + // Convert the image bytes to a Base64 string + string base64Image = Convert.ToBase64String(imageBytes); + + // Create a simple JSON object containing the Base64 image + var jsonObject = new { imageBase64 = base64Image }; + string json = JsonSerializer.Serialize(jsonObject); + + // Output the JSON string + Console.WriteLine(json); + } + + // Clean up resources + sheetRender.Dispose(); + } +} \ No newline at end of file diff --git a/working-with-images/convert-a-worksheet-to-svg-with-the-viewbox-attribute-enabled-for-scalable-rendering.cs b/working-with-images/convert-a-worksheet-to-svg-with-the-viewbox-attribute-enabled-for-scalable-rendering.cs new file mode 100644 index 000000000..8a0506fee --- /dev/null +++ b/working-with-images/convert-a-worksheet-to-svg-with-the-viewbox-attribute-enabled-for-scalable-rendering.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +namespace AsposeCellsSvgExport +{ + class Program + { + static void Main(string[] args) + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data + worksheet.Cells["A1"].PutValue("Product"); + worksheet.Cells["B1"].PutValue("Quantity"); + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["B2"].PutValue(150); + worksheet.Cells["A3"].PutValue("Orange"); + worksheet.Cells["B3"].PutValue(250); + + // Set SVG rendering options (FitToViewPort enables viewBox) + SvgImageOptions svgOptions = new SvgImageOptions + { + FitToViewPort = true + }; + + // Render the worksheet to SVG + SheetRender renderer = new SheetRender(worksheet, svgOptions); + string outputPath = "WorksheetOutput.svg"; + + // Ensure the output directory exists + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)) ?? Directory.GetCurrentDirectory(); + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Export the first page (index 0) as SVG + renderer.ToImage(0, outputPath); + + Console.WriteLine("Worksheet has been exported to SVG with FitToViewPort enabled."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-images/convert-an-entire-workbook-to-a-multipage-tiff-using-default-rendering-options.cs b/working-with-images/convert-an-entire-workbook-to-a-multipage-tiff-using-default-rendering-options.cs new file mode 100644 index 000000000..25eb48fe6 --- /dev/null +++ b/working-with-images/convert-an-entire-workbook-to-a-multipage-tiff-using-default-rendering-options.cs @@ -0,0 +1,29 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; + +class Program +{ + static void Main() + { + // Create a new workbook and add some sample data + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Multi‑page TIFF rendering demo"); + // Add more rows to ensure the workbook spans multiple pages + sheet.Cells["A1000"].PutValue("End of data"); + + // Configure default image options for TIFF output + ImageOrPrintOptions options = new ImageOrPrintOptions(); + options.ImageType = ImageType.Tiff; // Default TIFF format + + // Create a workbook renderer with the specified options + WorkbookRender renderer = new WorkbookRender(workbook, options); + + // Render the entire workbook to a multi‑page TIFF file + renderer.ToImage("output.tiff"); + + Console.WriteLine("Workbook successfully rendered to multi‑page TIFF: output.tiff"); + } +} \ No newline at end of file diff --git a/working-with-images/convert-the-first-worksheet-of-a-workbook-to-png-using-default-resolution-for-quick-preview.cs b/working-with-images/convert-the-first-worksheet-of-a-workbook-to-png-using-default-resolution-for-quick-preview.cs new file mode 100644 index 000000000..60b419130 --- /dev/null +++ b/working-with-images/convert-the-first-worksheet-of-a-workbook-to-png-using-default-resolution-for-quick-preview.cs @@ -0,0 +1,32 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +class WorksheetToPng +{ + static void Main() + { + // Load an existing workbook (replace with your file path) + var workbook = new Workbook("input.xlsx"); + + // Get the first worksheet (index 0) + var worksheet = workbook.Worksheets[0]; + + // Set image rendering options – PNG format, default resolution + var options = new ImageOrPrintOptions + { + ImageType = Aspose.Cells.Drawing.ImageType.Png + }; + + // Create a SheetRender for the worksheet with the specified options + var sheetRender = new SheetRender(worksheet, options); + + // Render the first page (page index 0) to a PNG file + sheetRender.ToImage(0, "first_sheet.png"); + + // Release resources used by SheetRender + sheetRender.Dispose(); + + Console.WriteLine("First worksheet rendered to PNG successfully."); + } +} \ No newline at end of file diff --git a/working-with-images/convert-the-workbook-tiff-to-pdf-by-invoking-a-thirdparty-converter-after-image-generation.cs b/working-with-images/convert-the-workbook-tiff-to-pdf-by-invoking-a-thirdparty-converter-after-image-generation.cs new file mode 100644 index 000000000..a320cc7d9 --- /dev/null +++ b/working-with-images/convert-the-workbook-tiff-to-pdf-by-invoking-a-thirdparty-converter-after-image-generation.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Drawing; +using Aspose.Cells.Rendering; + +class Program +{ + static void Main() + { + // Load the source workbook (uses the load rule) + Workbook workbook = new Workbook("input.xlsx"); + + // Configure options for rendering the workbook as a multi‑page TIFF + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Tiff, + TiffCompression = TiffCompression.CompressionLZW + }; + + // Render the entire workbook to a TIFF file (uses the WorkbookRender.ToImage(string) rule) + string tiffPath = "workbook.tiff"; + WorkbookRender renderer = new WorkbookRender(workbook, options); + renderer.ToImage(tiffPath); + + // Convert the generated TIFF to PDF using a third‑party converter (placeholder implementation) + string pdfPath = "workbook.pdf"; + ConvertTiffToPdf(tiffPath, pdfPath); + + Console.WriteLine("TIFF to PDF conversion completed."); + } + + // Placeholder for third‑party TIFF‑to‑PDF conversion logic + static void ConvertTiffToPdf(string tiffFile, string pdfFile) + { + // Example of how a third‑party library might be invoked: + // var converter = new ThirdPartyPdfConverter(); + // converter.Convert(tiffFile, pdfFile); + + // For demonstration purposes, simply copy the file (no real conversion) + File.Copy(tiffFile, pdfFile, overwrite: true); + } +} \ No newline at end of file diff --git a/working-with-images/embed-the-generated-svg-worksheet-file-into-an-html-document-using-the-object-tag-for-display.cs b/working-with-images/embed-the-generated-svg-worksheet-file-into-an-html-document-using-the-object-tag-for-display.cs new file mode 100644 index 000000000..2b525c008 --- /dev/null +++ b/working-with-images/embed-the-generated-svg-worksheet-file-into-an-html-document-using-the-object-tag-for-display.cs @@ -0,0 +1,83 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +namespace AsposeCellsSvgToHtmlDemo +{ + class Program + { + static void Main() + { + try + { + // ------------------------------------------------------------- + // 1. Create a workbook and add sample data to the first sheet + // ------------------------------------------------------------- + Workbook workbook = new Workbook(); // create a new workbook + Worksheet sheet = workbook.Worksheets[0]; // get the first worksheet + + // Populate cells + sheet.Cells["A1"].PutValue("Product"); + sheet.Cells["B1"].PutValue("Quantity"); + sheet.Cells["A2"].PutValue("Apple"); + sheet.Cells["B2"].PutValue(120); + sheet.Cells["A3"].PutValue("Orange"); + sheet.Cells["B3"].PutValue(85); + + // ------------------------------------------------------------- + // 2. Render the worksheet to an SVG file + // ------------------------------------------------------------- + SvgImageOptions svgOptions = new SvgImageOptions(); // options for SVG rendering + svgOptions.FitToViewPort = true; // fit SVG to viewport + + // Render the first page of the sheet to SVG + SheetRender renderer = new SheetRender(sheet, svgOptions); + string svgFileName = "worksheet.svg"; + renderer.ToImage(0, svgFileName); // save SVG file + + // ------------------------------------------------------------- + // 3. Create a simple HTML document that embeds the SVG + // ------------------------------------------------------------- + string htmlContent = $@" + + + + + Worksheet SVG in HTML + + + +

Worksheet rendered as SVG

+
+ + Your browser does not support SVG. + +
+ +"; + + // Save the HTML file + string htmlFileName = "worksheet.html"; + File.WriteAllText(htmlFileName, htmlContent); + + // ------------------------------------------------------------- + // 4. (Optional) Save the original workbook for reference + // ------------------------------------------------------------- + workbook.Save("original_workbook.xlsx"); + + Console.WriteLine($"SVG generated: {Path.GetFullPath(svgFileName)}"); + Console.WriteLine($"HTML generated: {Path.GetFullPath(htmlFileName)}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-images/embed-the-resulting-tiff-image-into-an-html-page-using-an-img-tag-with-appropriate-source-attribute.cs b/working-with-images/embed-the-resulting-tiff-image-into-an-html-page-using-an-img-tag-with-appropriate-source-attribute.cs new file mode 100644 index 000000000..6185b798e --- /dev/null +++ b/working-with-images/embed-the-resulting-tiff-image-into-an-html-page-using-an-img-tag-with-appropriate-source-attribute.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; + +class Program +{ + static void Main() + { + // Create a new workbook and add sample content + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + worksheet.Cells["A1"].PutValue("Aspose.Cells TIFF to HTML Demo"); + + // Configure rendering options for TIFF output + ImageOrPrintOptions renderOptions = new ImageOrPrintOptions + { + OnePagePerSheet = true, + ImageType = ImageType.Tiff + }; + + // Render the worksheet to a TIFF image stored in a memory stream + SheetRender sheetRenderer = new SheetRender(worksheet, renderOptions); + using (MemoryStream tiffStream = new MemoryStream()) + { + sheetRenderer.ToTiff(tiffStream); // Render to TIFF stream + + // Convert the TIFF bytes to a Base64 string + string base64Tiff = Convert.ToBase64String(tiffStream.ToArray()); + + // Build an HTML document that embeds the TIFF image using a data URI + string htmlContent = $@" + +Embedded TIFF Image + +

Embedded TIFF Image

+ + +"; + + // Save the HTML to a file + File.WriteAllText("output.html", htmlContent); + } + + Console.WriteLine("HTML file with embedded TIFF image has been created."); + } +} \ No newline at end of file diff --git a/working-with-images/export-a-chart-to-svg-with-viewbox-attribute-for-responsive-scaling-in-modern-browsers.cs b/working-with-images/export-a-chart-to-svg-with-viewbox-attribute-for-responsive-scaling-in-modern-browsers.cs new file mode 100644 index 000000000..fe7eda78c --- /dev/null +++ b/working-with-images/export-a-chart-to-svg-with-viewbox-attribute-for-responsive-scaling-in-modern-browsers.cs @@ -0,0 +1,44 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Charts; +using Aspose.Cells.Drawing; +using Aspose.Cells.Rendering; + +class ExportChartToResponsiveSvg +{ + static void Main() + { + // ---------- Create a new workbook ---------- + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // ---------- Populate worksheet with sample data ---------- + worksheet.Cells["A1"].PutValue("Category"); + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["A3"].PutValue("Orange"); + worksheet.Cells["A4"].PutValue("Banana"); + + worksheet.Cells["B1"].PutValue("Value"); + worksheet.Cells["B2"].PutValue(120); + worksheet.Cells["B3"].PutValue(80); + worksheet.Cells["B4"].PutValue(150); + + // ---------- Add a column chart ---------- + int chartIndex = worksheet.Charts.Add(ChartType.Column, 5, 0, 20, 10); + Chart chart = worksheet.Charts[chartIndex]; + chart.NSeries.Add("B2:B4", true); // Values + chart.NSeries.CategoryData = "A2:A4"; // Categories + chart.Title.Text = "Fruit Sales"; + + // ---------- Configure SVG rendering options ---------- + SvgImageOptions svgOptions = new SvgImageOptions(); + svgOptions.ImageType = ImageType.Svg; // Ensure output format is SVG + svgOptions.FitToViewPort = true; // Adds viewBox attribute for responsive scaling + + // ---------- Export the chart to an SVG file ---------- + // The file will contain a viewBox attribute, allowing the SVG to scale with the viewport. + chart.ToImage("FruitSales.svg", svgOptions); + + Console.WriteLine("Chart exported to SVG with responsive viewBox."); + } +} \ No newline at end of file diff --git a/working-with-images/export-a-worksheet-to-svg-without-the-viewbox-attribute-to-produce-fixedsize-vector-output.cs b/working-with-images/export-a-worksheet-to-svg-without-the-viewbox-attribute-to-produce-fixedsize-vector-output.cs new file mode 100644 index 000000000..0ff1d60a9 --- /dev/null +++ b/working-with-images/export-a-worksheet-to-svg-without-the-viewbox-attribute-to-produce-fixedsize-vector-output.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +class Program +{ + static void Main() + { + try + { + const string inputPath = "input.xlsx"; + const string outputPath = "output.svg"; + + // Verify that the input workbook exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Error: Input file \"{inputPath}\" not found."); + return; + } + + // Load the workbook + Workbook workbook = new Workbook(inputPath); + + // Get the first worksheet to be exported + Worksheet worksheet = workbook.Worksheets[0]; + + // Configure SVG rendering options + SvgImageOptions svgOptions = new SvgImageOptions + { + // Disable viewBox attribute for fixed‑size output + FitToViewPort = false, + // Render the whole sheet on a single page + OnePagePerSheet = true + }; + + // Render the worksheet to an SVG file + SheetRender sheetRender = new SheetRender(worksheet, svgOptions); + sheetRender.ToImage(0, outputPath); + + Console.WriteLine($"Worksheet exported to SVG without viewBox: \"{outputPath}\""); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-images/export-the-worksheet-named-chart-to-bmp-at-96-dpi-resolution-for-legacy-image-compatibility.cs b/working-with-images/export-the-worksheet-named-chart-to-bmp-at-96-dpi-resolution-for-legacy-image-compatibility.cs new file mode 100644 index 000000000..961cb223b --- /dev/null +++ b/working-with-images/export-the-worksheet-named-chart-to-bmp-at-96-dpi-resolution-for-legacy-image-compatibility.cs @@ -0,0 +1,35 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; + +class ExportWorksheetToBmp +{ + static void Main() + { + // Load the workbook (replace with your actual file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Get the worksheet named "Chart" + Worksheet chartSheet = workbook.Worksheets["Chart"]; + if (chartSheet == null) + { + Console.WriteLine("Worksheet named 'Chart' was not found."); + return; + } + + // Configure image options: BMP format, 96 DPI resolution + ImageOrPrintOptions options = new ImageOrPrintOptions(); + options.ImageType = ImageType.Bmp; // Set output format to BMP + options.VerticalResolution = 96; // Set vertical DPI to 96 + // HorizontalResolution defaults to 96 DPI; set explicitly if needed: + // options.HorizontalResolution = 96; + + // Render the worksheet to an image + SheetRender renderer = new SheetRender(chartSheet, options); + // Render the first (and usually only) page to a BMP file + renderer.ToImage(0, "Chart.bmp"); + + Console.WriteLine("Worksheet 'Chart' exported to Chart.bmp at 96 DPI."); + } +} \ No newline at end of file diff --git a/working-with-images/extract-every-chart-from-a-workbook-and-export-them-as-svg-files-into-a-designated-subfolder.cs b/working-with-images/extract-every-chart-from-a-workbook-and-export-them-as-svg-files-into-a-designated-subfolder.cs new file mode 100644 index 000000000..f976566d4 --- /dev/null +++ b/working-with-images/extract-every-chart-from-a-workbook-and-export-them-as-svg-files-into-a-designated-subfolder.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Charts; +using Aspose.Cells.Drawing; + +namespace AsposeCellsChartExport +{ + class Program + { + static void Main() + { + // Path to the source workbook + string workbookPath = "input.xlsx"; + + // Load the workbook (lifecycle rule: use load) + Workbook workbook = new Workbook(workbookPath); + + // Define the output folder for SVG files and ensure it exists + string outputFolder = Path.Combine(Environment.CurrentDirectory, "ExportedCharts"); + Directory.CreateDirectory(outputFolder); + + // Iterate through all worksheets + for (int sheetIdx = 0; sheetIdx < workbook.Worksheets.Count; sheetIdx++) + { + Worksheet sheet = workbook.Worksheets[sheetIdx]; + ChartCollection charts = sheet.Charts; + + // Iterate through all charts in the current worksheet + for (int chartIdx = 0; chartIdx < charts.Count; chartIdx++) + { + Chart chart = charts[chartIdx]; + + // Build a unique file name for each chart + string fileName = $"Sheet{sheetIdx + 1}_Chart{chartIdx + 1}.svg"; + string filePath = Path.Combine(outputFolder, fileName); + + // Export the chart to SVG using the ToImage method with ImageType.Svg + chart.ToImage(filePath, ImageType.Svg); + } + } + + Console.WriteLine($"All charts have been exported to SVG files in folder: {outputFolder}"); + } + } +} \ No newline at end of file diff --git a/working-with-images/generate-a-jpeg-image-from-a-worksheet-with-custom-image-quality-set-to-80-percent.cs b/working-with-images/generate-a-jpeg-image-from-a-worksheet-with-custom-image-quality-set-to-80-percent.cs new file mode 100644 index 000000000..99189062d --- /dev/null +++ b/working-with-images/generate-a-jpeg-image-from-a-worksheet-with-custom-image-quality-set-to-80-percent.cs @@ -0,0 +1,30 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; + +class Program +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Add some sample data to the worksheet + worksheet.Cells["A1"].PutValue("Sample text for JPEG rendering"); + + // Configure image options: set JPEG format and custom quality (80%) + ImageOrPrintOptions options = new ImageOrPrintOptions(); + options.ImageType = ImageType.Jpeg; // Output format + options.Quality = 80; // JPEG quality (0-100) + + // Create a SheetRender instance with the worksheet and options + SheetRender renderer = new SheetRender(worksheet, options); + + // Render the first page (index 0) to a JPEG file + renderer.ToImage(0, "WorksheetImage_Quality80.jpg"); + + Console.WriteLine("Worksheet rendered to JPEG with quality 80%."); + } +} \ No newline at end of file diff --git a/working-with-images/generate-a-multipage-tiff-from-the-first-three-worksheets-of-a-loaded-workbook.cs b/working-with-images/generate-a-multipage-tiff-from-the-first-three-worksheets-of-a-loaded-workbook.cs new file mode 100644 index 000000000..f29d6a6ef --- /dev/null +++ b/working-with-images/generate-a-multipage-tiff-from-the-first-three-worksheets-of-a-loaded-workbook.cs @@ -0,0 +1,51 @@ +using System; +using System.IO; +using System.Collections.Generic; +using Aspose.Cells; +using Aspose.Cells.Drawing; +using Aspose.Cells.Rendering; + +class Program +{ + static void Main() + { + const string inputPath = "input.xlsx"; + const string outputPath = "output.tiff"; + + // Verify that the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Error: Input file \"{inputPath}\" not found."); + return; + } + + try + { + // Load the source workbook + Workbook workbook = new Workbook(inputPath); + + // Determine which worksheets to render (up to the first three) + int sheetCount = Math.Min(3, workbook.Worksheets.Count); + int[] sheetIndexes = new int[sheetCount]; + for (int i = 0; i < sheetCount; i++) + sheetIndexes[i] = i; + + // Configure rendering options for a multi‑page TIFF + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Tiff, + SheetSet = new SheetSet(sheetIndexes) + }; + + // Render the selected sheets to a TIFF file + WorkbookRender renderer = new WorkbookRender(workbook, options); + renderer.ToImage(outputPath); + + Console.WriteLine("Multi‑page TIFF created successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-images/include-the-svg-chart-file-in-a-web-page-to-allow-interactive-zoom-and-pan-features.cs b/working-with-images/include-the-svg-chart-file-in-a-web-page-to-allow-interactive-zoom-and-pan-features.cs new file mode 100644 index 000000000..15e00bd69 --- /dev/null +++ b/working-with-images/include-the-svg-chart-file-in-a-web-page-to-allow-interactive-zoom-and-pan-features.cs @@ -0,0 +1,148 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Charts; +using Aspose.Cells.Rendering; + +namespace AsposeCellsSvgWebDemo +{ + class Program + { + static void Main() + { + try + { + // 1. Create a workbook and populate it with sample data + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + sheet.Cells["A1"].PutValue("Month"); + sheet.Cells["A2"].PutValue("Jan"); + sheet.Cells["A3"].PutValue("Feb"); + sheet.Cells["A4"].PutValue("Mar"); + sheet.Cells["A5"].PutValue("Apr"); + + sheet.Cells["B1"].PutValue("Sales"); + sheet.Cells["B2"].PutValue(12000); + sheet.Cells["B3"].PutValue(15000); + sheet.Cells["B4"].PutValue(18000); + sheet.Cells["B5"].PutValue(21000); + + // 2. Add a line chart that uses the data + int chartIndex = sheet.Charts.Add(ChartType.Line, 7, 0, 25, 10); + Chart chart = sheet.Charts[chartIndex]; + chart.NSeries.Add("B2:B5", true); // Values + chart.NSeries.CategoryData = "A2:A5"; // Categories + chart.Title.Text = "Monthly Sales"; + + // 3. Configure SVG rendering options – enable FitToViewPort for responsive scaling + SvgImageOptions svgOptions = new SvgImageOptions + { + FitToViewPort = true, + CssPrefix = "chart-" + }; + + // 4. Render the chart to an SVG file + string svgPath = "chart.svg"; + chart.ToImage(svgPath, svgOptions); + + // 5. Load the generated SVG content (ensure file exists) + if (!File.Exists(svgPath)) + throw new FileNotFoundException("SVG file was not created.", svgPath); + + string svgContent = File.ReadAllText(svgPath); + + // 6. Build an HTML page that embeds the SVG and adds simple zoom/pan support + string htmlTemplate = $@" + + + + + Interactive SVG Chart + + + +

Interactive Zoom & Pan for Aspose.Cells SVG Chart

+
+ {svgContent} +
+ + + +"; + + // 7. Save the HTML file + string htmlPath = "chart.html"; + File.WriteAllText(htmlPath, htmlTemplate); + + Console.WriteLine($"SVG chart generated at: {Path.GetFullPath(svgPath)}"); + Console.WriteLine($"Interactive HTML page generated at: {Path.GetFullPath(htmlPath)}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-images/iterate-through-each-worksheet-in-a-workbook-and-save-each-as-a-separate-png-file.cs b/working-with-images/iterate-through-each-worksheet-in-a-workbook-and-save-each-as-a-separate-png-file.cs new file mode 100644 index 000000000..6a6b9d955 --- /dev/null +++ b/working-with-images/iterate-through-each-worksheet-in-a-workbook-and-save-each-as-a-separate-png-file.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +class Program +{ + static void Main() + { + // Path to the source workbook + string inputPath = "input.xlsx"; + + // Directory where PNG files will be saved + string outputDir = "output"; + Directory.CreateDirectory(outputDir); + + // Load the workbook + Workbook workbook = new Workbook(inputPath); + + // Configure rendering options for PNG output + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = Aspose.Cells.Drawing.ImageType.Png, + OnePagePerSheet = true // Ensure each sheet renders to a single page + }; + + // Iterate through each worksheet and save as a separate PNG file + for (int i = 0; i < workbook.Worksheets.Count; i++) + { + Worksheet sheet = workbook.Worksheets[i]; + + // Create a SheetRender for the current worksheet + SheetRender sheetRender = new SheetRender(sheet, options); + + // Build a safe file name using the worksheet name + string safeName = string.Concat(sheet.Name.Split(Path.GetInvalidFileNameChars())); + string outputPath = Path.Combine(outputDir, $"{safeName}.png"); + + // Render the first (and only) page of the sheet to a PNG file + sheetRender.ToImage(0, outputPath); + + // Release resources used by SheetRender + sheetRender.Dispose(); + } + + Console.WriteLine("All worksheets have been saved as separate PNG files."); + } +} \ No newline at end of file diff --git a/working-with-images/measure-conversion-duration-using-stopwatch-and-log-elapsed-time-for-performance-analysis.cs b/working-with-images/measure-conversion-duration-using-stopwatch-and-log-elapsed-time-for-performance-analysis.cs new file mode 100644 index 000000000..8b825f82e --- /dev/null +++ b/working-with-images/measure-conversion-duration-using-stopwatch-and-log-elapsed-time-for-performance-analysis.cs @@ -0,0 +1,41 @@ +using System; +using System.Diagnostics; +using Aspose.Cells; + +namespace AsposeCellsPerformanceDemo +{ + class Program + { + static void Main() + { + // Create a new workbook (creation rule) + Workbook workbook = new Workbook(); + + // Populate some data to simulate a realistic conversion workload + Worksheet sheet = workbook.Worksheets[0]; + for (int row = 0; row < 5000; row++) + { + for (int col = 0; col < 20; col++) + { + sheet.Cells[row, col].PutValue($"R{row}C{col}"); + } + } + + // Initialize Stopwatch to measure conversion duration + Stopwatch sw = new Stopwatch(); + + // Start timing just before the conversion (save) operation + sw.Start(); + + // Perform the conversion: save the workbook to a different format (e.g., PDF) + // This uses the standard Save method (save rule) + workbook.Save("ConversionResult.pdf", SaveFormat.Pdf); + + // Stop timing after the operation completes + sw.Stop(); + + // Log the elapsed time for performance analysis + Console.WriteLine($"Conversion completed in {sw.Elapsed.TotalMilliseconds} ms."); + } + } +} \ No newline at end of file diff --git a/working-with-images/perform-pixelbypixel-comparison-between-the-generated-png-worksheet-image-and-a-baseline-reference.cs b/working-with-images/perform-pixelbypixel-comparison-between-the-generated-png-worksheet-image-and-a-baseline-reference.cs new file mode 100644 index 000000000..808e9c690 --- /dev/null +++ b/working-with-images/perform-pixelbypixel-comparison-between-the-generated-png-worksheet-image-and-a-baseline-reference.cs @@ -0,0 +1,75 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +namespace AsposeCellsPixelComparison +{ + class Program + { + static void Main() + { + try + { + // ---------- 1. Create a sample workbook ---------- + var workbook = new Workbook(); + var sheet = workbook.Worksheets[0]; + + // Populate some sample data + sheet.Cells["A1"].PutValue("Pixel Comparison Demo"); + sheet.Cells["A2"].PutValue(123); + sheet.Cells["B2"].PutValue(456); + sheet.Cells["C3"].PutValue(DateTime.Now); + + // ---------- 2. Render the worksheet to a PNG image ---------- + var renderOptions = new ImageOrPrintOptions(); // defaults to PNG + var sheetRender = new SheetRender(sheet, renderOptions); + + byte[] generatedImageBytes; + using (var genStream = new MemoryStream()) + { + sheetRender.ToImage(0, genStream); + generatedImageBytes = genStream.ToArray(); + + // Optional: save the generated image for visual inspection + File.WriteAllBytes("generated.png", generatedImageBytes); + } + + // ---------- 3. Load the baseline reference image ---------- + const string baselinePath = "baseline.png"; + if (!File.Exists(baselinePath)) + { + Console.WriteLine($"Baseline image not found at path: {baselinePath}"); + return; + } + + byte[] baselineImageBytes = File.ReadAllBytes(baselinePath); + + // ---------- 4. Perform byte‑by‑byte comparison ---------- + bool imagesAreIdentical = CompareByteArrays(baselineImageBytes, generatedImageBytes); + + // ---------- 5. Output the result ---------- + Console.WriteLine(imagesAreIdentical + ? "The generated image matches the baseline reference byte by byte." + : "The generated image differs from the baseline reference."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + + // Simple byte array comparison + private static bool CompareByteArrays(byte[] a, byte[] b) + { + if (a == null || b == null) return false; + if (a.Length != b.Length) return false; + + for (int i = 0; i < a.Length; i++) + { + if (a[i] != b[i]) return false; + } + return true; + } + } +} \ No newline at end of file diff --git a/working-with-images/preserve-data-labels-visibility-when-converting-a-chart-to-png-to-retain-informational-context.cs b/working-with-images/preserve-data-labels-visibility-when-converting-a-chart-to-png-to-retain-informational-context.cs new file mode 100644 index 000000000..69da1fd41 --- /dev/null +++ b/working-with-images/preserve-data-labels-visibility-when-converting-a-chart-to-png-to-retain-informational-context.cs @@ -0,0 +1,43 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Charts; +using Aspose.Cells.Drawing; + +class Program +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for the chart + worksheet.Cells["A1"].PutValue("Category"); + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["A3"].PutValue("Orange"); + worksheet.Cells["A4"].PutValue("Banana"); + worksheet.Cells["B1"].PutValue("Value"); + worksheet.Cells["B2"].PutValue(1200); + worksheet.Cells["B3"].PutValue(800); + worksheet.Cells["B4"].PutValue(1500); + + // Add a column chart to the worksheet + int chartIndex = worksheet.Charts.Add(ChartType.Column, 5, 0, 20, 8); + Chart chart = worksheet.Charts[chartIndex]; + + // Set the data range for the chart + chart.SetChartDataRange("A1:B4", true); + + // Enable data labels and ensure they are visible + Series series = chart.NSeries[0]; + series.DataLabels.ShowValue = true; // display the numeric values + series.DataLabels.ShowCategoryName = true; // display the category names + series.DataLabels.IsDeleted = false; // make sure the label object is not marked as deleted + + // Convert the chart to a PNG image while preserving the data labels + chart.ToImage("ChartWithDataLabels.png", ImageType.Png); + + // Save the workbook (optional, but keeps the chart in the file) + workbook.Save("ChartWorkbook.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-images/render-a-chart-object-from-the-workbook-to-a-png-image-using-the-chartrender-api.cs b/working-with-images/render-a-chart-object-from-the-workbook-to-a-png-image-using-the-chartrender-api.cs new file mode 100644 index 000000000..c2ca9e702 --- /dev/null +++ b/working-with-images/render-a-chart-object-from-the-workbook-to-a-png-image-using-the-chartrender-api.cs @@ -0,0 +1,47 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Charts; +using Aspose.Cells.Drawing; + +namespace ChartRenderExample +{ + class Program + { + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for the chart + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["A2"].PutValue("Apple"); + sheet.Cells["A3"].PutValue("Orange"); + sheet.Cells["A4"].PutValue("Banana"); + + sheet.Cells["B1"].PutValue("Value"); + sheet.Cells["B2"].PutValue(1200); + sheet.Cells["B3"].PutValue(800); + sheet.Cells["B4"].PutValue(1500); + + // Add a column chart to the worksheet + int chartIndex = sheet.Charts.Add(ChartType.Column, 5, 0, 20, 8); + Chart chart = sheet.Charts[chartIndex]; + + // Set the data range for the chart + chart.SetChartDataRange("A1:B4", true); + + // Render the chart to a PNG image file using the Chart API + string outputImagePath = "ChartOutput.png"; + chart.ToImage(outputImagePath, ImageType.Png); + + // Optionally, save the workbook for reference + workbook.Save("ChartWorkbook.xlsx"); + + Console.WriteLine($"Chart rendered and saved to '{outputImagePath}'."); + Console.WriteLine("Workbook saved as 'ChartWorkbook.xlsx'."); + } + } +} \ No newline at end of file diff --git a/working-with-images/render-a-workbook-as-tiff-using-300-dpi-resolution-to-improve-image-clarity.cs b/working-with-images/render-a-workbook-as-tiff-using-300-dpi-resolution-to-improve-image-clarity.cs new file mode 100644 index 000000000..6bbbd2e0d --- /dev/null +++ b/working-with-images/render-a-workbook-as-tiff-using-300-dpi-resolution-to-improve-image-clarity.cs @@ -0,0 +1,32 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; + +class RenderWorkbookToTiff +{ + static void Main() + { + // Create a new workbook (or load an existing one) + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Sample data for TIFF rendering"); + sheet.Cells["A2"].PutValue(DateTime.Now); + + // Configure image options: TIFF format with 300 DPI resolution + ImageOrPrintOptions options = new ImageOrPrintOptions(); + options.ImageType = ImageType.Tiff; // Set output format to TIFF + options.HorizontalResolution = 300; // 300 DPI horizontally + options.VerticalResolution = 300; // 300 DPI vertically + options.TiffCompression = TiffCompression.CompressionLZW; // Optional compression + + // Create a renderer for the whole workbook + WorkbookRender renderer = new WorkbookRender(workbook, options); + + // Render the workbook to a TIFF file + string outputFile = "workbook_300dpi.tiff"; + renderer.ToImage(outputFile); + + Console.WriteLine($"Workbook successfully rendered to TIFF at {outputFile} with 300 DPI."); + } +} \ No newline at end of file diff --git a/working-with-images/render-a-workbook-to-tiff-and-write-the-result-into-a-memory-stream-for-further-processing.cs b/working-with-images/render-a-workbook-to-tiff-and-write-the-result-into-a-memory-stream-for-further-processing.cs new file mode 100644 index 000000000..d26fc58a1 --- /dev/null +++ b/working-with-images/render-a-workbook-to-tiff-and-write-the-result-into-a-memory-stream-for-further-processing.cs @@ -0,0 +1,50 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; + +namespace AsposeCellsTiffRender +{ + public class Program + { + public static void Main() + { + // Create a new workbook (or load an existing one) + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Render this worksheet to TIFF in a memory stream."); + + // Configure rendering options for TIFF output + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Tiff, // Specify TIFF format + TiffCompression = TiffCompression.CompressionLZW, // Optional compression + OnePagePerSheet = true // Render the whole sheet as one page + }; + + // Initialize the workbook renderer with the workbook and options + WorkbookRender renderer = new WorkbookRender(workbook, options); + + // Create a memory stream to hold the TIFF image + using (MemoryStream tiffStream = new MemoryStream()) + { + // Render the entire workbook to the memory stream as a TIFF image + renderer.ToImage(tiffStream); + + // Reset the stream position if it will be read later + tiffStream.Position = 0; + + // Example: display the size of the generated TIFF data + Console.WriteLine($"TIFF image generated. Stream length: {tiffStream.Length} bytes"); + + // Further processing can be done here using tiffStream + // For instance, save to a file for verification (optional) + // File.WriteAllBytes("output.tiff", tiffStream.ToArray()); + } + + // Clean up resources + renderer.Dispose(); + } + } +} \ No newline at end of file diff --git a/working-with-images/render-a-workbook-to-tiff-with-horizontal-and-vertical-resolutions-set-to-150-dpi.cs b/working-with-images/render-a-workbook-to-tiff-with-horizontal-and-vertical-resolutions-set-to-150-dpi.cs new file mode 100644 index 000000000..fd6edd55b --- /dev/null +++ b/working-with-images/render-a-workbook-to-tiff-with-horizontal-and-vertical-resolutions-set-to-150-dpi.cs @@ -0,0 +1,39 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; + +namespace AsposeCellsTiffRenderDemo +{ + class Program + { + static void Main() + { + // Create a new workbook (or load an existing one) + Workbook workbook = new Workbook(); // creates an empty workbook + Worksheet sheet = workbook.Worksheets[0]; + + // Add some sample data to demonstrate rendering + sheet.Cells["A1"].PutValue("Aspose.Cells TIFF Rendering Demo"); + sheet.Cells["A2"].PutValue(DateTime.Now); + + // Configure image rendering options + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Tiff, // Set output format to TIFF + HorizontalResolution = 150, // Set horizontal DPI + VerticalResolution = 150, // Set vertical DPI + OnePagePerSheet = true // Render the whole sheet on one page + }; + + // Create a workbook renderer with the specified options + WorkbookRender renderer = new WorkbookRender(workbook, options); + + // Render the entire workbook to a multi‑page TIFF file + string outputPath = "RenderedWorkbook.tiff"; + renderer.ToImage(outputPath); + + Console.WriteLine($"Workbook successfully rendered to TIFF at: {outputPath}"); + } + } +} \ No newline at end of file diff --git a/working-with-images/render-a-worksheet-to-jpeg-and-upload-the-image-file-to-a-cloud-storage-bucket.cs b/working-with-images/render-a-worksheet-to-jpeg-and-upload-the-image-file-to-a-cloud-storage-bucket.cs new file mode 100644 index 000000000..618493369 --- /dev/null +++ b/working-with-images/render-a-worksheet-to-jpeg-and-upload-the-image-file-to-a-cloud-storage-bucket.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +class Program +{ + static void Main() + { + try + { + // 1. Create a new workbook and add some sample data + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Sample Data"); + sheet.Cells["B1"].PutValue(123); + sheet.Cells["A2"].PutValue("More Data"); + sheet.Cells["B2"].PutValue(456); + + // 2. Configure image rendering options for JPEG output + ImageOrPrintOptions imgOptions = new ImageOrPrintOptions + { + ImageType = Aspose.Cells.Drawing.ImageType.Jpeg, + OnePagePerSheet = true // render each sheet as a single page + }; + + // 3. Create a SheetRender instance (does not implement IDisposable) + SheetRender sheetRender = new SheetRender(sheet, imgOptions); + + // 4. Render the first page of the worksheet to a memory stream + using (MemoryStream imageStream = new MemoryStream()) + { + sheetRender.ToImage(0, imageStream); + imageStream.Position = 0; // reset stream position for saving + + // 5. Save the JPEG image locally (replace with cloud upload if needed) + string outputPath = Path.Combine(Environment.CurrentDirectory, "worksheet_page0.jpg"); + using (FileStream fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) + { + imageStream.CopyTo(fileStream); + } + + Console.WriteLine($"Worksheet rendered to JPEG and saved to: {outputPath}"); + } + + // Clean up resources + workbook.Dispose(); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-images/render-a-worksheet-to-jpeg-with-gridlines-hidden-by-setting-isgridlinesvisible-to-false.cs b/working-with-images/render-a-worksheet-to-jpeg-with-gridlines-hidden-by-setting-isgridlinesvisible-to-false.cs new file mode 100644 index 000000000..628977600 --- /dev/null +++ b/working-with-images/render-a-worksheet-to-jpeg-with-gridlines-hidden-by-setting-isgridlinesvisible-to-false.cs @@ -0,0 +1,45 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +namespace AsposeCellsRenderExample +{ + class Program + { + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + + // Add some sample data (optional, just to have visible content) + worksheet.Cells["A1"].PutValue("Sample Data"); + worksheet.Cells["B2"].PutValue(123); + worksheet.Cells["C3"].PutValue(DateTime.Now); + + // Hide gridlines for rendering + worksheet.IsGridlinesVisible = false; + + // Configure image rendering options for JPEG + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = Aspose.Cells.Drawing.ImageType.Jpeg, + // Optional: set JPEG quality (0-100) + Quality = 90 + }; + + // Create a SheetRender instance for the worksheet + SheetRender sheetRender = new SheetRender(worksheet, options); + + // Render the first page (index 0) to a JPEG file + sheetRender.ToImage(0, "RenderedWorksheet.jpg"); + + // Clean up resources + sheetRender.Dispose(); + + Console.WriteLine("Worksheet rendered to JPEG with gridlines hidden."); + } + } +} \ No newline at end of file diff --git a/working-with-images/render-the-svg-worksheet-image-in-a-wpf-image-control-for-display-within-a-desktop-application.cs b/working-with-images/render-the-svg-worksheet-image-in-a-wpf-image-control-for-display-within-a-desktop-application.cs new file mode 100644 index 000000000..d2d47754f --- /dev/null +++ b/working-with-images/render-the-svg-worksheet-image-in-a-wpf-image-control-for-display-within-a-desktop-application.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Drawing; +using Aspose.Cells.Rendering; + +namespace AsposeSvgDemo +{ + class Program + { + [STAThread] + static void Main() + { + try + { + RenderWorksheet(); + Console.WriteLine("Rendering completed."); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Unexpected error: {ex.Message}"); + } + } + + private static void RenderWorksheet() + { + try + { + // Create workbook and fill with sample data + var workbook = new Workbook(); + var worksheet = workbook.Worksheets[0]; + worksheet.Cells["A1"].PutValue("Item"); + worksheet.Cells["B1"].PutValue("Quantity"); + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["B2"].PutValue(10); + worksheet.Cells["A3"].PutValue("Orange"); + worksheet.Cells["B3"].PutValue(15); + + // ---------- SVG rendering ---------- + var svgOptions = new SvgImageOptions + { + FitToViewPort = true + }; + var svgRenderer = new SheetRender(worksheet, svgOptions); + string svgPath = Path.Combine(Path.GetTempPath(), "worksheet.svg"); + Directory.CreateDirectory(Path.GetDirectoryName(svgPath)!); + svgRenderer.ToImage(0, svgPath); // page index 0, save to file + + // ---------- PNG rendering ---------- + var pngOptions = new ImageOrPrintOptions + { + ImageType = ImageType.Png + }; + var pngRenderer = new SheetRender(worksheet, pngOptions); + string pngPath = Path.Combine(Path.GetTempPath(), "worksheet.png"); + pngRenderer.ToImage(0, pngPath); // page index 0, save to file + + Console.WriteLine($"SVG saved to: {svgPath}"); + Console.WriteLine($"PNG saved to: {pngPath}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Failed to render worksheet: {ex.Message}"); + throw; + } + } + } +} \ No newline at end of file diff --git a/working-with-images/save-a-generated-tiff-file-directly-to-a-network-share-path-after-converting-the-workbook.cs b/working-with-images/save-a-generated-tiff-file-directly-to-a-network-share-path-after-converting-the-workbook.cs new file mode 100644 index 000000000..5656252e6 --- /dev/null +++ b/working-with-images/save-a-generated-tiff-file-directly-to-a-network-share-path-after-converting-the-workbook.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +class SaveTiffToNetworkShare +{ + static void Main() + { + try + { + // Create a new workbook and add sample data + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + worksheet.Cells["A1"].PutValue("Aspose.Cells TIFF Export Demo"); + + // Configure rendering options (optional settings) + ImageOrPrintOptions renderOptions = new ImageOrPrintOptions + { + OnePagePerSheet = true // Render the whole sheet on a single page + }; + + // Initialize the sheet renderer with the worksheet and options + SheetRender sheetRenderer = new SheetRender(worksheet, renderOptions); + + // Define the network share path where the TIFF will be saved + string networkSharePath = @"\\Server\Share\Folder\output.tiff"; + + // Ensure the target directory exists; create it if necessary + string targetDir = Path.GetDirectoryName(networkSharePath); + if (!Directory.Exists(targetDir)) + { + Directory.CreateDirectory(targetDir); + } + + // Render the worksheet directly to a TIFF file on the network share + sheetRenderer.ToTiff(networkSharePath); + + Console.WriteLine($"TIFF file successfully saved to: {networkSharePath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-images/save-the-svg-worksheet-image-to-a-svg-file-with-utf8-encoding-to-preserve-character-data.cs b/working-with-images/save-the-svg-worksheet-image-to-a-svg-file-with-utf8-encoding-to-preserve-character-data.cs new file mode 100644 index 000000000..56578ad61 --- /dev/null +++ b/working-with-images/save-the-svg-worksheet-image-to-a-svg-file-with-utf8-encoding-to-preserve-character-data.cs @@ -0,0 +1,42 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Rendering; // For SvgImageOptions +using Aspose.Cells.Drawing; // For ImageType + +class SaveWorksheetAsSvgUtf8 +{ + static void Main() + { + // Create a new workbook (lifecycle: create) + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Populate cells with Unicode characters to demonstrate UTF‑8 preservation + sheet.Cells["A1"].PutValue("中文字符"); // Chinese + sheet.Cells["A2"].PutValue("😀 Emoji"); // Emoji + sheet.Cells["A3"].PutValue("Привет"); // Cyrillic + + // Configure SVG rendering options + SvgImageOptions svgOptions = new SvgImageOptions + { + // Ensure the output format is SVG + ImageType = ImageType.Svg, + + // Fit the generated SVG to the viewport (optional, but commonly used) + FitToViewPort = true + }; + + // Render the worksheet to an SVG file. + // The ToImage method writes the SVG content using UTF‑8 encoding internally. + SheetRender renderer = new SheetRender(sheet, svgOptions); + renderer.ToImage(0, "WorksheetOutput.svg"); // Saves the SVG file + + // Optional: Save the workbook itself in XLSX format (demonstrates use of the save rule) + workbook.Save("WorkbookOutput.xlsx", SaveFormat.Xlsx); + + Console.WriteLine("Worksheet saved as SVG with UTF‑8 encoding: WorksheetOutput.svg"); + } +} \ No newline at end of file diff --git a/working-with-images/send-the-png-worksheet-image-via-http-post-to-a-rest-endpoint-for-downstream-processing.cs b/working-with-images/send-the-png-worksheet-image-via-http-post-to-a-rest-endpoint-for-downstream-processing.cs new file mode 100644 index 000000000..56605bebf --- /dev/null +++ b/working-with-images/send-the-png-worksheet-image-via-http-post-to-a-rest-endpoint-for-downstream-processing.cs @@ -0,0 +1,47 @@ +using System; +using System.IO; +using System.Net.Http; +using System.Net.Http.Headers; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; + +class Program +{ + static async System.Threading.Tasks.Task Main() + { + // Create a new workbook (create rule) + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + worksheet.Cells["A1"].PutValue("Sample Data for PNG rendering"); + + // Configure image rendering options (PNG) + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Png, + OnePagePerSheet = true + }; + + // Render the first page of the worksheet to a memory stream (SheetRender.ToImage(int, Stream) rule) + using (MemoryStream imageStream = new MemoryStream()) + { + SheetRender sheetRender = new SheetRender(worksheet, options); + sheetRender.ToImage(0, imageStream); + imageStream.Position = 0; // reset for reading + + // Prepare HTTP client for POST + using (HttpClient client = new HttpClient()) + { + string endpoint = "https://example.com/api/upload"; // replace with actual URL + + // Create content from the image stream + var content = new StreamContent(imageStream); + content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); + + // Send POST request + HttpResponseMessage response = await client.PostAsync(endpoint, content); + Console.WriteLine($"POST response: {(int)response.StatusCode} {response.ReasonPhrase}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-images/set-chart-image-resolution-to-300-dpi-during-png-conversion-to-achieve-highdefinition-output.cs b/working-with-images/set-chart-image-resolution-to-300-dpi-during-png-conversion-to-achieve-highdefinition-output.cs new file mode 100644 index 000000000..50d7f8798 --- /dev/null +++ b/working-with-images/set-chart-image-resolution-to-300-dpi-during-png-conversion-to-achieve-highdefinition-output.cs @@ -0,0 +1,46 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Charts; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; + +class SetChartResolutionExample +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for the chart + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["A2"].PutValue("Apple"); + sheet.Cells["A3"].PutValue("Orange"); + sheet.Cells["A4"].PutValue("Banana"); + + sheet.Cells["B1"].PutValue("Value"); + sheet.Cells["B2"].PutValue(120); + sheet.Cells["B3"].PutValue(80); + sheet.Cells["B4"].PutValue(150); + + // Add a column chart + int chartIndex = sheet.Charts.Add(ChartType.Column, 5, 0, 15, 5); + Chart chart = sheet.Charts[chartIndex]; + chart.NSeries.Add("B2:B4", true); + chart.NSeries.CategoryData = "A2:A4"; + + // Configure image options for high‑definition PNG output + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Png, // Ensure PNG format + HorizontalResolution = 300, // 300 DPI horizontally + VerticalResolution = 300 // 300 DPI vertically + }; + + // Save the chart as a PNG image with the specified DPI + string outputPath = "HighResolutionChart.png"; + chart.ToImage(outputPath, options); + + Console.WriteLine($"Chart saved to '{outputPath}' with 300 DPI resolution."); + } +} \ No newline at end of file diff --git a/working-with-images/set-custom-page-margins-in-imageorprintoptions-before-converting-workbook-to-tiff-for-layout-control.cs b/working-with-images/set-custom-page-margins-in-imageorprintoptions-before-converting-workbook-to-tiff-for-layout-control.cs new file mode 100644 index 000000000..80f6c715e --- /dev/null +++ b/working-with-images/set-custom-page-margins-in-imageorprintoptions-before-converting-workbook-to-tiff-for-layout-control.cs @@ -0,0 +1,40 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +class SetCustomMarginsToTiff +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Add sample content + worksheet.Cells["A1"].PutValue("Custom margins demo"); + + // Set custom page margins (in inches) + worksheet.PageSetup.LeftMarginInch = 0.5; + worksheet.PageSetup.RightMarginInch = 0.5; + worksheet.PageSetup.TopMarginInch = 0.7; + worksheet.PageSetup.BottomMarginInch = 0.7; + + // Configure image options for TIFF rendering + ImageOrPrintOptions options = new ImageOrPrintOptions(); + options.ImageType = Aspose.Cells.Drawing.ImageType.Tiff; + options.OnePagePerSheet = true; // render the whole sheet on a single page + + // Create a SheetRender with the worksheet and the configured options + SheetRender renderer = new SheetRender(worksheet, options); + + // Render the worksheet to a TIFF file + string outputFile = "CustomMarginsOutput.tiff"; + using (FileStream tiffStream = new FileStream(outputFile, FileMode.Create)) + { + renderer.ToTiff(tiffStream); + } + + Console.WriteLine($"TIFF file saved to: {outputFile}"); + } +} \ No newline at end of file diff --git a/working-with-images/specify-a-white-background-color-in-imageorprintoptions-when-rendering-workbook-to-tiff-to-ensure-consistency.cs b/working-with-images/specify-a-white-background-color-in-imageorprintoptions-when-rendering-workbook-to-tiff-to-ensure-consistency.cs new file mode 100644 index 000000000..7493ad000 --- /dev/null +++ b/working-with-images/specify-a-white-background-color-in-imageorprintoptions-when-rendering-workbook-to-tiff-to-ensure-consistency.cs @@ -0,0 +1,28 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Drawing; +using Aspose.Cells.Rendering; + +class RenderTiffWhiteBackground +{ + static void Main() + { + // Create a new workbook and add some sample data + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + worksheet.Cells["A1"].PutValue("TIFF rendering with white background"); + + // Configure image rendering options for TIFF + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Tiff, // Set output format to TIFF + Transparent = false // Ensure the background is solid white (default) + }; + + // Render the entire workbook to a TIFF file + WorkbookRender renderer = new WorkbookRender(workbook, options); + renderer.ToImage("output_white_background.tiff"); + + Console.WriteLine("TIFF file generated with a white background."); + } +} \ No newline at end of file diff --git a/working-with-images/split-a-multipage-tiff-workbook-output-into-individual-singlepage-tiff-files-for-separate-handling.cs b/working-with-images/split-a-multipage-tiff-workbook-output-into-individual-singlepage-tiff-files-for-separate-handling.cs new file mode 100644 index 000000000..33e8a8b31 --- /dev/null +++ b/working-with-images/split-a-multipage-tiff-workbook-output-into-individual-singlepage-tiff-files-for-separate-handling.cs @@ -0,0 +1,47 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; + +namespace AsposeCellsTiffSplitDemo +{ + class Program + { + static void Main() + { + // Load the source Excel workbook (replace with your actual file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Configure image options for TIFF rendering + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Tiff, // Output format + TiffCompression = TiffCompression.CompressionLZW, + HorizontalResolution = 300, + VerticalResolution = 300 + }; + + // Create a renderer for the entire workbook + WorkbookRender renderer = new WorkbookRender(workbook, options); + + // Determine how many pages the workbook will generate + int totalPages = renderer.PageCount; + + // Ensure the output directory exists + string outputDir = "TiffPages"; + Directory.CreateDirectory(outputDir); + + // Render each page to a separate single‑page TIFF file + for (int pageIndex = 0; pageIndex < totalPages; pageIndex++) + { + string pageFile = Path.Combine(outputDir, $"Page_{pageIndex + 1}.tiff"); + renderer.ToImage(pageIndex, pageFile); + Console.WriteLine($"Saved page {pageIndex + 1} to {pageFile}"); + } + + // Clean up resources + renderer.Dispose(); + } + } +} \ No newline at end of file diff --git a/working-with-images/store-the-png-worksheet-image-in-azure-blob-storage-with-custom-metadata-for-categorization.cs b/working-with-images/store-the-png-worksheet-image-in-azure-blob-storage-with-custom-metadata-for-categorization.cs new file mode 100644 index 000000000..e79c2d728 --- /dev/null +++ b/working-with-images/store-the-png-worksheet-image-in-azure-blob-storage-with-custom-metadata-for-categorization.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using System.Collections.Generic; +using Aspose.Cells; +using Aspose.Cells.Drawing; +using Aspose.Cells.Rendering; + +class Program +{ + static void Main() + { + try + { + // Create a new workbook and add sample data + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + worksheet.Cells["A1"].PutValue("Sample Data"); + + // Set image rendering options for PNG output + ImageOrPrintOptions imgOptions = new ImageOrPrintOptions + { + ImageType = ImageType.Png + }; + + // Render the first worksheet to a PNG image in a memory stream + WorkbookRender renderer = new WorkbookRender(workbook, imgOptions); + using (MemoryStream imageStream = new MemoryStream()) + { + renderer.ToImage(imageStream); // Render to stream + imageStream.Position = 0; // Reset for reading + + // OPTIONAL: Save the image locally (replace Azure upload) + string imagePath = "sampleWorksheet.png"; + using (FileStream file = new FileStream(imagePath, FileMode.Create, FileAccess.Write)) + { + imageStream.CopyTo(file); + } + + // If Azure Blob Storage is required, ensure the Azure.Storage.Blobs package is referenced + // and uncomment the following block after adding the appropriate using directive. + /* + string connectionString = ""; + string containerName = "worksheet-images"; + string blobName = "sampleWorksheet.png"; + + var container = new Azure.Storage.Blobs.BlobContainerClient(connectionString, containerName); + container.CreateIfNotExists(); + + var blob = container.GetBlobClient(blobName); + imageStream.Position = 0; // Reset before upload + blob.Upload(imageStream, overwrite: true); + + var metadata = new Dictionary + { + { "category", "financial" }, + { "createdby", "aspnet" } + }; + blob.SetMetadata(metadata); + */ + } + + // Save the workbook to disk (optional) + string workbookPath = "output.xlsx"; + workbook.Save(workbookPath); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-images/track-workbooktotiff-conversion-progress-by-handling-the-conversion-progress-event-and-logging-percentages.cs b/working-with-images/track-workbooktotiff-conversion-progress-by-handling-the-conversion-progress-event-and-logging-percentages.cs new file mode 100644 index 000000000..d298dec56 --- /dev/null +++ b/working-with-images/track-workbooktotiff-conversion-progress-by-handling-the-conversion-progress-event-and-logging-percentages.cs @@ -0,0 +1,51 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Drawing; +using Aspose.Cells.Rendering; + +class WorkbookToTiffProgressDemo +{ + static void Main() + { + // Create a new workbook and populate it with enough data to span multiple pages + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + for (int i = 0; i < 300; i++) + { + sheet.Cells[i, 0].PutValue($"Row {i + 1}"); + } + + // Configure image options for TIFF rendering + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = ImageType.Tiff, + TiffCompression = TiffCompression.CompressionLZW, + OnePagePerSheet = false // generate a multi‑page TIFF + }; + + // Attach the progress callback + options.PageSavingCallback = new ProgressCallback(); + + // Render the worksheet to a multi‑page TIFF file + SheetRender renderer = new SheetRender(sheet, options); + renderer.ToTiff("WorkbookToTiffWithProgress.tiff"); + } + + // Callback that logs the conversion progress as a percentage + private class ProgressCallback : IPageSavingCallback + { + public void PageStartSaving(PageStartSavingArgs args) + { + int totalPages = args.PageCount; + int currentPage = args.PageIndex + 1; // convert zero‑based index to 1‑based + double percent = (double)currentPage / totalPages * 100; + Console.WriteLine($"Saving page {currentPage}/{totalPages} ({percent:0.##}%)"); + } + + public void PageEndSaving(PageEndSavingArgs args) + { + // Optional: indicate when a page has finished rendering + Console.WriteLine($"Finished page {args.PageIndex + 1}"); + } + } +} \ No newline at end of file diff --git a/working-with-images/use-the-svg-worksheet-graphic-as-a-vector-element-when-generating-a-pdf-document-with-itextsharp.cs b/working-with-images/use-the-svg-worksheet-graphic-as-a-vector-element-when-generating-a-pdf-document-with-itextsharp.cs new file mode 100644 index 000000000..7b1f6797c --- /dev/null +++ b/working-with-images/use-the-svg-worksheet-graphic-as-a-vector-element-when-generating-a-pdf-document-with-itextsharp.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Drawing; + +class SvgWorksheetToPdf +{ + static void Main() + { + try + { + const string svgFilePath = "image.svg"; + const string pdfOutputPath = "output.pdf"; + + // Verify SVG source file exists + if (!File.Exists(svgFilePath)) + { + Console.WriteLine($"SVG file not found: {Path.GetFullPath(svgFilePath)}"); + return; + } + + // Load SVG bytes + byte[] svgBytes = File.ReadAllBytes(svgFilePath); + + // Create a new workbook and add the SVG shape + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + ShapeCollection shapes = sheet.Shapes; + + // Add SVG at row 4, column 5 (zero‑based indices); size auto‑adjusted + shapes.AddSvg(4, 0, 5, 0, -1, -1, svgBytes, null); + + // Save the workbook directly to PDF (vector graphics are preserved) + workbook.Save(pdfOutputPath, SaveFormat.Pdf); + + Console.WriteLine("PDF generated successfully: " + Path.GetFullPath(pdfOutputPath)); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/working-with-images/validate-the-svg-worksheet-file-against-the-svg-schema-to-ensure-structural-correctness.cs b/working-with-images/validate-the-svg-worksheet-file-against-the-svg-schema-to-ensure-structural-correctness.cs new file mode 100644 index 000000000..cec2ee696 --- /dev/null +++ b/working-with-images/validate-the-svg-worksheet-file-against-the-svg-schema-to-ensure-structural-correctness.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Xml; +using System.Xml.Schema; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +namespace AsposeCellsSvgValidationDemo +{ + class Program + { + static void Main() + { + try + { + // Step 1: Create a simple workbook with sample data + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Item"); + sheet.Cells["B1"].PutValue("Quantity"); + sheet.Cells["A2"].PutValue("Apple"); + sheet.Cells["B2"].PutValue(10); + sheet.Cells["A3"].PutValue("Orange"); + sheet.Cells["B3"].PutValue(15); + + // Step 2: Render the worksheet to an SVG file + string svgPath = "worksheet.svg"; + SvgImageOptions svgOptions = new SvgImageOptions + { + // ImageType is implicitly SVG for SvgImageOptions; no need to set it explicitly + FitToViewPort = true + }; + SheetRender renderer = new SheetRender(sheet, svgOptions); + renderer.ToImage(0, svgPath); + + // Verify that the SVG file was created + if (!File.Exists(svgPath)) + { + Console.WriteLine($"Failed to generate SVG file: {svgPath}"); + return; + } + + // Step 3: Validate the generated SVG against an SVG XSD schema + // Assume the SVG schema file (svg.xsd) is placed in the same directory as the executable + string xsdPath = "svg.xsd"; + if (!File.Exists(xsdPath)) + { + Console.WriteLine($"Schema file not found: {xsdPath}"); + return; + } + + // Collect validation errors + List validationErrors = new List(); + XmlReaderSettings settings = new XmlReaderSettings(); + settings.Schemas.Add(null, xsdPath); + settings.ValidationType = System.Xml.ValidationType.Schema; + settings.ValidationEventHandler += (sender, args) => + { + validationErrors.Add(args.Message); + }; + + // Perform validation + using (XmlReader reader = XmlReader.Create(svgPath, settings)) + { + try + { + while (reader.Read()) { } + } + catch (XmlException ex) + { + validationErrors.Add($"XML parsing error: {ex.Message}"); + } + } + + // Step 4: Report validation result + if (validationErrors.Count == 0) + { + Console.WriteLine("SVG file is valid against the schema."); + } + else + { + Console.WriteLine("SVG validation failed with the following errors:"); + foreach (string error in validationErrors) + { + Console.WriteLine("- " + error); + } + } + } + catch (Exception ex) + { + // Catch any unexpected exceptions to prevent the program from crashing + Console.WriteLine($"An unexpected error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file