using ExcelToPdfService.Services; using Microsoft.AspNetCore.Mvc; namespace ExcelToPdfService.Controllers; [ApiController] [Route("api/[controller]")] public class ExcelToPdfController : ControllerBase { private readonly IExcelToPdfService _service; public ExcelToPdfController(IExcelToPdfService service) => _service = service; /// Upload Excel file → nhận PDF trả về [HttpPost("convert")] public async Task Convert( IFormFile file, [FromQuery] string? printArea = null, [FromQuery] bool landscape = false) { if (file == null || file.Length == 0) return BadRequest(new { success = false, message = "No file uploaded" }); var ext = Path.GetExtension(file.FileName).ToLowerInvariant(); if (ext != ".xlsx" && ext != ".xls") return BadRequest(new { success = false, message = "Only .xlsx/.xls files are supported" }); await using var stream = file.OpenReadStream(); var pdfBytes = await _service.ConvertAsync(stream, printArea, landscape); var fileName = Path.GetFileNameWithoutExtension(file.FileName) + ".pdf"; return File(pdfBytes, "application/pdf", fileName); } /// Chuyển đổi file Excel theo đường dẫn trên server [HttpPost("convert-by-path")] public async Task ConvertByPath([FromBody] ConvertByPathRequest req) { if (string.IsNullOrWhiteSpace(req.FilePath)) return BadRequest(new { success = false, message = "FilePath is required" }); try { var pdfBytes = await _service.ConvertFileAsync(req.FilePath, req.PrintArea, req.Landscape); var fileName = Path.GetFileNameWithoutExtension(req.FilePath) + ".pdf"; return File(pdfBytes, "application/pdf", fileName); } catch (FileNotFoundException) { return NotFound(new { success = false, message = $"File not found: {req.FilePath}" }); } catch (Exception ex) { return StatusCode(500, new { success = false, message = ex.Message }); } } /// Health check [HttpGet("health")] public IActionResult Health() => Ok(new { status = "ok", version = "1.0.0", time = DateTime.UtcNow }); } public record ConvertByPathRequest(string FilePath, string? PrintArea = null, bool Landscape = false);