Convert Excel to PDF saving stream not working

HI Team ,

Already I have OpenXML Excel file in the format of bytes and have convert Aspose excel stream format , After that I have tried to convert pdf format in the stream format but is not working .

Pls find the following my code and pls suggest right solution.
private MemoryStream GenerateExcleFileToPDFFile(byte[] ExcelContent)
{
MemoryStream msFile = new MemoryStream();

        if (ExcelContent.Length > 0)
        {
            msFile.Write(ExcelContent, 0, ExcelContent.Length);

            msFile.Position = 0;

            Workbook workbook = new Workbook(msFile);

            workbook.Worksheets[0].IsVisible = false;

            workbook.Save(msFile, SaveFormat.Xlsx);

            workbook.Save(msFile, SaveFormat.Pdf);

            Aspose.Cells.PdfSaveOptions opts = new Aspose.Cells.PdfSaveOptions();

            opts.AllColumnsInOnePagePerSheet = true;

            opts.OptimizationType = Aspose.Cells.Rendering.PdfOptimizationType.MinimumSize;

            //Aspose.Pdf.Document doc = new Aspose.Pdf.Document();

            //doc.Save(msFile)
        }

it is very critical issue to resolve ,pls response quickly
Thanks
Sreeni

@sreeni379,

Your code is not right, so you should correct it. Apparently you are trying to save Excel XLSX and PDF files directly to the same (existing) streams which is not possible (you may get “Memory stream is not expandable” error). Moreover, if your workbook has single sheet in it, then the line of code will throw an error as you must have one visible worksheet in the workbook:

workbook.Worksheets[0].IsVisible = false;  

I tried the following sample code with a sample Excel file and it works fine:
e.g.
Sample code:

byte[] bytes = File.ReadAllBytes("e:\\test2\\Bk_test1.xlsx");
Stream msFile = new MemoryStream(bytes);

Workbook workbook = new Workbook(msFile);

Aspose.Cells.PdfSaveOptions opts = new Aspose.Cells.PdfSaveOptions();
opts.AllColumnsInOnePagePerSheet = true;
opts.OptimizationType = Aspose.Cells.Rendering.PdfOptimizationType.MinimumSize;

MemoryStream msPdf = new MemoryStream();
workbook.Save(msPdf, opts);
msPdf.Seek(0, SeekOrigin.Begin);

byte[] buffer = new byte[msPdf.Length];
buffer = msPdf.ToArray();

File.WriteAllBytes("e:\\test2\\outputPdfFile1.pdf", buffer);

Hope, this helps a bit.

Thanks Amjad,Sahi for quick support, Working fine as per you suggested code .

Thanks
Sreeni

@sreeni379,

Good to know that your issue is sorted out by the suggested code segment. Feel free to write us back if you have further comments or questions.

above also raised question ,Pls can you help us

@sreeni379,

I can only help regarding Aspose.Cells APIs here. Regarding your issue/requirements regarding Aspose.PDF API, please be patient as one our fellow colleagues from Aspose.PDF team will assist you there soon.

1 Like