Home > Software design >  How to generate PDF from Excel MemoryStream created using EPPlus.core?
How to generate PDF from Excel MemoryStream created using EPPlus.core?

Time:03-24

I have to create a API in dot net core which will return the excel as PDF. Excel works fine but when I try to send it in PDF content as you can see in the following code:

        [HttpPost]
        [Route("ExportToPdf")]
        public IActionResult ExportToPdf()
        {
            MemoryStream stream = MyClassExcelWorkBook.GetExcel();
            return File(stream, "application/pdf", "excel-Demo.pdf");
        }

MyClassExcelWorkBook is a class where in GetExcel() will return MemoryStream of excel that has been created. I have created the excel memory stream from epplus.core library that I have installed from NuGet. Can anyone help in creating the excel memory stream to pdf as response?

CodePudding user response:

According to the official documentation of the EPPlus, the library is not supporting any direct export to PDF.

But there is a workaround option would be exporting the Excel using the one of the EPPlus 6.0 beta feature, HtmlExporter and get the HTML and styles.

This can be fed into the html to pdf converter like iText pdfHTML, sharkPdf(.NET wrapper for wkhtmltopdf) to export as PDF.

CodePudding user response:

An xlsx stream is a Microsoft zip archive but a PDF is a printer output so a basic application cannot convert a zip file into a printer file unless for example using the MS interop export XLS render to MS PDF printer. And that would be the best method on an Office.net PC.

Presumably you are allowing for MS.net users without any version of an installed MS Office.

There are many variations or addons to EPPlus that can do the necessary conversion to PDF and https://www.nuget.org/packages/EpplusExcel/ is specifically designed as one of them but as its V1 and not updated the past 7 years may not be best final supported solution, but worth a try just to see how its methodologies work for you.

The most common converter avoiding interop is using Libre/Open Office with its basic language alternative to VBA to print spread sheet areas to PDF printouts.

I would avoid any X/HTML methods as changing from sheet area structure to reflowing text which is not suited to PDF fixed page production, unless each page/sheet is converted to a fixed layout equal to a single PDF page.

  • Related