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

