控制在将MS Excel工作簿渲染为PDF时加载外部资源
Contents
[
Hide
]
可能的使用场景
您的Excel文件可能包含外部资源,例如链接的图像或对象。当您将Excel文件转换为PDF时,Aspose.Cells会检索这些外部资源并将它们渲染为PDF。但有时,您可能不希望加载这些外部资源,甚至希望对它们进行操作。您可以使用PdfSaveOptions.StreamProvider来实现IStreamProvider接口。
控制在将MS Excel工作簿渲染为PDF时加载外部资源
以下样本代码解释了如何使用PdfSaveOptions.StreamProvider来控制加载外部资源并对其进行操作。请查看代码中使用的sample Excel file以及代码生成的output 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-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); | |
} |