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

新手求助:能否在ASP.Net Core Web API中使用QuestPDF库?

在ASP.NET Core Web API中使用QuestPDF生成问卷PDF

1. 安装QuestPDF包

在Web API项目中通过NuGet安装QuestPDF,命令行执行:

Install-Package QuestPDF

或直接在NuGet包管理器中搜索安装。

2. 封装PDF生成逻辑

将你控制台项目中的PDF生成代码封装为可复用类,比如创建QuestionnairePdfGenerator,接收问卷数据模型并生成PDF字节流:

using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;

public class QuestionnairePdfGenerator
{
    // 问卷数据模型,按需调整字段
    public class QuestionnaireData
    {
        public string Title { get; set; }
        public List<QuestionAnswerPair> Questions { get; set; }
        public string LogoPath { get; set; }
    }

    public class QuestionAnswerPair
    {
        public string Question { get; set; }
        public string Answer { get; set; }
    }

    public byte[] GenerateQuestionnairePdf(QuestionnaireData data)
    {
        // 配置QuestPDF许可证(社区版免费用于非商业场景)
        QuestPDF.Settings.License = LicenseType.Community;
        // 若控制台用了自定义字体,这里需同步注册
        FontManager.RegisterFontFromFile("path/to/your/custom-font.ttf");

        return Document.Create(container =>
        {
            container.Page(page =>
            {
                page.Size(PageSizes.A4);
                page.Margin(2, Unit.Centimetre);
                
                // 页眉:Logo+标题
                page.Header()
                    .Row(row =>
                    {
                        row.Item().Image(data.LogoPath).ScaleToFit(80, 80);
                        row.Item().AlignCenter().Text(data.Title).FontSize(20).Bold();
                    });
                
                // 主体:问卷表格
                page.Content()
                    .PaddingVertical(1, Unit.Centimetre)
                    .Table(table =>
                    {
                        // 表头
                        table.Header(header =>
                        {
                            header.Cell().Text("问题").Bold().Background(Colors.Grey.Lighten3);
                            header.Cell().Text("答案").Bold().Background(Colors.Grey.Lighten3);
                        });

                        // 填充问卷数据
                        foreach (var item in data.Questions)
                        {
                            table.Cell().Text(item.Question).Padding(5);
                            table.Cell().Text(item.Answer).Padding(5);
                        }
                    });
            });
        }).GeneratePdf();
    }
}

3. 编写API控制器接口

在Web API控制器中创建接口,处理HTTP请求并返回PDF文件:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/pdf")]
public class PdfController : ControllerBase
{
    // GET接口:返回示例问卷PDF
    [HttpGet("questionnaire")]
    public IActionResult GetQuestionnairePdf()
    {
        // 模拟问卷数据,实际可从数据库/请求体获取
        var sampleData = new QuestionnairePdfGenerator.QuestionnaireData
        {
            Title = "2024用户满意度调查问卷",
            // 假设Logo放在项目wwwroot目录下
            LogoPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "company-logo.png"),
            Questions = new List<QuestionnairePdfGenerator.QuestionAnswerPair>
            {
                new() { Question = "您对产品操作便捷性打几分?", Answer = "9分" },
                new() { Question = "您最常用的产品功能是?", Answer = "数据可视化" },
                new() { Question = "您希望产品新增什么功能?", Answer = "批量导出数据" }
            }
        };

        var generator = new QuestionnairePdfGenerator();
        var pdfBytes = generator.GenerateQuestionnairePdf(sampleData);

        // 返回PDF文件,指定文件名和MIME类型
        return File(pdfBytes, "application/pdf", "问卷结果_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
    }

    // POST接口:接收自定义问卷数据生成PDF
    [HttpPost("custom-questionnaire")]
    public IActionResult GenerateCustomQuestionnaire([FromBody] QuestionnairePdfGenerator.QuestionnaireData data)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        var generator = new QuestionnairePdfGenerator();
        var pdfBytes = generator.GenerateQuestionnairePdf(data);

        return File(pdfBytes, "application/pdf", "自定义问卷结果.pdf");
    }
}

4. 关键注意事项

  • Logo路径处理:Web API中建议将静态资源(如Logo)放在wwwroot目录,用Directory.GetCurrentDirectory()拼接绝对路径,避免环境差异导致的路径错误。
  • 依赖注入优化:如果需要多次调用生成器,可在Program.cs中注册为服务:builder.Services.AddScoped<QuestionnairePdfGenerator>(),再通过控制器构造函数注入使用。
  • 性能优化:若生成大体积PDF,可改用GeneratePdf(stream)方法直接写入流,减少内存占用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:22:55