最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#生成動(dòng)態(tài)pdf文件的實(shí)現(xiàn)示例

 更新時(shí)間:2026年01月09日 09:24:46   作者:#清詞#  
本文介紹了使用.NET平臺(tái)下的iTextSharp程序包動(dòng)態(tài)生成并提供下載PDF文件,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

一、使用場(chǎng)景

我們不難發(fā)現(xiàn),在實(shí)際生活中,PDF文件的使用無(wú)處不在。比如說(shuō)考試結(jié)束查分渠道公布了,下載的成績(jī)單;開(kāi)具了發(fā)票了,下載的發(fā)票文件;考試前登錄報(bào)考系統(tǒng)下載的準(zhǔn)考證;黨政機(jī)關(guān)撰寫(xiě)的公文等等,諸如此類(lèi)的文件都是用PDF文件形式保存的。

PDF文件保存不會(huì)丟失源格式,不易于直接篡改信息等優(yōu)點(diǎn),在日常中的使用非常普遍。
今天讓我們?cè)谶@里,使用.NET平臺(tái)下的iTextSharp程序包,動(dòng)態(tài)生成寫(xiě)入一個(gè)PDF文件,回傳到前端提供下載 。

二、操作流程

1.安裝iTextSharpNuGet程序包:右擊項(xiàng)目選項(xiàng),點(diǎn)擊管理NuGet程序包,搜索iTextSharp,選擇合適的版本安裝上;

2.后端C#代碼的編寫(xiě):引入iTextSharp庫(kù),使用.ashx一般處理程序響應(yīng)前端的請(qǐng)求,在指定的物理路徑中生成成績(jī)單pdf文件,并寫(xiě)入信息;

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>
    /// 建立前端適配的映射類(lèi)
    /// </summary>
    class ReqParams
    {
        public string type { get; set; }
        public int payload { get; set; }
    }

    /// <summary>
    /// Handler1 的摘要說(shuō)明
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //創(chuàng)建序列化工具
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            //獲取前端提交的JSON字符串
            string jsonString = context.Request.Form["param"].ToString();
            //反序列化映射JSON字符串
            ReqParams req = serializer.Deserialize<ReqParams>(jsonString);
            //需要返回前端的狀態(tài)
            object state = null;
            switch (req.type)
            {
                case "init":
                    state = new
                    {
                        time = DateTime.Now.ToLongTimeString(),
                        result=req.payload+1,
                    };
                    break;
                case "uploadFile":
                    //有文件上傳負(fù)載到Request中,才下一步操作
                    if (context.Request.Files.Count > 0)
                    {
                        HttpPostedFile file = context.Request.Files["file"];
                        //制定文件保存路徑
                        string savePath = context.Server.MapPath("~/Content/images/") + file.FileName;
                        try
                        {
                            //保存文件,記錄狀態(tài)信息
                            file.SaveAs(savePath);
                            state = new
                            {
                                time = DateTime.Now.ToLongTimeString(),
                                result = "上傳成功",
                                payload = req.payload + 1,
                                url = "/Content/images/" + file.FileName,
                            };
                        }
                        catch(Exception e)
                        {
                            //保存失敗,拋出錯(cuò)誤信息
                            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";
            //創(chuàng)建pdf文檔、pdf寫(xiě)入器
            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();
            //建立表格對(duì)象
            PdfPTable table = new PdfPTable(3 + 3 + 3);
            //添加表格的單元格數(shù)據(jù)
            table.AddCell(new PdfPCell(new Phrase("姓名", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("班級(jí)", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("準(zhǔn)考證", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("語(yǔ)文", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("數(shù)學(xué)", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("英語(yǔ)", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("體育", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("美術(shù)", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("勞動(dòng)", chineseFont)));
            //也可以添加表格的行
            PdfPRow row = new PdfPRow(new PdfPCell[]
            {
                new PdfPCell(new Phrase("李明",chineseFont)),
                new PdfPCell(new Phrase("一年級(jí)二班",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.前端接口的調(diào)用:以下載成績(jī)單為例,點(diǎn)擊下載成績(jī)單按鈕即可查看并下載成績(jī)單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()">下載成績(jī)單</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("成績(jī)單已經(jīng)生成,是否打開(kāi)文件?")){
                        window.location.href = data.url
                    }
                }else{
                    alert("下載失敗!")
                }
            }
        })
       
    }

</script>

運(yùn)行可查看結(jié)果:

點(diǎn)擊確定后出現(xiàn)了寫(xiě)入的成績(jī)單pdf文件

三、注意事項(xiàng)

1.iTextSharp需要和.NET框架兼容,才能正常安裝使用。安裝前,可鼠標(biāo)右擊項(xiàng)目選項(xiàng)卡,查看項(xiàng)目框架版本;

2.文件流操作非常容易出現(xiàn)異常,例如打開(kāi)pdf文件寫(xiě)入單元格、行的時(shí)候,需要適當(dāng)?shù)禺惓L幚恚?/p>

            try
            {
                pdf.Open();
                //建立表格對(duì)象
                PdfPTable table = new PdfPTable(3 + 3 + 3);
                //添加表格的單元格數(shù)據(jù)
                table.AddCell(new PdfPCell(new Phrase("姓名", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("班級(jí)", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("準(zhǔn)考證", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("語(yǔ)文", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("數(shù)學(xué)", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("英語(yǔ)", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("體育", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("美術(shù)", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("勞動(dòng)", chineseFont)));
                //也可以添加表格的行
                PdfPRow row = new PdfPRow(new PdfPCell[]
                {
                new PdfPCell(new Phrase("李明",chineseFont)),
                new PdfPCell(new Phrase("一年級(jí)二班",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文件寫(xiě)入呈現(xiàn),必須制定中文字體(若沒(méi)有創(chuàng)建支持中文的字體傳入創(chuàng)建單元格的參數(shù)中,則中文寫(xiě)入后無(wú)法顯示);

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

到此這篇關(guān)于C#生成動(dòng)態(tài)pdf文件的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)C#生成動(dòng)態(tài)pdf文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

九龙坡区| 林周县| 杭锦后旗| 南华县| 张家界市| 吉木乃县| 惠东县| 新竹县| 安化县| 娄烦县| 阳原县| 山西省| 玛沁县| 奉节县| 禄丰县| 湖南省| 漠河县| 黔南| 科尔| 曲阳县| 中卫市| 罗定市| 卓尼县| 卢龙县| 家居| 荆门市| 灯塔市| 元阳县| 德州市| 固始县| 格尔木市| 抚松县| 浠水县| 大城县| 社旗县| 文山县| 万荣县| 吉林省| 绩溪县| 加查县| 晋宁县|