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

如何使用C#基于Telerik trdp模板和JSON数据生成PDF文件

C#控制台基于Telerik Reporting实现TRDP模板转PDF(绑定JSON数据)教程

1. 前置准备

  • 安装所需NuGet包:Telerik.Reporting、Telerik.Reporting.PdfRenderer、Telerik.Reporting.JsonDataSource,注意包版本必须和你制作TRDP模板使用的Telerik Reporting版本一致,避免兼容性错误。
  • 将准备好的.trdp模板文件、JSON数据文件放入项目目录,右键两个文件选择「属性」,将「复制到输出目录」设置为「如果较新则复制」,避免运行时找不到文件。
  • 提前确认TRDP模板中定义的字段名和JSON数据里的字段名完全匹配,模板内绑定字段格式为Fields.字段名。

2. 核心实现代码

using System.IO;
using Telerik.Reporting;
using Telerik.Reporting.Processing;

namespace TelerikReportDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1. 读取TRDP模板文件
            var reportPackager = new ReportPackager();
            Report report;
            using (var trdpStream = File.OpenRead("template.trdp"))
            {
                report = (Report)reportPackager.UnpackageDocument(trdpStream);
            }

            // 2. 加载JSON数据
            string jsonContent = File.ReadAllText("data.json");
            var jsonDataSource = new Telerik.Reporting.JsonDataSource
            {
                Source = jsonContent
                // 若JSON有嵌套层级需指定根节点,取消注释下行填写对应路径即可:Select = "$.Data"
            };

            // 3. 替换模板数据源,此处名称需和模板内预先定义的数据源名称完全一致
            report.DataSources["模板内的数据源名称"] = jsonDataSource;

            // 4. 渲染为PDF
            var reportSource = new InstanceReportSource { ReportDocument = report };
            var reportProcessor = new ReportProcessor();
            var deviceInfo = new System.Collections.Hashtable();
            var renderingResult = reportProcessor.RenderReport("PDF", reportSource, deviceInfo);

            // 5. 保存输出PDF
            if (renderingResult.HasErrors)
            {
                foreach (var error in renderingResult.Errors)
                {
                    System.Console.WriteLine($"渲染报错:{error.Message}");
                }
                return;
            }
            using (var fs = new FileStream("output.pdf", FileMode.Create))
            {
                fs.Write(renderingResult.DocumentBytes, 0, renderingResult.DocumentBytes.Length);
            }
        }
    }
}

3. 常见问题规避

  • 若JSON数据有嵌套层级,绑定字段时需要写全层级,比如Fields.User.BaseInfo.Name。
  • 项目平台目标不要选择Any CPU,需根据你的运行环境指定x64或x86,否则可能出现PDF渲染失败的问题。
  • 试用版Telerik Reporting生成的PDF会自带试用水印,激活正版许可后水印会自动消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:36:06