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

基于MigraDoc与PDFsharp NuGet包的C#多页PDF开发需求

使用C# + MigraDoc/PDFsharp 创建带页眉Logo、页脚和表格的6页PDF

准备工作

首先安装所需NuGet包:

  • 针对.NET Framework:Install-Package PDFsharp-MigraDoc-GDI
  • 针对.NET Core/.NET 5+:Install-Package PDFsharp-MigraDoc.NETCore

核心实现步骤

1. 初始化文档与页面设置

创建基础文档对象,设置页面尺寸、边距等属性,为页眉、页脚和表格预留足够空间。

为所有页面的页眉添加Logo图片,自定义尺寸与对齐方式。

3. 设置全局页脚

配置包含自动页码和版权信息的页脚,支持动态计算总页数。

4. 生成跨页表格

创建带重复表头的表格,定义列宽与单元格对齐规则,填充足量数据以生成6页内容。

完整代码示例

using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using PdfSharp.Pdf;
using System;
using System.IO;

class PdfGenerator
{
    static void Main(string[] args)
    {
        // 创建文档
        Document document = new Document();
        document.Info.Title = "6页数据报表";
        document.Info.Subject = "带页眉Logo、页脚和表格的PDF示例";

        // 设置页面格式:A4纸,边距配置
        Section section = document.AddSection();
        section.PageSetup.PageFormat = PageFormat.A4;
        section.PageSetup.LeftMargin = "2cm";
        section.PageSetup.RightMargin = "2cm";
        section.PageSetup.TopMargin = "3cm"; // 预留页眉空间
        section.PageSetup.BottomMargin = "2.5cm"; // 预留页脚空间

        // --------------------------
        // 添加页眉Logo
        // --------------------------
        HeaderFooter header = section.Headers.Primary;
        Image logo = header.AddImage(@"C:\Your\Logo\Path\logo.png"); // 替换为实际Logo路径
        logo.Width = "3cm";
        logo.Height = "1.5cm";
        logo.Format.Alignment = ParagraphAlignment.Left;
        logo.WrapFormat.Style = WrapStyle.Through;

        // --------------------------
        // 设置页脚
        // --------------------------
        HeaderFooter footer = section.Footers.Primary;
        Paragraph footerPara = footer.AddParagraph();
        footerPara.Format.Alignment = ParagraphAlignment.Center;
        footerPara.AddText("第 ");
        footerPara.AddField("Page");
        footerPara.AddText(" 页,共 ");
        footerPara.AddField("NumPages");
        footerPara.AddText(" 页");
        footerPara.AddLineBreak();
        footerPara.AddText("© 2024 你的公司名称 | 保留所有权利");
        footerPara.Format.Font.Size = 8;
        footerPara.Format.Font.Color = Colors.Gray;

        // --------------------------
        // 创建表格
        // --------------------------
        Table table = section.AddTable();
        table.Borders.Width = 0.75; // 表格边框宽度
        table.Borders.Color = Colors.Black;
        table.RepeatHeaderOnEveryPage = true; // 每页重复表头

        // 定义列宽
        table.AddColumn("2cm");
        table.AddColumn("5cm");
        table.AddColumn("4cm");
        table.AddColumn("3cm");
        table.AddColumn("3cm");

        // 添加表头行
        Row headerRow = table.AddRow();
        headerRow.HeadingFormat = true;
        headerRow.Format.Font.Bold = true;
        headerRow.Format.Font.Color = Colors.White;
        headerRow.Shading.Color = Colors.DarkBlue;

        // 配置表头单元格文本与对齐
        headerRow.Cells[0].AddParagraph("序号");
        headerRow.Cells[0].Format.Alignment = ParagraphAlignment.Center;
        headerRow.Cells[1].AddParagraph("产品名称");
        headerRow.Cells[1].Format.Alignment = ParagraphAlignment.Left;
        headerRow.Cells[2].AddParagraph("分类");
        headerRow.Cells[2].Format.Alignment = ParagraphAlignment.Left;
        headerRow.Cells[3].AddParagraph("单价");
        headerRow.Cells[3].Format.Alignment = ParagraphAlignment.Right;
        headerRow.Cells[4].AddParagraph("库存数量");
        headerRow.Cells[4].Format.Alignment = ParagraphAlignment.Right;

        // 填充120行数据(足够生成6页内容)
        for (int i = 1; i <= 120; i++)
        {
            Row dataRow = table.AddRow();
            dataRow.Cells[0].AddParagraph(i.ToString());
            dataRow.Cells[0].Format.Alignment = ParagraphAlignment.Center;
            dataRow.Cells[1].AddParagraph($"产品{i:D3}");
            dataRow.Cells[1].Format.Alignment = ParagraphAlignment.Left;
            dataRow.Cells[2].AddParagraph(i % 3 == 0 ? "电子设备" : i % 3 == 1 ? "办公用品" : "家居用品");
            dataRow.Cells[2].Format.Alignment = ParagraphAlignment.Left;
            dataRow.Cells[3].AddParagraph($"{Math.Round(new Random(i).NextDouble() * 1000 + 50, 2)} 元");
            dataRow.Cells[3].Format.Alignment = ParagraphAlignment.Right;
            dataRow.Cells[4].AddParagraph(new Random(i+100).Next(10, 500).ToString());
            dataRow.Cells[4].Format.Alignment = ParagraphAlignment.Right;

            // 隔行浅灰背景(可选优化)
            if (i % 2 == 0)
            {
                dataRow.Shading.Color = Colors.LightGray;
                dataRow.Shading.Pattern = ShadingPattern.Percent10;
            }
        }

        // --------------------------
        // 生成并保存PDF
        // --------------------------
        PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
        renderer.Document = document;
        renderer.RenderDocument();

        string outputPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "6页报表.pdf");
        renderer.PdfDocument.Save(outputPath);

        Console.WriteLine($"PDF已生成:{outputPath}");
    }
}

关键细节说明

  • Logo路径:若使用嵌入资源,可通过Assembly.GetExecutingAssembly().GetManifestResourceStream获取流后加载图片。
  • 表格分页:RepeatHeaderOnEveryPage = true确保每页顶部自动显示表头,MigraDoc会自动处理表格跨页逻辑。
  • 对齐设置:通过ParagraphAlignment分别配置表头、数据单元格的对齐方式,提升内容可读性。
  • 页脚页码:使用AddField("Page")和AddField("NumPages")动态插入当前页与总页数,无需手动计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 04:00:57