Convert Worksheet to Image - Remove whitespace around data

Remove Whitespace around Data

The SheetRender API converts a worksheet to an image file with any specified attributes, for example, image format, paginated sheets, etc. Several image formats are supported, including BMP, GIF, JPG, TIFF, and EMF.

When you use the sheet-to-image feature, the output image has whitespace, that is, a border, around it by default. You can remove this by setting the top, bottom, left and right page setup margins for the source worksheet to 0 and specify ImageOrPrintOptions attributes accordingly.

The following code snippet removes the whitespace around the data in the output image.

from aspose.cells import LoadDataFilterOptions, LoadFilter, LoadOptions, PrintingPageType, Workbook
from aspose.cells.drawing import ImageType
from aspose.cells.rendering import ImageOrPrintOptions, SheetRender
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# Source directory
sourceDir = RunExamples.Get_SourceDirectory()
# Output directory
outputDir = RunExamples.Get_OutputDirectory()
# Open the template file
book = Workbook(sourceDir + "Book1.xlsx")
# Get the first worksheet
sheet = book.worksheets[0]
options = LoadOptions()
options.load_filter = LoadFilter(LoadDataFilterOptions.ALL)
# Specify your print area if you want
# Sheet.PageSetup.PrintArea = "A1:H8";
# To remove the white border around the image.
sheet.page_setup.left_margin = 0.0
sheet.page_setup.right_margin = 0.0
sheet.page_setup.bottom_margin = 0.0
sheet.page_setup.top_margin = 0.0
# Define ImageOrPrintOptions
imgOptions = ImageOrPrintOptions()
imgOptions.image_type = ImageType.EMF
# Set only one page would be rendered for the image
imgOptions.one_page_per_sheet = True
imgOptions.printing_page = PrintingPageType.IGNORE_BLANK
# Create the SheetRender object based on the sheet with its
# ImageOrPrintOptions attributes
sr = SheetRender(sheet, imgOptions)
# Convert the image
sr.to_image(0, outputDir + "outputRemoveWhitespaceAroundData.emf")