C#生成動態(tài)pdf文件的實現(xiàn)示例
一、使用場景
我們不難發(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)文章
使用策略模式實現(xiàn)報警服務(wù)示例詳解(短信報警)
服務(wù)的功能:這個服務(wù)就是能夠?qū)崿F(xiàn)多通路報警的服務(wù),比如郵件報警、客戶端報警、短信報警等,該服務(wù)靈活性還不錯,比較方便擴展2014-01-01
混合語言編程—C#使用原生的Directx和OpenGL繪圖的方法
本文要說的是混合C#和C/C++語言編程,在C#的Winform和WPF下使用原生的Direct和OpenGL進行繪圖2013-09-09
Ruby創(chuàng)建數(shù)組方法總結(jié)
在本篇文章里小編給大家分享了關(guān)于Ruby創(chuàng)建數(shù)組方法的知識點內(nèi)容,對戲有興趣的朋友們學習下。2019-01-01
C# 使用動態(tài)庫DllImport("kernel32")讀寫ini文件的步驟
kernel32.dll是Windows中非常重要的32位動態(tài)鏈接庫文件,屬于內(nèi)核級文件,這篇文章主要介紹了C# 利用動態(tài)庫DllImport("kernel32")讀寫ini文件,需要的朋友可以參考下2023-05-05
C#使用Spire.Doc for .NET獲取并替換Word文檔中的字體
在企業(yè)文檔處理流程中,C# Word 字體替換需求頻繁出現(xiàn),手動查找并替換 Word 文檔字體,不僅耗費時間,還易遺漏,Spire.Doc for .NET 作為專業(yè)庫,提供查找并替換字體功能,支持自動化批量操作,本文基于 Spire.Doc,分享精確 C# 代碼,實現(xiàn)字體標準化,需要的朋友可以參考下2026-03-03
c#使用微信接口開發(fā)微信門戶應(yīng)用中微信消息的處理和應(yīng)答
這篇文章主要介紹了c#使用微信接口開發(fā)微信門戶中的微信消息的處理和應(yīng)答的過程,需要的朋友可以參考下2014-03-03

