渲染到 PDF 时控制 MS Excel 工作簿中外部资源的加载

可能的使用场景

您的 Excel 文件可能包含外部资源,例如链接的图像或对象。当您将 Excel 文件转换为 PDF 时,Aspose.Cells 会检索这些外部资源并将它们呈现给 PDF。但有时,您不想加载这些外部资源,不仅如此,您还想操作它们。您可以使用工作簿设置.StreamProvider它实现了IStreamProvider界面。

渲染到 PDF 时控制 MS Excel 工作簿中外部资源的加载

下面的示例代码解释了如何使用工作簿设置.StreamProvider控制外部资源的加载和操作。请检查示例 Excel 文件在代码中使用输出 PDF由代码生成。这截屏展示了如何旧的外部图像示例 Excel 文件中的替换为新图片在输出 PDF 中。

待办事项:图片_替代_文本

示例代码

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
//Implement IStreamProvider
class MyStreamProvider : IStreamProvider
{
public void CloseStream(StreamProviderOptions options)
{
System.Diagnostics.Debug.WriteLine("-----Close Stream-----");
}
public void InitStream(StreamProviderOptions options)
{
string sourceDir = RunExamples.Get_SourceDirectory();
System.Diagnostics.Debug.WriteLine("-----Init Stream-----");
//Read the new image in a memory stream and assign it to Stream property
byte[] bts = File.ReadAllBytes(sourceDir + "newPdfSaveOptions_StreamProvider.png");
MemoryStream ms = new MemoryStream(bts);
options.Stream = ms;
}
}
public static void Run()
{
//Source directory
string sourceDir = RunExamples.Get_SourceDirectory();
//Output directory
string outputDir = RunExamples.Get_OutputDirectory();
//Load source Excel file containing external image
Workbook wb = new Workbook(sourceDir + "samplePdfSaveOptions_StreamProvider.xlsx");
//Specify Pdf Save Options - Stream Provider
PdfSaveOptions opts = new PdfSaveOptions();
opts.OnePagePerSheet = true;
wb.Settings.ResourceProvider = new MyStreamProvider();
//Save the workbook to Pdf
wb.Save(outputDir + "outputPdfSaveOptions_StreamProvider.pdf", opts);
Console.WriteLine("ControlLoadingOfExternalResourcesInExcelToPDF executed successfully.\r\n");
}