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

可能的使用场景

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

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

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

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

示例代码

// 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);
}