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

相关文章:

  • 《重构项目》基于Apollo架构设计的项目重构方案(多种地图、多阶段、多任务、状态机管理)
  • Context Engineering:从Prompt Engineering到上下文工程的演进
  • Ragas的Prompt Object
  • 微软 Bluetooth LE Explorer 实用工具的详细使用分析
  • JVM字节码加载与存储中的细节
  • 川翔云电脑:突破硬件极限,重构设计生产力范式
  • 【vim中替换】
  • 【自动驾驶】经典LSS算法解析——深度估计
  • BEV感知算法:自动驾驶的“上帝视角“革命
  • django 一个表中包括id和parentid,如何通过parentid找到全部父爷id
  • 免费扫描软件NAPS2:跨平台支持 旋转裁剪 + 多页合并,纸质文档变 PDF / 图片
  • 详解Kafka重平衡机制详解
  • Python(30)基于itertools生成器的量子计算模拟技术深度解析
  • 18-C#改变形参内容
  • 《设计模式之禅》笔记摘录 - 5.代理模式
  • AI应用实践:制作一个支持超长计算公式的计算器,计算内容只包含加减乘除算法,保存在一个HTML文件中
  • 设计模式(行为型)-责任链模式
  • Flink Forward Asia 2025 主旨演讲精彩回顾
  • 两张图片对比clip功能
  • React 19 概览:新特性与生态系统变革
  • 1.1 ARMv8/ARMv9安全扩展
  • 网络安全之RCE分析与利用详情
  • 前端使用Web Cryptography API进行内容加密,几乎无法破解
  • 循环神经网络详解
  • 数据结构之位图和布隆过滤器
  • Web 前端框架选型:React、Vue 和 Angular 的对比与实践
  • [特殊字符] 突破小样本瓶颈:DataDream——用Stable Diffusion生成高质量分类数据集
  • “AI 曼哈顿计划”:科技竞赛还是人类挑战?
  • VUE混合开发,选哪个PHP框架最顺手?
  • 【Qt】Qt QML json处理