You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core如何将上传的Word文件自动转换为PDF供用户预览

实现方案

1. 引入转换组件

直接在项目Nuget包管理器中安装Free Spire.Doc for .NET,无需在服务器安装Office即可完成Word转PDF操作,满足常规业务场景需求。如果有大文件转换需求,也可替换为LibreOffice命令行转换方案,在服务器部署LibreOffice后调用系统命令完成转换即可。

2. 新增存储目录

在项目根目录创建pdf_cache文件夹,专门存储转换后的PDF预览文件,和upload目录下的原始Word文件按文件名一一映射,方便调用。

3. 修改上传逻辑,加入自动转换

修改你现有POST类型的Index1上传方法,在Word文件保存到upload目录后,自动触发转换逻辑:

[HttpPost]
public IActionResult Index1(IFormFile[] files)
{
    foreach (var file in files)
    {
        var fileName = System.IO.Path.GetFileName(file.FileName);
        var filePath = Path.Combine(Directory.GetCurrentDirectory(), "upload", fileName);

        if (System.IO.File.Exists(filePath))
        {
            System.IO.File.Delete(filePath);
        }

        using (var localFile = System.IO.File.OpenWrite(filePath))
        using (var uploadedFile = file.OpenReadStream())
        {
            uploadedFile.CopyTo(localFile);
        }

        // 新增:Word文件自动转PDF
        var ext = Path.GetExtension(fileName).ToLowerInvariant();
        if (ext is ".docx" or ".doc")
        {
            var pdfFileName = Path.GetFileNameWithoutExtension(fileName) + ".pdf";
            var pdfSavePath = Path.Combine(Directory.GetCurrentDirectory(), "pdf_cache", pdfFileName);
            // 存在旧预览文件直接覆盖
            if (System.IO.File.Exists(pdfSavePath))
            {
                System.IO.File.Delete(pdfSavePath);
            }
            using (var doc = new Spire.Doc.Document(filePath))
            {
                doc.SaveToFile(pdfSavePath, Spire.Doc.FileFormat.PDF);
            }
        }
    }
    ViewBag.Message = "Files are successfully uploaded";

    var model = new FilesViewModel();
    foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
    {
        model.Files.Add(
            new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
    }
    return View(model);
}

4. 新增PDF预览接口

新增专门的预览接口,用户点击预览时返回对应PDF文件直接在浏览器加载:

public async Task<IActionResult> Preview(string originalFileName)
{
    if (string.IsNullOrWhiteSpace(originalFileName))
        return Content("无效的文件名参数");
    
    var ext = Path.GetExtension(originalFileName).ToLowerInvariant();
    if (ext is not (".docx" or ".doc"))
        return Content("仅支持Word文档预览");
    
    var pdfFileName = Path.GetFileNameWithoutExtension(originalFileName) + ".pdf";
    var pdfPath = Path.Combine(Directory.GetCurrentDirectory(), "pdf_cache", pdfFileName);
    
    if (!System.IO.File.Exists(pdfPath))
        return Content("预览文件生成失败,请重新上传原文档");

    var memory = new MemoryStream();
    using (var stream = new FileStream(pdfPath, FileMode.Open))
    {
        await stream.CopyToAsync(memory);
    }
    memory.Position = 0;
    // 直接在浏览器中打开PDF
    return File(memory, "application/pdf");
}

5. 前端逻辑调整

在文件列表页给每个文件新增两个操作入口:

  • 预览按钮:针对Word文件点击时调用Preview接口,传入原始Word文件名,浏览器会直接加载PDF供用户预览
  • 下载按钮:继续调用原有Download接口,返回原始docx/doc文件

注意事项

  • Free Spire.Doc免费版最多支持转换1000个段落的Word文档,如有更大文档转换需求可以购买商业授权,或者切换为LibreOffice命令行转换方案
  • 生产环境请增加文件格式校验,避免恶意篡改后缀的文件被上传转换
  • 当前代码中用户信息为硬编码仅适用于测试,生产环境请将用户信息存入数据库,且密码需要加盐加密后存储

内容的提问来源于stack exchange,提问作者RaresHoriaPanait

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 14:36:03