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

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

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

一、使用場景

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

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

二、操作流程

1.安裝iTextSharpNuGet程序包:右擊項目選項,點擊管理NuGet程序包,搜索iTextSharp,選擇合適的版本安裝上;

2.后端C#代碼的編寫:引入iTextSharp庫,使用.ashx一般處理程序響應(yīng)前端的請求,在指定的物理路徑中生成成績單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)
        {
            //創(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":
                    //有文件上傳負載到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)
                        {
                            //保存失敗,拋出錯誤信息
                            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寫入器
            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);
            //添加表格的單元格數(shù)據(jù)
            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("數(shù)學", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("英語", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("體育", chineseFont)));
            table.AddCell(new PdfPCell(new Phrase("美術(shù)", 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.前端接口的調(diào)用:以下載成績單為例,點擊下載成績單按鈕即可查看并下載成績單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("成績單已經(jīng)生成,是否打開文件?")){
                        window.location.href = data.url
                    }
                }else{
                    alert("下載失??!")
                }
            }
        })
       
    }

</script>

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

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

三、注意事項

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

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

            try
            {
                pdf.Open();
                //建立表格對象
                PdfPTable table = new PdfPTable(3 + 3 + 3);
                //添加表格的單元格數(shù)據(jù)
                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("數(shù)學", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("英語", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("體育", chineseFont)));
                table.AddCell(new PdfPCell(new Phrase("美術(shù)", 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文件寫入呈現(xiàn),必須制定中文字體(若沒有創(chuàng)建支持中文的字體傳入創(chuàng)建單元格的參數(shù)中,則中文寫入后無法顯示);

            // 指定中文字體(如微軟雅黑)
            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#生成動態(tài)pdf文件的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)C#生成動態(tài)pdf文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

沁阳市| 东辽县| 裕民县| 迁西县| 靖西县| 齐齐哈尔市| 海晏县| 张家界市| 龙口市| 区。| 驻马店市| 达孜县| 扶沟县| 绵竹市| 榆社县| 徐州市| 长汀县| 祁门县| 宜阳县| 商洛市| 临沭县| 琼海市| 雅江县| 北海市| 湘潭县| 内黄县| 温州市| 东乌珠穆沁旗| 桦川县| 广德县| 鄂托克旗| 清苑县| 珲春市| 连城县| 清河县| 那曲县| 饶平县| 巴东县| 龙泉市| 巴林右旗| 习水县|