public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Create a new Workbook object and //open a template Excel file. Workbook book = new Workbook(dataDir + "MyTestBook1.xls"); //Get the first worksheet. Worksheet sheet = book.Worksheets[0]; //Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); //Specify the image format imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; //Only one page for the whole sheet would be rendered imgOptions.OnePagePerSheet = true; //Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, imgOptions); //Render the image for the sheet Bitmap bitmap = sr.ToImage(0); //Save the image file specifying its image format. bitmap.Save(dataDir + "SheetImage.jpg"); // Display result, so that user knows the processing has finished. System.Console.WriteLine("Conversion to Image(s) completed."); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); string filePath = dataDir + "Template.xlsx"; //Create a workbook object from the template file Workbook book = new Workbook(filePath); //Convert each worksheet into svg format in a single page. ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); imgOptions.SaveFormat = SaveFormat.SVG; imgOptions.OnePagePerSheet = true; //Convert each worksheet into svg format foreach (Worksheet sheet in book.Worksheets) { SheetRender sr = new SheetRender(sheet, imgOptions); for (int i = 0; i < sr.PageCount; i++) { //Output the worksheet into Svg image format sr.ToImage(i, filePath + sheet.Name + i + ".out.svg"); } } }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); string filePath = dataDir+ "aspose-sample.xlsx"; //Create workbook from source file. Workbook workbook = new Workbook(filePath); //Access the first worksheet Worksheet worksheet = workbook.Worksheets[0]; //Set the print area with your desired range worksheet.PageSetup.PrintArea = "E12:H16"; //Set all margins as 0 worksheet.PageSetup.LeftMargin = 0; worksheet.PageSetup.RightMargin = 0; worksheet.PageSetup.TopMargin = 0; worksheet.PageSetup.BottomMargin = 0; //Set OnePagePerSheet option as true ImageOrPrintOptions options = new ImageOrPrintOptions(); options.OnePagePerSheet = true; options.ImageFormat = ImageFormat.Jpeg; //Take the image of your worksheet SheetRender sr = new SheetRender(worksheet, options); sr.ToImage(0, dataDir+ "output.jpg"); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create workbook object from source file Workbook wb = new Workbook(dataDir+ "aspose-sample.xlsx"); // Apply different image or print options var imgOption = new ImageOrPrintOptions(); imgOption.ImageFormat = ImageFormat.Png; imgOption.HorizontalResolution = 200; imgOption.VerticalResolution = 200; imgOption.OnePagePerSheet = true; // Apply transparency to the output image imgOption.Transparent = true; // Create image after apply image or print options var sr = new SheetRender(wb.Worksheets[0], imgOption); dataDir = dataDir+ "output.png"; sr.ToImage(0, dataDir); // ExEnd:1 Console.WriteLine("\nProcess completed successfully.\nFile saved at " + dataDir); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Create a new Workbook object //Open a template excel file Workbook book = new Workbook(dataDir+ "Testbook.xlsx"); //Get the first worksheet. Worksheet sheet = book.Worksheets[0]; //Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); //Specify the image format imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; //Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, imgOptions); //Render the image for the sheet Bitmap bitmap = sr.ToImage(0); //Save the image file bitmap.Save(dataDir+ "SheetImage.jpg"); }
public static void CreateStaticReport() { //Open template string path = System.Web.HttpContext.Current.Server.MapPath("~"); path = path.Substring(0, path.LastIndexOf("\\")); path += @"\designer\MyTestBook1.xls"; //Instantiate a new Workbook object. Workbook book = new Workbook(path); ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; Worksheet sheet = book.Worksheets[0]; SheetRender sheetRender = new SheetRender(sheet, imgOptions); //Create a memory stream object. MemoryStream memorystream = new MemoryStream(); //Convert worksheet to image. sheetRender.ToImage(0, memorystream); memorystream.Seek(0, SeekOrigin.Begin); //Set Response object to stream the image file. byte[] data = memorystream.ToArray(); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "image/jpeg"; HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=SheetImage.jpeg"); HttpContext.Current.Response.OutputStream.Write(data, 0, data.Length); //End response to avoid unneeded html after xls HttpContext.Current.Response.End(); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); string filePath = dataDir + "Template.xlsx"; //Create a workbook object from the template file Workbook book = new Workbook(filePath); //Convert each worksheet into svg format in a single page. ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); imgOptions.SaveFormat = SaveFormat.SVG; imgOptions.OnePagePerSheet = true; //Convert each worksheet into svg format foreach (Worksheet sheet in book.Worksheets) { SheetRender sr = new SheetRender(sheet, imgOptions); for (int i = 0; i < sr.PageCount; i++) { //Output the worksheet into Svg image format sr.ToImage(i, filePath + sheet.Name + i + ".out.svg"); } } }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiate and open an Excel file Workbook book = new Workbook(dataDir+ "book1.xlsx"); //Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); //Specify the image format imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; //Set the vertical and horizontal resolution imgOptions.VerticalResolution = 200; imgOptions.HorizontalResolution = 200; //One page per sheet is enabled imgOptions.OnePagePerSheet = true; //Get the first worksheet Worksheet sheet = book.Worksheets[0]; //Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, imgOptions); //Render the image for the sheet Bitmap bmp = sr.ToImage(0); //Create a bitmap Bitmap thumb = new Bitmap(100, 100); //Get the graphics for the bitmap System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(thumb); //Draw the image gr.DrawImage(bmp, 0, 0, 100, 100); //Save the thumbnail thumb.Save(dataDir+ "mythumbnail.out.bmp"); }
public static void Run() { // ExStart:CalculatePageSetupScalingFactor // Create workbook object Workbook workbook = new Workbook(); // Access first worksheet Worksheet worksheet = workbook.Worksheets[0]; // Put some data in these cells worksheet.Cells["A4"].PutValue("Test"); worksheet.Cells["S4"].PutValue("Test"); // Set paper size worksheet.PageSetup.PaperSize = PaperSizeType.PaperA4; // Set fit to pages wide as 1 worksheet.PageSetup.FitToPagesWide = 1; // Calculate page scale via sheet render SheetRender sr = new SheetRender(worksheet, new ImageOrPrintOptions()); // Convert page scale double value to percentage string strPageScale = sr.PageScale.ToString("0%"); // Write the page scale value Console.WriteLine(strPageScale); // ExEnd:CalculatePageSetupScalingFactor }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Open a template excel file Workbook book = new Workbook(dataDir + "Testbook1.xlsx"); // Get the first worksheet. Worksheet sheet = book.Worksheets[0]; // Get the second worksheet. // Worksheet sheet = book.Worksheets[1]; // Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); // Specify the image format imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; // If you want entire sheet as a singe image imgOptions.OnePagePerSheet = true; // Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, imgOptions); // Render the image for the sheet Bitmap bitmap = sr.ToImage(0); // Save the image file bitmap.Save(dataDir + "SheetImage_out.jpg"); // ExEnd:1 }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); string filePath = dataDir+ "aspose-sample.xlsx"; // Create workbook from source file. Workbook workbook = new Workbook(filePath); // Access the first worksheet Worksheet worksheet = workbook.Worksheets[0]; // Set the print area with your desired range worksheet.PageSetup.PrintArea = "E12:H16"; // Set all margins as 0 worksheet.PageSetup.LeftMargin = 0; worksheet.PageSetup.RightMargin = 0; worksheet.PageSetup.TopMargin = 0; worksheet.PageSetup.BottomMargin = 0; // Set OnePagePerSheet option as true ImageOrPrintOptions options = new ImageOrPrintOptions(); options.OnePagePerSheet = true; options.ImageFormat = ImageFormat.Jpeg; // Take the image of your worksheet SheetRender sr = new SheetRender(worksheet, options); dataDir = dataDir+ "output.out.jpg"; sr.ToImage(0, dataDir); // ExEnd:1 Console.WriteLine("\nProcess completed successfully.\nFile saved at " + dataDir); }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiate a workbook //Open the template file Workbook book = new Workbook(dataDir+ "MyTestBook1.xlsx"); //Get the first worksheet Worksheet sheet = book.Worksheets[0]; //Specify your print area if you want //sheet.PageSetup.PrintArea = "A1:H8"; //To remove the white border around the image. sheet.PageSetup.LeftMargin = 0; sheet.PageSetup.RightMargin = 0; sheet.PageSetup.BottomMargin = 0; sheet.PageSetup.TopMargin = 0; //Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Emf; //Set only one page would be rendered for the image imgOptions.OnePagePerSheet = true; imgOptions.PrintingPage = PrintingPageType.IgnoreBlank; //Create the SheetRender object based on the sheet with its //ImageOrPrintOptions attributes SheetRender sr = new SheetRender(sheet, imgOptions); //Convert the image sr.ToImage(0, dataDir+ "img_MyTestBook1.emf"); }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiate a new Workbook //Load an Excel file Workbook wb = new Workbook(dataDir+ "Book1.xlsx"); //Instantiate SheetRender object based on the first worksheet //Set the ImageOrPrintOptions with desired pixel format (24 bits per pixel) and image format type SheetRender sr = new SheetRender(wb.Worksheets[0], new ImageOrPrintOptions { PixelFormat = PixelFormat.Format24bppRgb, ImageFormat = ImageFormat.Tiff }); //Save the image (first page of the sheet) with the specified options sr.ToImage(0, dataDir+ "outImage1.out.tiff"); }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Instantiate a new Workbook //Load an Excel file Workbook wb = new Workbook(dataDir+ "Book1.xlsx"); //Instantiate SheetRender object based on the first worksheet //Set the ImageOrPrintOptions with desired pixel format (24 bits per pixel) and image format type SheetRender sr = new SheetRender(wb.Worksheets[0], new ImageOrPrintOptions { PixelFormat = PixelFormat.Format24bppRgb, ImageFormat = ImageFormat.Tiff }); //Save the image (first page of the sheet) with the specified options sr.ToImage(0, dataDir+ "outImage1.tiff"); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create workbook object. Workbook wb = new Workbook(); // Set default font of the workbook to none Style s = wb.DefaultStyle; s.Font.Name = ""; wb.DefaultStyle = s; // Access first worksheet. Worksheet ws = wb.Worksheets[0]; // Access cell A4 and add some text inside it. Cell cell = ws.Cells["A4"]; cell.PutValue("This text has some unknown or invalid font which does not exist."); // Set the font of cell A4 which is unknown. Style st = cell.GetStyle(); st.Font.Name = "UnknownNotExist"; st.Font.Size = 20; st.IsTextWrapped = true; cell.SetStyle(st); // Set first column width and fourth column height ws.Cells.SetColumnWidth(0, 80); ws.Cells.SetRowHeight(3, 60); // Create image or print options. ImageOrPrintOptions opts = new ImageOrPrintOptions(); opts.OnePagePerSheet = true; opts.ImageFormat = ImageFormat.Png; // Render worksheet image with Courier New as default font. opts.DefaultFont = "Courier New"; SheetRender sr = new SheetRender(ws, opts); sr.ToImage(0, "out_courier_new_out.png"); // Render worksheet image again with Times New Roman as default font. opts.DefaultFont = "Times New Roman"; sr = new SheetRender(ws, opts); sr.ToImage(0, "times_new_roman_out.png"); // ExEnd:1 }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook(dataDir + "Testbook1.xlsx", new Aspose.Cells.LoadOptions(Aspose.Cells.LoadFormat.Xlsx)); foreach (Worksheet ws in wb.Worksheets) { SheetRender sr = new SheetRender(ws, new ImageOrPrintOptions() { OnePagePerSheet = true, ImageFormat = ImageFormat.Jpeg }); sr.ToImage(0, dataDir + "Img_" + ws.Index + "_out.jpg"); } // ExEnd:1 }
static void Main(string[] args) { //Instantiating a Workbook object Workbook workbook = new Workbook("../../data/test.xlsx"); //Create an object for ImageOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Create a SheetRender object with respect to your desired sheet SheetRender sr = new SheetRender(sheet, imgOptions); //Print the worksheet sr.ToPrinter("Samsung ML-1520 Series"); }
public static void Run() { // ExStart:SpecifyJobNameWhilePrinting // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create workbook object from source Excel file Workbook workbook = new Workbook(dataDir + "SampleBook.xlsx"); string printerName = ""; while (string.IsNullOrEmpty(printerName) && string.IsNullOrWhiteSpace(printerName)) { Console.WriteLine("Please Enter Your Printer Name:"); printerName = Console.ReadLine(); } string jobName = "Job Name while Printing with Aspose.Cells"; // Print workbook using WorkbookRender WorkbookRender wr = new WorkbookRender(workbook, new ImageOrPrintOptions()); try { wr.ToPrinter(printerName, jobName); } catch (Exception ex) { Console.WriteLine(ex.Message); } // Access first worksheet Worksheet worksheet = workbook.Worksheets[0]; // Print worksheet using SheetRender SheetRender sr = new SheetRender(worksheet, new ImageOrPrintOptions()); try { sr.ToPrinter(printerName, jobName); } catch (Exception ex) { Console.WriteLine(ex.Message); } // ExEnd:SpecifyJobNameWhilePrinting }
public static void Run() { // ExStart:PrintingSpecificRangeOfPages // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create workbook from source Excel file Workbook workbook = new Workbook(dataDir + "SampleBook.xlsx"); string printerName = ""; while (string.IsNullOrEmpty(printerName) && string.IsNullOrWhiteSpace(printerName)) { Console.WriteLine("Please Enter Your Printer Name:"); printerName = Console.ReadLine(); } // Print the worbook specifying the range of pages. Here we are printing pages 2-3 WorkbookRender wr = new WorkbookRender(workbook, new ImageOrPrintOptions()); try { wr.ToPrinter(printerName, 1, 2); } catch (Exception ex) { Console.WriteLine(ex.Message); } // Access first worksheet Worksheet worksheet = workbook.Worksheets[0]; // Print the worksheet specifying the range of pages. Here we are printing pages 2-3 SheetRender sr = new SheetRender(worksheet, new ImageOrPrintOptions()); try { sr.ToPrinter(printerName, 1, 2); } catch (Exception ex) { Console.WriteLine(ex.Message); } // ExEnd:PrintingSpecificRangeOfPages }
public static void CreateStaticReport() { //Open template string path = System.Web.HttpContext.Current.Server.MapPath("~"); path = path.Substring(0, path.LastIndexOf("\\")); path += @"\designer\MyTestBook1.xls"; //Instantiate a new Workbook object. Workbook book = new Workbook(path); //Get the first worksheet Worksheet sheet = book.Worksheets[0]; //Apply different Image and Print options ImageOrPrintOptions options = new ImageOrPrintOptions(); options.HorizontalResolution = 300; options.VerticalResolution = 300; options.TiffCompression = TiffCompression.CompressionCCITT4; options.IsCellAutoFit = false; options.ImageFormat = System.Drawing.Imaging.ImageFormat.Tiff; options.PrintingPage = PrintingPageType.Default; //Create a memory stream object. MemoryStream memorystream = new MemoryStream(); SheetRender sheetRender = new SheetRender(sheet, options); //Convert worksheet to image. sheetRender.ToTiff(memorystream); memorystream.Seek(0, SeekOrigin.Begin); //Set Response object to stream the image file. byte[] data = memorystream.ToArray(); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "image/tiff"; HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=SheetImage.tiff"); HttpContext.Current.Response.OutputStream.Write(data, 0, data.Length); //End response to avoid unneeded html after xls HttpContext.Current.Response.End(); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); Workbook book = new Workbook(dataDir+ "TestData.xlsx"); Worksheet sheet = book.Worksheets[0]; Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions(); options.HorizontalResolution = 200; options.VerticalResolution = 200; options.ImageFormat = System.Drawing.Imaging.ImageFormat.Tiff; //Sheet2Image By Page conversion SheetRender sr = new SheetRender(sheet, options); for (int j = 0; j < sr.PageCount; j++) { sr.ToImage(j, dataDir+ "test" + sheet.Name + " Page" + (j + 1) + ".tif"); } }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); Workbook book = new Workbook(dataDir+ "TestData.xlsx"); Worksheet sheet = book.Worksheets[0]; Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions(); options.HorizontalResolution = 200; options.VerticalResolution = 200; options.ImageFormat = System.Drawing.Imaging.ImageFormat.Tiff; //Sheet2Image By Page conversion SheetRender sr = new SheetRender(sheet, options); for (int j = 0; j < sr.PageCount; j++) { sr.ToImage(j, dataDir+ "test" + sheet.Name + " Page" + (j + 1) + ".out.tif"); } }
static void Main(string[] args) { string MyDir = @"Files\"; Workbook book = new Workbook(MyDir + "Sheet to Image by Page.xls"); Worksheet sheet = book.Worksheets[0]; Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions(); options.HorizontalResolution = 200; options.VerticalResolution = 200; options.ImageFormat = System.Drawing.Imaging.ImageFormat.Tiff; //Sheet2Image By Page conversion SheetRender sr = new SheetRender(sheet, options); for (int j = 0; j < sr.PageCount; j++) { Bitmap pic = sr.ToImage(j); pic.Save(MyDir + sheet.Name + " Page" + (j + 1) + ".tiff"); } }
public static void Run() { // ExStart:PrintingExcelWorkbookUsingSheetRender // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Instantiate a workbook with Excel file. Workbook workbook = new Workbook(dataDir + "SampleBook.xlsx"); string printerName = ""; while (string.IsNullOrEmpty(printerName) && string.IsNullOrWhiteSpace(printerName)) { Console.WriteLine("Please Enter Your Printer Name:"); printerName = Console.ReadLine(); } // Define a worksheet. Worksheet worksheet; // Get the second sheet. worksheet = workbook.Worksheets[1]; // Apply different Image/Print options. Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions(); options.PrintingPage = PrintingPageType.Default; SheetRender sr = new SheetRender(worksheet, options); Console.WriteLine("Printing SampleBook.xlsx"); // Print the sheet. try { sr.ToPrinter(printerName); Console.WriteLine("Pinting finished."); } catch (Exception ex) { Console.WriteLine(ex.Message); } // ExEnd:PrintingExcelWorkbookUsingSheetRender }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Open template Workbook book = new Workbook(dataDir + "Testbook1.xlsx"); // Get the first worksheet Worksheet sheet = book.Worksheets[0]; // Apply different Image and Print options Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions(); // Set Horizontal Resolution options.HorizontalResolution = 300; // Set Vertical Resolution options.VerticalResolution = 300; // Set TiffCompression options.TiffCompression = Aspose.Cells.Rendering.TiffCompression.CompressionLZW; // Set Autofit options options.IsCellAutoFit = false; // Set Image Format options.ImageFormat = System.Drawing.Imaging.ImageFormat.Tiff; // Set printing page type options.PrintingPage = PrintingPageType.Default; // Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, options); // Render/save the image for the sheet sr.ToImage(0, dataDir + @"SheetImage_out.tiff"); // ExEnd:1 }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Create workbook object from source file Workbook wb = new Workbook(dataDir+ "aspose-sample.xlsx"); //Apply different image or print options var imgOption = new ImageOrPrintOptions(); imgOption.ImageFormat = ImageFormat.Png; imgOption.HorizontalResolution = 200; imgOption.VerticalResolution = 200; imgOption.OnePagePerSheet = true; //Apply transparency to the output image imgOption.Transparent = true; //Create image after apply image or print options var sr = new SheetRender(wb.Worksheets[0], imgOption); sr.ToImage(0, dataDir+ "output.out.png"); }
static void Main(string[] args) { string MyDir = @"Files\"; //Create a new Workbook object //Open a template excel file Workbook book = new Workbook(MyDir+"Sheet to Image.xls"); //Get the first worksheet. Worksheet sheet = book.Worksheets[0]; //Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); //Specify the image format imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; //Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, imgOptions); //Render the image for the sheet Bitmap bitmap = sr.ToImage(0); //Save the image file bitmap.Save(MyDir+"SheetImage.jpg"); }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Create workbook object from source file Workbook wb = new Workbook(dataDir+ "aspose-sample.xlsx"); //Apply different image or print options var imgOption = new ImageOrPrintOptions(); imgOption.ImageFormat = ImageFormat.Png; imgOption.HorizontalResolution = 200; imgOption.VerticalResolution = 200; imgOption.OnePagePerSheet = true; //Apply transparency to the output image imgOption.Transparent = true; //Create image after apply image or print options var sr = new SheetRender(wb.Worksheets[0], imgOption); sr.ToImage(0, dataDir+ "output.png"); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Create a new Workbook object //Open a template excel file Workbook book = new Workbook(dataDir+ "Testbook.xlsx"); //Get the first worksheet. Worksheet sheet = book.Worksheets[0]; //Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); //Specify the image format imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; //Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, imgOptions); //Render the image for the sheet Bitmap bitmap = sr.ToImage(0); //Save the image file bitmap.Save(dataDir+ "SheetImage.jpg"); }
public static void Run() { // ExStart:1 //Source directory string sourceDir = RunExamples.Get_SourceDirectory(); //Output directory string outputDir = RunExamples.Get_OutputDirectory(); // Open a template excel file Workbook book = new Workbook(sourceDir + "sampleSpecificPagesToImages.xlsx"); // Get the first worksheet. Worksheet sheet = book.Worksheets[0]; // Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); // Specify the image format imgOptions.ImageType = Drawing.ImageType.Jpeg; // Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, imgOptions); //Specify page index to be rendered int idxPage = 3; // Render the third image for the sheet Bitmap bitmap = sr.ToImage(idxPage); // Save the image file bitmap.Save(outputDir + "outputSpecificPagesToImage_" + (idxPage + 1) + ".jpg"); // ExEnd:1 Console.WriteLine("SpecificPagesToImage executed successfully."); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Create a new Workbook object //Open a template excel file Workbook book = new Workbook(dataDir + "Testbook.xlsx"); //Get the first worksheet. Worksheet sheet = book.Worksheets[0]; //Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); //Specify the image format imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; //Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, imgOptions); //Render the image for the sheet Bitmap bitmap = sr.ToImage(0); //Save the image file bitmap.Save(dataDir + "SheetImage.jpg"); }
public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); Workbook book = new Workbook(dataDir + "TestData.xlsx"); Worksheet sheet = book.Worksheets[0]; Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions(); options.HorizontalResolution = 200; options.VerticalResolution = 200; options.ImageFormat = System.Drawing.Imaging.ImageFormat.Tiff; //Sheet2Image By Page conversion SheetRender sr = new SheetRender(sheet, options); for (int j = 0; j < sr.PageCount; j++) { sr.ToImage(j, dataDir + "test" + sheet.Name + " Page" + (j + 1) + ".out.tif"); } //ExEnd:1 }
public async Task ProcessFilesAsync(IEnumerable <int> previewDelta, Func <Stream, string, Task> pagePreviewCallback, CancellationToken token) { var imgOptions = new ImageOrPrintOptions { ImageFormat = ImageFormat.Jpeg, OnePagePerSheet = false }; var t = new List <Task>(); var diff = Enumerable.Range(0, _excel.Value.Worksheets.Count); diff = diff.Except(previewDelta); foreach (var item in diff) { if (token.IsCancellationRequested) { break; } var wb = _excel.Value.Worksheets[item]; ScalePageSetupToFitPage(wb); var sr = new SheetRender(wb, imgOptions); using (var img = sr.ToImage(0)) { if (img is null) { continue; } var ms = new MemoryStream(); img.Save(ms, ImageFormat.Jpeg); t.Add(pagePreviewCallback(ms, $"{item}.jpg").ContinueWith(_ => ms.Dispose(), token)); } } await Task.WhenAll(t); }
private void button1_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = ""; string fileName = ""; string myFilePath = openFileDialog.FileName; string ext = Path.GetExtension(myFilePath); switch (ext) { case ".jpg": ProcessImage((Bitmap)Bitmap.FromFile(openFileDialog.FileName)); break; case ".png": ProcessImage((Bitmap)Bitmap.FromFile(openFileDialog.FileName)); break; case ".xlsx": Workbook workbook = new Workbook(openFileDialog.FileName); //Get the first worksheet. Worksheet sheet = workbook.Worksheets[0]; //Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); //Specify the image format imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; //Only one page for the whole sheet would be rendered imgOptions.OnePagePerSheet = true; //Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, imgOptions); //Render the image for the sheet Bitmap bitmap = sr.ToImage(0); //Save the image file specifying its image format. //bitmap.Save("excel.jpg"); ProcessImage(bitmap); break; case ".doc": filePath = Path.GetDirectoryName(openFileDialog.FileName); fileName = Path.GetFileNameWithoutExtension(openFileDialog.FileName) + ".doc"; WordToJpg(filePath, fileName); break; case ".docx": filePath = Path.GetDirectoryName(openFileDialog.FileName); fileName = Path.GetFileNameWithoutExtension(openFileDialog.FileName) + ".docx"; WordToJpg(filePath, fileName); break; case ".pdf": PdfLoadedDocument loadedDocument = new PdfLoadedDocument(openFileDialog.FileName); Bitmap image = loadedDocument.ExportAsImage(0); //image.Save("Image.jpg", ImageFormat.Jpeg); ProcessImage(image); loadedDocument.Close(true); break; } } }
public HttpResponseMessage DownloadDocument(string file, string folderName, bool isImage) { file = Uri.UnescapeDataString(file); folderName = Uri.UnescapeDataString(folderName); var outFolderName = AppSettings.OutputDirectory + folderName + "/"; try { string fullPath; if (File.Exists(AppSettings.WorkingDirectory + folderName + "/" + file)) { fullPath = AppSettings.WorkingDirectory + folderName + "/" + file; } else { fullPath = AppSettings.OutputDirectory + folderName + "/" + file; } var options = new LoadOptions { CheckExcelRestriction = false }; var workbook = new Workbook(fullPath, options); var zipOutFolder = outFolderName + Path.GetFileNameWithoutExtension(file); if (!Directory.Exists(zipOutFolder)) { Directory.CreateDirectory(zipOutFolder); } var worksheetsCount = workbook.Worksheets.Count; string outfileName; if (isImage) { outfileName = Path.GetFileNameWithoutExtension(file) + ".png"; var imgOptions = new ImageOrPrintOptions { ImageType = ImageType.Png, OnePagePerSheet = true }; foreach (var sheet in workbook.Worksheets) { var sr = new SheetRender(sheet, imgOptions); var srPageCount = sr.PageCount; for (var i = 0; i < sr.PageCount; i++) { if (worksheetsCount > 1 || srPageCount > 1) { outfileName = zipOutFolder + "/" + sheet.Name + "_" + (i + 1) + ".png"; } else { outfileName = zipOutFolder + "/" + Path.GetFileNameWithoutExtension(file) + ".png"; } sr.ToImage(i, outfileName); } } } else { if (worksheetsCount > 1) { outfileName = zipOutFolder + "/" + Path.GetFileNameWithoutExtension(file) + ".html"; } else { outfileName = outFolderName + "/" + Path.GetFileNameWithoutExtension(file) + ".html"; } var htmlSaveOptions = new HtmlSaveOptions { ExportImagesAsBase64 = true, Encoding = UTF8WithoutBom }; workbook.Save(outfileName, htmlSaveOptions); } if (isImage || worksheetsCount > 1) { outfileName = outFolderName + Path.GetFileNameWithoutExtension(file) + ".zip"; if (File.Exists(outfileName)) { File.Delete(outfileName); } ZipFile.CreateFromDirectory(zipOutFolder, outfileName); Directory.Delete(zipOutFolder, true); } using (var fileStream = new FileStream(outfileName, FileMode.Open, FileAccess.Read)) { using (var ms = new MemoryStream()) { fileStream.CopyTo(ms); var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(ms.ToArray()) }; result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = Path.GetFileName(outfileName) }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return(result); } } } catch (Exception e) { var message = $"{e.Message} | File = {file}"; NLogger.LogError(App, "DownloadDocument", message, folderName); var response = new Response { StatusCode = 500, Status = e.Message, FileName = file, FolderName = folderName, Text = "Viewer Download" }; return(Request.CreateResponse(HttpStatusCode.InternalServerError, response)); } }
public List <PageInfo> Convert(String inputFile, ImageConversionOptions options) { var ext = (options.ProcessAs ?? Path.GetExtension(inputFile).Trim('.', ' ')).ToUpper(); Workbook book = OpenWorkbook(inputFile, ext); ImageOrPrintOptions saveOptions = new ImageOrPrintOptions(); saveOptions.HorizontalResolution = options.Resolution; saveOptions.VerticalResolution = options.Resolution; saveOptions.ImageFormat = ImageFormat.Png; //saveOptions.IsCellAutoFit = true; //saveOptions.OnePagePerSheet = true; if (options.BinarisationAlgorithm == BinarisationAlgorithm.Default) { options.BinarisationAlgorithm = BinarisationAlgorithm.OtsuThreshold; } var pages = new List <PageInfo>(); foreach (Worksheet sheet in book.Worksheets) { if (ext == "CSV" || ext == "TSV") { sheet.PageSetup.Orientation = PageOrientationType.Landscape; foreach (Cell cell in sheet.Cells) { cell.PutValue(cell.StringValue.Replace("\0", "").Trim()); } sheet.AutoFitColumns(); sheet.AutoFitRows(); } // Adjust the margins sheet.PageSetup.TopMargin = 0.5; sheet.PageSetup.BottomMargin = 0.5; sheet.PageSetup.LeftMargin = 0.5; sheet.PageSetup.RightMargin = 0.5; SheetRender render = new SheetRender(sheet, saveOptions); for (int i = 0; i < render.PageCount; i++) { using (var bmp = render.ToImage(i)) { // Convert the page and add it to the list pages.AddRange(ImageProcessingEngine.Instance.Convert(bmp, options)); } } } // TODO: DONT THROW HERE, ALLOW THIS IF REMOVE BLANK PAGES IS ENABLED // BUT WILL NEED TO BE DONE BACK IN EMAILCONVERTER if (!pages.Any()) { throw new Exception("Aspose.Cells did not find anything to print."); } return(pages); }
public override void GeneratePreview(Stream docStream, IPreviewGenerationContext context) { var document = new Workbook(docStream); var printOptions = new ImageOrPrintOptions { ImageFormat = Common.PREVIEWIMAGEFORMAT, OnePagePerSheet = false, HorizontalResolution = context.PreviewResolution, VerticalResolution = context.PreviewResolution }; // every worksheet may contain multiple pages (as set by Excel // automatically, or by the user using the print layout) var estimatedPageCount = document.Worksheets.Select(w => new SheetRender(w, printOptions).PageCount).Sum(); if (context.StartIndex == 0) { context.SetPageCount(estimatedPageCount); } int firstIndex; int lastIndex; context.SetIndexes(estimatedPageCount, out firstIndex, out lastIndex); var workbookPageIndex = 0; var worksheetIndex = 0; var loggedPageError = false; // iterate through worksheets while (worksheetIndex < document.Worksheets.Count) { try { var worksheet = document.Worksheets[worksheetIndex]; var sheetRender = new SheetRender(worksheet, printOptions); // if we need to start preview generation on a subsequent worksheet, skip the previous ones if (workbookPageIndex + sheetRender.PageCount < context.StartIndex) { workbookPageIndex += sheetRender.PageCount; worksheetIndex++; continue; } // iterate through pages inside a worksheet for (var worksheetPageIndex = 0; worksheetPageIndex < sheetRender.PageCount; worksheetPageIndex++) { // if the desired page interval contains this page, generate the image if (workbookPageIndex >= firstIndex && workbookPageIndex <= lastIndex) { using (var imgStream = new MemoryStream()) { sheetRender.ToImage(worksheetPageIndex, imgStream); // handle empty sheets if (imgStream.Length == 0) { context.SaveEmptyPreview(workbookPageIndex + 1); } else { context.SavePreviewAndThumbnail(imgStream, workbookPageIndex + 1); } } } workbookPageIndex++; } } catch (Exception ex) { if (Tools.HandlePageError(ex, workbookPageIndex + 1, context, !loggedPageError)) { return; } loggedPageError = true; workbookPageIndex++; } worksheetIndex++; } // set the real count if some of the sheets turned out to be empty if (workbookPageIndex < estimatedPageCount) { context.SetPageCount(workbookPageIndex); } }
private static void GenerateWorkBookPreview(int previewsFolderId, Stream docStream) { var document = new Workbook(docStream); var printOptions = new ImageOrPrintOptions { ImageFormat = PREVIEWIMAGEFORMAT, OnePagePerSheet = false }; // every worksheet may contain multiple pages (as set by Excel // automatically, or by the user using the print layout) var estimatedPageCount = document.Worksheets.Cast <Worksheet>().Select(w => new SheetRender(w, printOptions).PageCount).Sum(); if (StartIndex == 0) { SetPageCount(estimatedPageCount); } var firstIndex = 0; var lastIndex = 0; SetIndexes(StartIndex, estimatedPageCount, out firstIndex, out lastIndex, MaxPreviewCount); var workbookPageIndex = 0; var worksheetIndex = 0; // iterate through worksheets while (worksheetIndex < document.Worksheets.Count) { //if (!CheckActuality(file)) // break; try { var worksheet = document.Worksheets[worksheetIndex]; var sheetRender = new SheetRender(worksheet, printOptions); // if we need to start preview generation on a subsequent worksheet, skip the previous ones if (workbookPageIndex + sheetRender.PageCount < StartIndex) { workbookPageIndex += sheetRender.PageCount; worksheetIndex++; continue; } // iterate through pages inside a worksheet for (var worksheetPageIndex = 0; worksheetPageIndex < sheetRender.PageCount; worksheetPageIndex++) { // if the desired page interval contains this page, generate the image if (workbookPageIndex >= firstIndex && workbookPageIndex <= lastIndex) { using (var imgStream = new MemoryStream()) { sheetRender.ToImage(worksheetPageIndex, imgStream); // handle empty sheets if (imgStream.Length == 0) { SaveEmptyPreview(workbookPageIndex + 1, previewsFolderId); } else { SavePreviewAndThumbnail(imgStream, workbookPageIndex + 1, previewsFolderId); } } } workbookPageIndex++; } } catch (Exception ex) { Logger.WriteError(ContentId, workbookPageIndex + 1, "", ex, StartIndex, Version); SaveEmptyPreview(workbookPageIndex + 1, previewsFolderId); workbookPageIndex++; } worksheetIndex++; } //set the real count if some of the sheets turned out to be empty if (workbookPageIndex < estimatedPageCount) { SetPageCount(workbookPageIndex); } }
public override async Task GeneratePreviewAsync(Stream docStream, IPreviewGenerationContext context, CancellationToken cancellationToken) { var document = new Workbook(docStream); var printOptions = new ImageOrPrintOptions { ImageType = GetImageType(), OnePagePerSheet = false, HorizontalResolution = context.PreviewResolution, VerticalResolution = context.PreviewResolution }; // every worksheet may contain multiple pages (as set by Excel // automatically, or by the user using the print layout) var estimatedPageCount = document.Worksheets.Select(w => new SheetRender(w, printOptions).PageCount).Sum(); if (context.StartIndex == 0) { await context.SetPageCountAsync(estimatedPageCount, cancellationToken).ConfigureAwait(false); } context.SetIndexes(estimatedPageCount, out var firstIndex, out var lastIndex); var workbookPageIndex = 0; var worksheetIndex = 0; var loggedPageError = false; // iterate through worksheets while (worksheetIndex < document.Worksheets.Count) { cancellationToken.ThrowIfCancellationRequested(); try { var worksheet = document.Worksheets[worksheetIndex]; var sheetRender = new SheetRender(worksheet, printOptions); // if we need to start preview generation on a subsequent worksheet, skip the previous ones if (workbookPageIndex + sheetRender.PageCount < context.StartIndex) { workbookPageIndex += sheetRender.PageCount; worksheetIndex++; continue; } // iterate through pages inside a worksheet for (var worksheetPageIndex = 0; worksheetPageIndex < sheetRender.PageCount; worksheetPageIndex++) { // if the desired page interval contains this page, generate the image if (workbookPageIndex >= firstIndex && workbookPageIndex <= lastIndex) { using (var imgStream = new MemoryStream()) { sheetRender.ToImage(worksheetPageIndex, imgStream); // handle empty sheets if (imgStream.Length == 0) { await context.SaveEmptyPreviewAsync(workbookPageIndex + 1, cancellationToken) .ConfigureAwait(false); } else { await context.SavePreviewAndThumbnailAsync(imgStream, workbookPageIndex + 1, cancellationToken).ConfigureAwait(false); } } } workbookPageIndex++; } } catch (Exception ex) { if (await Tools.HandlePageErrorAsync(ex, workbookPageIndex + 1, context, !loggedPageError, cancellationToken).ConfigureAwait(false)) { return; } loggedPageError = true; workbookPageIndex++; } worksheetIndex++; } // set the real count if some of the sheets turned out to be empty if (workbookPageIndex < estimatedPageCount) { await context.SetPageCountAsync(workbookPageIndex, cancellationToken).ConfigureAwait(false); } }
/// <summary> /// Excel转为图片 /// </summary> /// <param name="source">源文件路径</param> /// <param name="target">图片保存的文件夹路径</param> /// <param name="dpi">dpi</param> /// <param name="format">图片格式</param> public static bool ConverToImage(string source, string target, int resolution = 300, AsposeConvertDelegate d = null) { double percent = 0.0; int page = 0; int total = 0; double second = 0; string path = ""; string message = ""; DateTime startTime = DateTime.Now; if (!FileUtil.CreateDirectory(target)) { throw new DirectoryNotFoundException(); } if (!File.Exists(source)) { throw new FileNotFoundException(); } if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.1; message = "正在解析文件!"; d.Invoke(percent, page, total, second, path, message); } LoadOptions loadOptions = new LoadOptions(LoadFormat.Auto); Workbook workbook = new Workbook(source, loadOptions); total = workbook.Worksheets.Count; if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.2; message = "开始转换文件,共" + total + "页!"; d.Invoke(percent, page, total, second, path, message); } logger.Info("ConverToImage - source=" + source + ", target=" + target + ", pageCount=" + total); for (page = 0; page < total; page++) { Worksheet sheet = workbook.Worksheets[page]; ImageOrPrintOptions op = new ImageOrPrintOptions(); op.ImageFormat = ImageFormat.Png; op.HorizontalResolution = resolution; op.VerticalResolution = resolution; SheetRender sr = new SheetRender(sheet, op); for (int j = 0; j < sr.PageCount; j++) { Bitmap bitmap = sr.ToImage(j); path = target + "\\" + (page + 1) + "_" + (j + 1) + ".png"; bitmap.Save(path); if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.2 + (page + 1) * 0.8 / total; message = "正在转换第" + (page + 1) + "/" + total + "页!"; d.Invoke(percent, (page + 1), total, second, path, message); } } } return(true); }
/**/ /// <summary> /// 将Word文档转换为图片的方法 /// </summary> /// <param name="wordInputPath">Word文件路径</param> /// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为Word所在路径</param> /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数</param> /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param> private void _ConvertToImage(string filepath, string outpath, int startPage, int endPage, int resolution = 300) { try { var workBook = new Workbook(filepath); if (workBook == null) { throw new Exception("Excel文件无效或者Excel文件已被加密!"); } var iop = new ImageOrPrintOptions(); iop.ImageFormat = ImageFormat.Png; //iop.AllColumnsInOnePagePerSheet = true; iop.ChartImageType = ImageFormat.Png; iop.OnePagePerSheet = true; iop.HorizontalResolution = 400; iop.VerticalResolution = 400; if (!Directory.Exists(outpath)) { Directory.CreateDirectory(outpath); } if (startPage <= 0) { startPage = 0; } if (endPage > workBook.Worksheets.Count || endPage <= 0) { endPage = workBook.Worksheets.Count; } if (resolution <= 0) { resolution = 300; } for (int index = startPage; index < endPage; index++) { if (this._cancelled) { break; } Worksheet item = workBook.Worksheets[index]; SheetRender sr = new SheetRender(item, iop); for (int kindex = 0; kindex < sr.PageCount; kindex++) { sr.ToImage(kindex, outpath + item.Name + ".png"); System.Threading.Thread.Sleep(200); } if (!_cancelled && this.OnProgressChanged != null) { this.OnProgressChanged(index + 1, endPage); } } if (this._cancelled) { return; } if (this.OnConvertSucceed != null) { this.OnConvertSucceed(); } } catch (Exception ex) { if (this.OnConvertFailed != null) { this.OnConvertFailed(ex.Message); } } }
/// <summary> /// Excel转为图片 /// </summary> /// <param name="source">源文件路径</param> /// <param name="target">图片保存的文件夹路径</param> /// <param name="dpi">dpi</param> /// <param name="format">图片格式</param> public static bool ConverToImage(string source, string target, int resolution = 300, AsposeConvertDelegate d = null) { double percent = 0.0; int page = 0; int total = 0; double second = 0; string path = ""; string message = ""; DateTime startTime = DateTime.Now; if (!FileUtil.CreateDirectory(target)) { throw new DirectoryNotFoundException(); } if (!File.Exists(source)) { throw new FileNotFoundException(); } if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.1; message = "正在解析文件!"; d.Invoke(percent, page, total, second, path, message); } LoadOptions loadOptions = new LoadOptions(LoadFormat.Auto); Workbook workbook = new Workbook(source, loadOptions); total = workbook.Worksheets.Count; if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.2; message = "开始转换文件,共" + total + "页!"; d.Invoke(percent, page, total, second, path, message); } logger.Info("ConverToImage - source=" + source + ", target=" + target + ", pageCount=" + total); for (page = 0; page < total; page++) { Worksheet sheet = workbook.Worksheets[page]; ImageOrPrintOptions op = new ImageOrPrintOptions(); op.ImageFormat = ImageFormat.Png; op.HorizontalResolution = resolution; op.VerticalResolution = resolution; SheetRender sr = new SheetRender(sheet, op); for (int j = 0; j < sr.PageCount; j++ ) { Bitmap bitmap = sr.ToImage(j); path = target + "\\" + (page + 1) + "_" + (j + 1) + ".png"; bitmap.Save(path); if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.2 + (page + 1) * 0.8 / total; message = "正在转换第" + (page + 1) + "/" + total + "页!"; d.Invoke(percent, (page + 1), total, second, path, message); } } } return true; }