I am working on converting excel into pdf C#. I have used the below code to convert. When I executed the code the pdf file is successfully created. But I can't able to open the file. it shows an error like "unable to open the file."
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add( DateTime.Now.ToString("dddd, dd MMMM yyyy"));
var currentRow = 2;
worksheet.Row(1).Cells(1, 11).Style.Fill.BackgroundColor = XLColor.FromHtml("#154c79");
worksheet.Row(1).Height = 20;
worksheet.Range(worksheet.Cell(1, 1), worksheet.Cell(1, 11)).Merge();
worksheet.Row(1).Style.Font.SetFontColor(XLColor.WhiteSmoke);
worksheet.Row(1).Style.Font.SetBold();
worksheet.Cell(1, 1).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
worksheet.Cell(1, 1).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Center);
worksheet.Row(1).Cell(1).CreateRichText().AddText("Users Report - " + DateTime.Now.ToString("dddd, dd MMMM yyyy hh:mm tt")).SetBold().SetFontSize(15).SetFontColor(XLColor.White);
worksheet.Row(1).Height = 30;
worksheet.Row(2).Cells(1, 11).Style.Fill.BackgroundColor = XLColor.FromHtml("#eeeee4");
worksheet.Row(2).Style.Font.SetFontColor(XLColor.Black);
worksheet.Row(2).Style.Font.SetBold();
worksheet.Cell(currentRow, 1).Value = "FirstName";
worksheet.Cell(currentRow, 2).Value = "LastName";
worksheet.Cell(currentRow, 3).Value = "Role";
worksheet.Cell(currentRow, 4).Value = "Email";
worksheet.Cell(currentRow, 5).Value = "Phone Number";
foreach (var user in users)
{
currentRow++;
worksheet.Cell(currentRow, 1).Value = user.FirstName;
worksheet.Cell(currentRow, 2).Value = user.LastName;
worksheet.Cell(currentRow, 3).Value = user.UserRole;
worksheet.Cell(currentRow, 4).Value = user.Email;
worksheet.Cell(currentRow, 5).Value = user.PhoneNumber;
}
worksheet.Columns().AdjustToContents();
var workbookBytes = new byte[0];
var workbook2 = new Workbook();
using (var ms = new MemoryStream())
{
workbook.SaveAs(ms);
workbookBytes = ms.ToArray();
ms.Flush();
}
System.IO.File.WriteAllBytes("file.pdf", workbookBytes);
await js.InvokeAsync<Object>("saveAsFile", fileName, Convert.ToBase64String(workbookBytes));
It seems that the pdf file seems to be corrupted.