夏日正午 發表於 2026-1-9 09:24:46

C#生成动态pdf文件的实现示例

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>一、使用场景</li><li>二、操作流程</li><li>三、注意事项</li></ul></div><p class="maodian"></p><h2>一、使用场景</h2>
<p>我们不难发现,在实际生活中,PDF文件的使用无处不在。比如说考试结束查分渠道公布了,下载的成绩单;开具了发票了,下载的发票文件;考试前登录报考系统下载的准考证;党政机关撰写的公文等等,诸如此类的文件都是用PDF文件形式保存的。</p>
<p>PDF文件保存不会丢失源格式,不易于直接篡改信息等优点,在日常中的使用非常普遍。<br />今天让我们在这里,使用.NET平台下的iTextSharp程序包,动态生成写入一个PDF文件,回传到前端提供下载&nbsp;。</p>
<p class="maodian"></p><h2>二、操作流程</h2>
<p>1.安装iTextSharpNuGet程序包:右击项目选项,点击管理NuGet程序包,搜索iTextSharp,选择合适的版本安装上;</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026010909213390.png" /></p>
<p>2.后端C#代码的编写:引入iTextSharp库,使用.ashx一般处理程序响应前端的请求,在指定的物理路径中生成成绩单pdf文件,并写入信息;</p>
<div class="jb51code"><pre class="brush:csharp;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace MySolution1
{
    /// &lt;summary&gt;
    /// 建立前端适配的映射类
    /// &lt;/summary&gt;
    class ReqParams
    {
      public string type { get; set; }
      public int payload { get; set; }
    }

    /// &lt;summary&gt;
    /// Handler1 的摘要说明
    /// &lt;/summary&gt;
    public class Handler1 : IHttpHandler
    {

      public void ProcessRequest(HttpContext context)
      {
            //创建序列化工具
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            //获取前端提交的JSON字符串
            string jsonString = context.Request.Form["param"].ToString();
            //反序列化映射JSON字符串
            ReqParams req = serializer.Deserialize&lt;ReqParams&gt;(jsonString);
            //需要返回前端的状态
            object state = null;
            switch (req.type)
            {
                case "init":
                  state = new
                  {
                        time = DateTime.Now.ToLongTimeString(),
                        result=req.payload+1,
                  };
                  break;
                case "uploadFile":
                  //有文件上传负载到Request中,才下一步操作
                  if (context.Request.Files.Count &gt; 0)
                  {
                        HttpPostedFile file = context.Request.Files["file"];
                        //制定文件保存路径
                        string savePath = context.Server.MapPath("~/Content/images/") + file.FileName;
                        try
                        {
                            //保存文件,记录状态信息
                            file.SaveAs(savePath);
                            state = new
                            {
                              time = DateTime.Now.ToLongTimeString(),
                              result = "上传成功",
                              payload = req.payload + 1,
                              url = "/Content/images/" + file.FileName,
                            };
                        }
                        catch(Exception e)
                        {
                            //保存失败,抛出错误信息
                            state = new
                            {
                              time = DateTime.Now.ToLongTimeString(),
                              result = "上传失败!" + e.Message.ToString(),
                              payload=-1
                            };
                        }
                  }
                  break;
                case "getScorePDF":
                  state = CreatePDF(context);
                  break;
            }
            
            context.Response.Write(serializer.Serialize(state));
      }


      object CreatePDF(HttpContext context)
      {
            Random ran = new Random(60);
            //指定pdf文件目录
            string path = context.Server.MapPath("~/Content/") + "scorePDF.pdf";
            //创建pdf文档、pdf写入器
            Document pdf = new Document(PageSize.A4, 10, 10, 40, 30);
            PdfWriter writer = PdfWriter.GetInstance(pdf, new FileStream(path, FileMode.Create));
            // 指定中文字体(如微软雅黑)
            string fontPath = @"C:\Windows\Fonts\msyh.ttc,0"; // 微软雅黑
            BaseFont baseFont = BaseFont.CreateFont(fontPath,
            BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font chineseFont = new Font(baseFont, 8);
            pdf.Open();
            //建立表格对象
            PdfPTable table = new PdfPTable(3 + 3 + 3);
            //添加表格的单元格数据
            table.AddCell(new PdfPCell(new Phrase("姓名", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("班级", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("准考证", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("语文", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("数学", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("英语", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("体育", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("美术", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("劳动", chineseFont)));
            //也可以添加表格的行
            PdfPRow row = new PdfPRow(new PdfPCell[]
            {
                new PdfPCell(new Phrase("李明",chineseFont)),
                new PdfPCell(new Phrase("一年级二班",chineseFont)),
                new PdfPCell(new Phrase("0500090901",chineseFont)),
                new PdfPCell(new Phrase(ran.Next(60,100).ToString(),chineseFont)),
                new PdfPCell(new Phrase(ran.Next(60,100).ToString(),chineseFont)),
                new PdfPCell(new Phrase(ran.Next(60,100).ToString(),chineseFont)),
                new PdfPCell(new Phrase(ran.Next(60,100).ToString(),chineseFont)),
                new PdfPCell(new Phrase(ran.Next(60,100).ToString(),chineseFont)),
                new PdfPCell(new Phrase(ran.Next(60,100).ToString(),chineseFont)),
            });
            table.Rows.Add(row);
            //把表格放入pdf文档
            pdf.Add(table);
            pdf.Close();
            return new
            {
                time = DateTime.Now.ToLongTimeString(),
                result = "操作成功!",
                url = "/Content/scorePDF.pdf",
                success = true
            };
               
      }

      public bool IsReusable
      {
            get
            {
                return false;
            }
      }
    }
}</pre></div>
<p>3.前端接口的调用:以下载成绩单为例,点击下载成绩单按钮即可查看并下载成绩单pdf文件;</p>
<div class="jb51code"><pre class="brush:csharp;">&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="MySolution1.WebForm3" %&gt;

&lt;!DOCTYPE html&gt;

&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head runat="server"&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt;
    &lt;title&gt;使用C#生成pdf&lt;/title&gt;
    &lt;script src="Scripts/jquery-1.10.2.min.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div&gt;
      &lt;button onclick="downloadPDF()"&gt;下载成绩单&lt;/button&gt;
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
&lt;script type="text/javascript"&gt;
    function downloadPDF() {
      const param = {
            "type": "getScorePDF",
            "payload":0
      }
      const formData=new FormData()
      formData.append("param", JSON.stringify(param))
      $.ajax({
            "url":"/Handler1.ashx",
            "type":"post",
            "data":formData,
            "processData":false,
            "contentType":false,
            "success":res=&gt;{
                const data = JSON.parse(res)
                if (data.success) {
                  if(confirm("成绩单已经生成,是否打开文件?")){
                        window.location.href = data.url
                  }
                }else{
                  alert("下载失败!")
                }
            }
      })
      
    }

&lt;/script&gt;</pre></div>
<p>运行可查看结果:</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026010909213377.png" /></p>
<p>点击确定后出现了写入的成绩单pdf文件</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026010909213383.png" /></p>
<p class="maodian"></p><h2>三、注意事项</h2>
<p>1.iTextSharp需要和.NET框架兼容,才能正常安装使用。安装前,可鼠标右击项目选项卡,查看项目框架版本;</p>
<p style="text-align:center"><img alt="" height="600" src="https://img.jbzj.com/file_images/article/202601/2026010909213351.jpg" width="1200" /></p>
<p>2.文件流操作非常容易出现异常,例如打开pdf文件写入单元格、行的时候,需要适当地异常处理;</p>
<div class="jb51code"><pre class="brush:csharp;">            try
            {
                pdf.Open();
                //建立表格对象
                PdfPTable table = new PdfPTable(3 + 3 + 3);
                //添加表格的单元格数据
                table.AddCell(new PdfPCell(new Phrase("姓名", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("班级", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("准考证", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("语文", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("数学", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("英语", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("体育", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("美术", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("劳动", chineseFont)));
                //也可以添加表格的行
                PdfPRow row = new PdfPRow(new PdfPCell[]
                {
                new PdfPCell(new Phrase("李明",chineseFont)),
                new PdfPCell(new Phrase("一年级二班",chineseFont)),
                new PdfPCell(new Phrase("0500090901",chineseFont)),
                new PdfPCell(new Phrase(ran.Next(60,100).ToString(),chineseFont)),
                new PdfPCell(new Phrase(ran.Next(60,100).ToString(),chineseFont)),
                new PdfPCell(new Phrase(ran.Next(60,100).ToString(),chineseFont)),
                new PdfPCell(new Phrase(ran.Next(60,100).ToString(),chineseFont)),
                new PdfPCell(new Phrase(ran.Next(60,100).ToString(),chineseFont)),
                new PdfPCell(new Phrase(ran.Next(60,100).ToString(),chineseFont)),
                });
                table.Rows.Add(row);
                //把表格放入pdf文档
                pdf.Add(table);
                return new
                {
                  time = DateTime.Now.ToLongTimeString(),
                  result = "操作成功!",
                  url = "/Content/scorePDF.pdf",
                  success = true
                };
            }
            catch(Exception e)
            {
                throw new Exception(e.Message.ToString());
            }
            finally
            {
                pdf.Close();
            }
            </pre></div>
<p>3.若需中文字体需要在pdf文件写入呈现,必须制定中文字体(若没有创建支持中文的字体传入创建单元格的参数中,则中文写入后无法显示);</p>
<div class="jb51code"><pre class="brush:csharp;">            // 指定中文字体(如微软雅黑)
            string fontPath = @"C:\Windows\Fonts\msyh.ttc,0"; // 微软雅黑
            BaseFont baseFont = BaseFont.CreateFont(fontPath,
            BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font chineseFont = new Font(baseFont, 8);</pre></div>
<p>到此这篇关于C#生成动态pdf文件的实现示例的文章就介绍到这了,更多相关C#生成动态pdf文件内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>C#实现PDF文档自动化生成的开发实战</li><li>使用C#生成二维码并插入PDF、Word与Excel文档</li><li>如何在C#中自动化生成PDF表格</li><li>在C#中生成PDF的步骤详解</li><li>C#使用iTextSharp生成PDF的示例代码</li><li>C#生成PDF的方法</li><li>C#实现的pdf生成图片文字水印类实例</li><li>C#编程简单实现生成PDF文档的方法示例</li><li>C#生成PDF文件流</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: C#生成动态pdf文件的实现示例