当前位置: 首页 > news >正文

ali linux 安装libreoffice

sudo yum install libreoffice-headless libreoffice-writer# 检查版本
libreoffice --version# 测试转换功能
libreoffice --headless --convert-to pdf test.docx --outdir /tmp

 C#实现:

using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;namespace SaaS.OfficialWebSite.Web.Controllers
{public class OfficeController : Controller{private readonly ILogger<OfficeController> _logger;public OfficeController(ILogger<OfficeController> logger){_logger = logger;}public IActionResult Index(){return View();}[HttpPost]public async Task<IActionResult> ConvertToPdf(){if (Request.Form.Files.Count == 0)return BadRequest("No file uploaded");var file = Request.Form.Files[0];if (file.Length == 0)return BadRequest("Empty file");// 验证文件类型var allowedExtensions = new[] { ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx" };var fileExtension = Path.GetExtension(file.FileName).ToLower();if (!allowedExtensions.Contains(fileExtension))return BadRequest("Unsupported file type");try{// 创建临时目录var tempFolder = Path.Combine(Directory.GetCurrentDirectory(), "Uploads");if (!Directory.Exists(tempFolder)){Directory.CreateDirectory(tempFolder);}// 生成唯一文件名var uniqueId = Guid.NewGuid().ToString();var inputPath = Path.Combine(tempFolder, $"{uniqueId}{fileExtension}");var outputPath = Path.Combine(tempFolder, $"{uniqueId}.pdf");// 保存上传的文件using (var stream = new FileStream(inputPath, FileMode.Create)){await file.CopyToAsync(stream);}// 调用 LibreOffice 转换var result = await ConvertWithLibreOffice(inputPath, outputPath);if (!result.success){_logger.LogError(Newtonsoft.Json.JsonConvert.SerializeObject(result));return StatusCode(500, result.message);}// 清理临时文件System.IO.File.Delete(inputPath);// 返回下载URLvar outputFileName = Path.GetFileNameWithoutExtension(outputPath) + ".pdf";var downloadUrl = Url.Action("Download", "Office", new { fileName = outputFileName, originalName = file.FileName }, Request.Scheme);downloadUrl = downloadUrl.Replace("http", "https");return Ok(new{success = true,downloadUrl = downloadUrl});}catch (Exception ex){_logger.LogError(ex,ex.Message);return StatusCode(500, $"Conversion failed: {ex.Message}");}}private async Task<(bool success, string message)> ConvertWithLibreOffice(string inputPath, string outputPath){try{var psi = new ProcessStartInfo{FileName = "libreoffice",Arguments = $"--headless --convert-to pdf \"{inputPath}\" --outdir \"{Path.GetDirectoryName(outputPath)}\" ",RedirectStandardOutput = true,RedirectStandardError = true,UseShellExecute = false,CreateNoWindow = true};using var process = Process.Start(psi);await process.WaitForExitAsync();if (process.ExitCode != 0){var error = await process.StandardError.ReadToEndAsync();return (false, $"LibreOffice error: {error}");}return (true, null);}catch (Exception ex){return (false, $"Process error: {ex.Message}");}}[HttpGet]public IActionResult Download(string fileName,string originalName){var tempFolder = Path.Combine(Directory.GetCurrentDirectory(), "Uploads");if (!System.IO.File.Exists(Path.Combine(tempFolder, fileName))){return NotFound();}var fileStream = new FileStream(Path.Combine(tempFolder,fileName), FileMode.Open, FileAccess.Read);var result = File(fileStream, "application/pdf", Path.GetFileNameWithoutExtension(originalName) + ".pdf");// 文件下载后删除Response.OnCompleted(async () =>{fileStream.Dispose();try { System.IO.File.Delete(Path.Combine(tempFolder, fileName)); } catch { }});return result;}}public static class ProcessExtensions{public static Task WaitForExitAsync(this Process process){var tcs = new TaskCompletionSource<bool>();process.EnableRaisingEvents = true;process.Exited += (s, e) => tcs.SetResult(true);return tcs.Task;}}
}

运行效果:Office转PDF在线转换器

http://www.dtcms.com/a/271122.html

相关文章:

  • Linux 系统 docker 部署 Dify
  • Airtest 的 Poco 框架中,offspring()
  • 【网络】Linux 内核优化实战 - net.ipv4.tcp_ecn
  • Protable 问题记录
  • 【RK3568+PG2L50H开发板实验例程】FPGA部分 | ROM、RAM、FIFO 的使用
  • 使用DDR4控制器实现多通道数据读写(十九)
  • 通过Tcl脚本命令:set_param labtools.auto_update_hardware 0
  • 闲庭信步使用图像验证平台加速FPGA的开发:第六课——测试图案的FPGA实现
  • 闲庭信步使用图像验证平台加速FPGA的开发:第七课——获取RAW图像
  • RAM带宽计算及分析
  • 双esp8266-01s间TCP通讯
  • 云服务器域名可以设置多少二级域名
  • 为什么Spring中推荐使用构造函数而不是@Autowired字段注入
  • WIFI协议全解析04:从芯片角度看WiFi协议:ESP32/8266 支持了哪些?
  • 如何解决pip安装报错ModuleNotFoundError: No module named ‘re’问题
  • python学习打卡:DAY 25 异常处理
  • 在 PyCharm 中安装并配置 Node.js 的指南
  • npm init vue@latestnpm error code ETIMEDOUT
  • windows指定某node及npm版本下载
  • 使用Python求解最优化问题:从理论到实践的全方位指南
  • 嵌入式调试LOG日志输出(以STM32为例)
  • Oracle 数据库升级踩坑:DBLink ORA-02019 问题解决思路
  • Mysql: Bin log原理以及三种格式
  • SAP ERP与Oracle EBS对比,两个ERP系统有什么区别?
  • 矩阵之方阵与行列式的关系
  • JSP动态网页开发基础
  • Rust与人工智能(AI)技术
  • 网络安全之RCE分析与利用详情
  • Hadoop(一)
  • Claude Code: Best practices for agentic coding