Control loading of External Resources in MS Excel Workbook while rendering to PDF
Possible Usage Scenarios
Your Excel file may contain external resources e.g. linked images or objects. When you convert your Excel file to PDF, Aspose.Cells retrieves these external resources and renders them to PDF. But sometimes, you do not want to load these external resources and more than that, you want to manipulate them. You can do this using WorkbookSettings.StreamProvider which implements the IStreamProvider interface.
Control loading of External Resources in MS Excel Workbook while rendering to PDF
The following sample code explains how to make use of WorkbookSettings.StreamProvider to control the loading of external resources and manipulate them. Please check the sample Excel file used inside the code and the output PDF generated by the code. The screenshot shows how the old external image in the sample Excel file was replaced with a new image in the output PDF.
Sample Code
// 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"); | |
} |