使用 DrawObjectEventHandler 类渲染到 PDF 时获取 DrawObject 和 Bound

可能的使用场景

Aspose.Cells 提供抽象类绘图对象事件处理器它有一个画()方法。用户可以实施绘图对象事件处理器并利用画()获取方法绘图对象并在将 Excel 渲染为 PDF 或图像时绑定。下面简单介绍一下参数画()方法。

如果您将 Excel 文件渲染到 PDF,那么您可以利用绘图对象事件处理器PdfSaveOptions.DrawObjectEventHandler.同样,如果您将 Excel 文件渲染为图像,您可以使用绘图对象事件处理器ImageOrPrintOptions.DrawObjectEventHandler.

使用 DrawObjectEventHandler 类在渲染到 Pdf 时获取 DrawObject 和 Bound

请参阅以下示例代码。它加载了示例 Excel 文件并将其另存为输出 PDF.在渲染到 PDF 时,它利用PdfSaveOptions.DrawObjectEventHandler财产和捕获绘图对象现有单元格和对象的边界,例如图像等。如果绘图对象type 是 Cell,它打印它的 Bound 和 StringValue。如果绘图对象类型是图像,它打印它的绑定和形状名称。请查看下面给出的示例代码的控制台输出以获得更多帮助。

示例代码

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aspose.Cells.Rendering;
namespace Aspose.Cells.Examples.CSharp.Rendering
{
class GetDrawObjectAndBoundUsingDrawObjectEventHandler
{
//Implement the concrete class of DrawObjectEventHandler
class clsDrawObjectEventHandler : DrawObjectEventHandler
{
public override void Draw(DrawObject drawObject, float x, float y, float width, float height)
{
Console.WriteLine("");
//Print the coordinates and the value of Cell object
if (drawObject.Type == DrawObjectEnum.Cell)
{
Console.WriteLine("[X]: " + x + " [Y]: " + y + " [Width]: " + width + " [Height]: " + height + " [Cell Value]: " + drawObject.Cell.StringValue);
}
//Print the coordinates and the shape name of Image object
if (drawObject.Type == DrawObjectEnum.Image)
{
Console.WriteLine("[X]: " + x + " [Y]: " + y + " [Width]: " + width + " [Height]: " + height + " [Shape Name]: " + drawObject.Shape.Name);
}
Console.WriteLine("----------------------");
}
}
public static void Run()
{
//Load sample Excel file
Workbook wb = new Workbook("sampleGetDrawObjectAndBoundUsingDrawObjectEventHandler.xlsx");
//Specify Pdf save options
PdfSaveOptions opts = new PdfSaveOptions();
//Assign the instance of DrawObjectEventHandler class
opts.DrawObjectEventHandler = new clsDrawObjectEventHandler();
//Save to Pdf format with Pdf save options
wb.Save("outputGetDrawObjectAndBoundUsingDrawObjectEventHandler.pdf", opts);
}
}
}

控制台输出

 [X]: 153.6035 [Y]: 82.94118 [Width]: 103.2035 [Height]: 14.47059 [Cell Value]: This is sample text.

----------------------

[X]: 267.6917 [Y]: 153.4853 [Width]: 160.4491 [Height]: 128.0647 [Shape Name]: Sun

----------------------