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

ASP.NET Core 6 MVC中如何将Office文件字节数组转为PDF字节数组?

ASP.NET Core 6 MVC中Office字节数组转PDF字节数组方案

方案一:正确调用Gotenberg API处理字节数组

你之前调用Gotenberg失败大概率是没有正确构造字节流的上传请求,Gotenberg支持直接通过Multipart表单上传字节流,无需本地文件路径。以下是完整的调用代码:

using System.Net.Http;
using System.Net.Http.Headers;
using System.IO;

public async Task<byte[]> ConvertOfficeToPdfViaGotenberg(byte[] officeBytes, string fileName)
{
    using var httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("http://你的Gotenberg服务地址:3000");

    using var formContent = new MultipartFormDataContent();
    // 将Office字节数组包装为StreamContent
    using var fileStream = new MemoryStream(officeBytes);
    var fileContent = new StreamContent(fileStream);
    // 设置正确的MIME类型,Gotenberg靠此识别文件类型
    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(GetFileMimeType(fileName));
    formContent.Add(fileContent, "files", fileName);

    // 发送转换请求(所有Office类型都用/convert/office端点)
    var response = await httpClient.PostAsync("/convert/office", formContent);
    response.EnsureSuccessStatusCode();

    // 读取返回的PDF字节数组
    return await response.Content.ReadAsByteArrayAsync();
}

// 辅助方法:根据文件名后缀返回对应MIME类型
private string GetFileMimeType(string fileName)
{
    var extension = Path.GetExtension(fileName).ToLowerInvariant();
    return extension switch
    {
        ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        ".doc" => "application/msword",
        ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        ".xls" => "application/vnd.ms-excel",
        ".pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
        ".ppt" => "application/vnd.ms-powerpoint",
        _ => throw new ArgumentException("不支持的Office文件类型")
    };
}

注意事项

  • 确保Gotenberg服务正常运行,端口和地址配置正确
  • 必须传递带正确后缀的文件名(如test.docx),Gotenberg通过文件名后缀识别文件类型
  • 若需自定义转换参数(如页面方向、边距),可在表单中添加额外参数

方案二:使用GemBox系列库(无需Office依赖)

如果Gotenberg仍无法满足需求,可使用GemBox的文档处理库,它支持直接从字节数组读取Office文件并导出为PDF字节数组,无需本地文件路径。

Word转PDF示例

首先安装NuGet包:Install-Package GemBox.Document

using GemBox.Document;
using System.IO;

public byte[] ConvertWordToPdf(byte[] wordBytes)
{
    // 配置GemBox许可证(免费版有页数限制,商业版需购买正式许可证)
    ComponentInfo.SetLicense("FREE-LIMITED-KEY");

    using var inputStream = new MemoryStream(wordBytes);
    var document = DocumentModel.Load(inputStream);

    using var outputStream = new MemoryStream();
    document.Save(outputStream, SaveOptions.PdfDefault);

    return outputStream.ToArray();
}

Excel/PPT转PDF示例

  • Excel转换:安装GemBox.Spreadsheet,代码逻辑类似,使用ExcelFile.Load和ExcelFile.Save
  • PPT转换:安装GemBox.Presentation,使用PresentationDocument.Load和PresentationDocument.Save

方案三:OpenXML SDK + QuestPDF(适合简单文档场景)

如果不想使用第三方付费库,对于结构简单的Word文档(纯文本、基础格式),可以用OpenXML SDK读取内容,再用QuestPDF生成PDF。注意:复杂格式(表格、图片、样式)会丢失。

首先安装NuGet包:Install-Package DocumentFormat.OpenXml 和 Install-Package QuestPDF

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using QuestPDF.Fluent;
using QuestPDF.Infrastructure;
using System.IO;

public byte[] ConvertSimpleWordToPdf(byte[] wordBytes)
{
    // 读取Word文档文本内容
    string textContent;
    using var inputStream = new MemoryStream(wordBytes);
    using var wordDoc = WordprocessingDocument.Open(inputStream, false);
    var body = wordDoc.MainDocumentPart.Document.Body;
    textContent = body.InnerText;

    // 用QuestPDF生成PDF字节数组
    var pdfDocument = Document.Create(container =>
    {
        container.Page(page =>
        {
            page.Size(PageSizes.A4);
            page.Margin(2, Unit.Centimetre);
            page.Content().Text(textContent).FontSize(12).LineHeight(1.5f);
        });
    });

    using var outputStream = new MemoryStream();
    pdfDocument.GeneratePdf(outputStream);
    return outputStream.ToArray();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:15:38