cecde2bc1c
- Services/ExcelToPdfService.cs: core conversion logic (XlsIORenderer) - Controllers/ExcelToPdfController.cs: REST API endpoints * POST /api/ExcelToPdf/convert (file upload) * POST /api/ExcelToPdf/convert-by-path (server path) * GET /api/ExcelToPdf/health - Program.cs: minimal API setup, 50MB upload limit - appsettings.json: port 5200, Syncfusion license - Syncfusion 21.1.37 (XlsIO + Pdf + XlsIORenderer) - Binary signed: Azure Trusted Signing (Private Trust)
66 lines
2.1 KiB
C#
66 lines
2.1 KiB
C#
using Syncfusion.XlsIO;
|
|
using Syncfusion.XlsIORenderer;
|
|
|
|
namespace ExcelToPdfService.Services;
|
|
|
|
public interface IExcelToPdfService
|
|
{
|
|
Task<byte[]> ConvertAsync(Stream excelStream, string? printArea = null, bool landscape = false);
|
|
Task<byte[]> ConvertFileAsync(string filePath, string? printArea = null, bool landscape = false);
|
|
}
|
|
|
|
public class ExcelToPdfService : IExcelToPdfService
|
|
{
|
|
public Task<byte[]> ConvertAsync(Stream excelStream, string? printArea = null, bool landscape = false)
|
|
{
|
|
using var excelEngine = new ExcelEngine();
|
|
var app = excelEngine.Excel;
|
|
app.DefaultVersion = ExcelVersion.Xlsx;
|
|
|
|
var workbook = app.Workbooks.Open(excelStream);
|
|
return Task.FromResult(Convert(workbook, printArea, landscape));
|
|
}
|
|
|
|
public Task<byte[]> ConvertFileAsync(string filePath, string? printArea = null, bool landscape = false)
|
|
{
|
|
if (!File.Exists(filePath))
|
|
throw new FileNotFoundException("Excel file not found", filePath);
|
|
|
|
using var excelEngine = new ExcelEngine();
|
|
var app = excelEngine.Excel;
|
|
app.DefaultVersion = ExcelVersion.Xlsx;
|
|
|
|
using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
|
|
var workbook = app.Workbooks.Open(fs);
|
|
return Task.FromResult(Convert(workbook, printArea, landscape));
|
|
}
|
|
|
|
private static byte[] Convert(IWorkbook workbook, string? printArea, bool landscape)
|
|
{
|
|
var sheet = workbook.Worksheets[0];
|
|
|
|
// Page setup
|
|
sheet.PageSetup.FitToPagesWide = 1;
|
|
sheet.PageSetup.FitToPagesTall = 0;
|
|
sheet.PageSetup.Orientation = landscape
|
|
? ExcelPageOrientation.Landscape
|
|
: ExcelPageOrientation.Portrait;
|
|
|
|
if (!string.IsNullOrWhiteSpace(printArea))
|
|
sheet.PageSetup.PrintArea = printArea;
|
|
|
|
// Convert
|
|
var renderer = new XlsIORenderer();
|
|
var settings = new XlsIORendererSettings
|
|
{
|
|
LayoutOptions = LayoutOptions.Automatic
|
|
};
|
|
|
|
var pdf = renderer.ConvertToPDF(workbook, settings);
|
|
|
|
using var ms = new MemoryStream();
|
|
pdf.Save(ms);
|
|
return ms.ToArray();
|
|
}
|
|
}
|