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 PdfSaveOptions.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 PdfSaveOptions.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.

todo:image_alt_text

Sample Code

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Implement IStreamProvider
class MyStreamProvider implements IStreamProvider {
public void closeStream(StreamProviderOptions options) throws Exception {
System.out.println("-----Close Stream-----");
}
public void initStream(StreamProviderOptions options) throws Exception {
System.out.println("-----Init Stream-----");
// Read the new image in a memory stream and assign it to Stream property
File imgFile = new File( srcDir + "newPdfSaveOptions_StreamProvider.png");
byte[] bts = new byte[(int) imgFile.length()];
FileInputStream fin = new FileInputStream(imgFile);
fin.read(bts);
fin.close();
ByteArrayOutputStream baout = new ByteArrayOutputStream();
baout.write(bts);
baout.close();
options.setStream(baout);
}
}//MyStreamProvider
// ------------------------------------------------
// ------------------------------------------------
void Run() throws Exception {
// Load source Excel file containing external image
Workbook wb = new Workbook(srcDir + "samplePdfSaveOptions_StreamProvider.xlsx");
// Specify Pdf Save Options - Stream Provider
PdfSaveOptions opts = new PdfSaveOptions();
opts.setOnePagePerSheet(true);
opts.setStreamProvider(new MyStreamProvider());
// Save the workbook to Pdf
wb.save(outDir + "outputPdfSaveOptions_StreamProvider.pdf", opts);
}