Files
exceltopdf-service/Controllers/ExcelToPdfController.cs
T
huanld cecde2bc1c feat: standalone ExcelToPdfService - ASP.NET Core 8 + Syncfusion
- 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)
2026-05-18 15:05:10 +07:00

64 lines
2.4 KiB
C#

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;
/// <summary>Upload Excel file → nhận PDF trả về</summary>
[HttpPost("convert")]
public async Task<IActionResult> 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);
}
/// <summary>Chuyển đổi file Excel theo đường dẫn trên server</summary>
[HttpPost("convert-by-path")]
public async Task<IActionResult> 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 });
}
}
/// <summary>Health check</summary>
[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);