Home > Software design >  aspose convert pdf to excel as temporary file
aspose convert pdf to excel as temporary file

Time:12-21

The question is rather simple. I am using the aspose library to convert a pdf file to excel. The excel file is subsequently written to the database and this generated excel file is not needed in the future.

My method:

public void main(MultipartFile file) throws IOException {

        InputStream inputStream = file.getInputStream();

        Document document = new Document(inputStream);

        ExcelSaveOptions options = new ExcelSaveOptions();

        options.setFormat(ExcelSaveOptions.ExcelFormat.XLSX);

        document.save("newExcelFile.xlsx", options);
    }

In this method, the file is saved to the root folder of the project (if it is running locally). How can I not store this file, but make it temporary? My question is that this project is located on the server, and I would not like to create directories specifically for this file.

CodePudding user response:

The Document.save() method has an overload for saving to an OutputStream (See here for the API reference).

Given that you can store the result to anything that implements an OutputStream, you can provide any implementation that you want - one useful option might be to use ByteArrayOutputStream to store the result in memory, or possibly - just use Files.createTempFile() and create a FileOutputStream for that.

For example, your code may be rewritten thus:

public byte[] convertToExcel(MultipartFile file) throws IOException {
    InputStream inputStream = file.getInputStream();
    Document document = new Document(inputStream);
    ExcelSaveOptions options = new ExcelSaveOptions();
    options.setFormat(ExcelSaveOptions.ExcelFormat.XLSX);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    document.save(baos, options);
    return baos.toByteArray();
}
  • Related