当前位置: 首页 > 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.lryc.cn/news/583030.html

相关文章:

  • Markdown入门
  • 类和对象拓展——日期类
  • Django核心知识点详解:JSON、AJAX、Cookie、Session与用户认证
  • npu-smi info 华为昇腾NPU 状态监控工具解读
  • 类与对象【下篇】-- 关于类的其它语法
  • 树莓派vsftpd文件传输服务器的配置方法
  • 【02】MFC入门到精通——MFC 手动添加创建新的对话框模板
  • overleaf 改为XeLatex
  • Vue响应式原理四:响应式-监听属性变化
  • 正点原子学习 用户权限管理
  • 【python基础】运算符与布尔值全解析
  • 智慧航天运载体系全生命周期监测 | 图扑数字孪生
  • Shader面试题100道之(41-60)
  • 从0实现线性回归模型
  • vue3.2 前端动态分页算法
  • 「Java案例」打印数字金字塔
  • [Backlog] 核心协调器 | 终端用户界面(TUI)实现 | 多分支任务冲突解决 | 测试验证体系
  • 技术支持丨解决 ServBay 在 Windows 启动时反复提示安装 .NET 的问题
  • Python(30)基于itertools生成器的量子计算模拟技术深度解析
  • 使用LLaMA-Factory微调Qwen2.5-VL-3B 的目标检测任务-数据集格式转换(voc 转 ShareGPT)
  • 【洛谷题单】--顺序结构(一)
  • C++高频知识点(六)
  • [NOIP][C++]洛谷P1376 [USACO05MAR] Yogurt factory 机器工厂
  • LeetCode--42.接雨水
  • C++(STL源码刨析/vector)
  • 从历史航拍图像中去除阴影
  • 11款常用C++在线编译与运行平台推荐与对比
  • 力扣-75.颜色分类
  • Web后端开发-Mybatis
  • qt-C++笔记之setCentralWidget的使用