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

 更新时间:2026年01月09日 09:24:46   作者:#清词#  
本文介绍了使用.NET平台下的iTextSharp程序包动态生成并提供下载PDF文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、使用场景

我们不难发现,在实际生活中,PDF文件的使用无处不在。比如说考试结束查分渠道公布了,下载的成绩单;开具了发票了,下载的发票文件;考试前登录报考系统下载的准考证;党政机关撰写的公文等等,诸如此类的文件都是用PDF文件形式保存的。

PDF文件保存不会丢失源格式,不易于直接篡改信息等优点,在日常中的使用非常普遍。
今天让我们在这里,使用.NET平台下的iTextSharp程序包,动态生成写入一个PDF文件,回传到前端提供下载 。

二、操作流程

1.安装iTextSharpNuGet程序包:右击项目选项,点击管理NuGet程序包,搜索iTextSharp,选择合适的版本安装上;

2.后端C#代码的编写:引入iTextSharp库,使用.ashx一般处理程序响应前端的请求,在指定的物理路径中生成成绩单pdf文件,并写入信息;

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
{
    /// <summary>
    /// 建立前端适配的映射类
    /// </summary>
    class ReqParams
    {
        public string type { get; set; }
        public int payload { get; set; }
    }

    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    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<ReqParams>(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 > 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;
            }
        }
    }
}

3.前端接口的调用:以下载成绩单为例,点击下载成绩单按钮即可查看并下载成绩单pdf文件;

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="MySolution1.WebForm3" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>使用C#生成pdf</title>
    <script src="Scripts/jquery-1.10.2.min.js"></script>
</head>
<body>
    <div>
        <button onclick="downloadPDF()">下载成绩单</button>
    </div>
</body>
</html>
<script type="text/javascript">
    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=>{
                const data = JSON.parse(res)
                if (data.success) {
                    if(confirm("成绩单已经生成,是否打开文件?")){
                        window.location.href = data.url
                    }
                }else{
                    alert("下载失败!")
                }
            }
        })
       
    }

</script>

运行可查看结果:

点击确定后出现了写入的成绩单pdf文件

三、注意事项

1.iTextSharp需要和.NET框架兼容,才能正常安装使用。安装前,可鼠标右击项目选项卡,查看项目框架版本;

2.文件流操作非常容易出现异常,例如打开pdf文件写入单元格、行的时候,需要适当地异常处理;

            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();
            }
            

3.若需中文字体需要在pdf文件写入呈现,必须制定中文字体(若没有创建支持中文的字体传入创建单元格的参数中,则中文写入后无法显示);

            // 指定中文字体(如微软雅黑)
            string fontPath = @"C:\Windows\Fonts\msyh.ttc,0"; // 微软雅黑
            BaseFont baseFont = BaseFont.CreateFont(fontPath,
            BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font chineseFont = new Font(baseFont, 8);

到此这篇关于C#生成动态pdf文件的实现示例的文章就介绍到这了,更多相关C#生成动态pdf文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论