控制在将MS Excel工作簿渲染为PDF时加载外部资源
Contents
[
Hide
]
可能的使用场景
您的Excel文件可能包含外部资源,例如链接的图像或对象。当您将Excel文件转换为PDF时,Aspose.Cells会检索这些外部资源并将它们呈现到PDF中。但有时,您不想加载这些外部资源,更甚者,您希望操纵它们。您可以使用 WorkbookSettings.StreamProvider 实现 IStreamProvider 接口来实现这一点。
控制在将MS Excel工作簿渲染为PDF时加载外部资源
以下示例代码解释了如何利用 WorkbookSettings.StreamProvider 控制外部资源的加载和操纵它们。请查看代码中使用的 示例Excel文件 和代码生成的 输出PDF。屏幕截图 显示了如何将示例Excel文件中的 旧外部图像 替换为 新图像。
示例代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
} |