iTextSharp生成PDF文件

时间:2022-09-24 02:54:09

这是一篇简单的教程,所以只涉及一些iTextSharp生成pdf的简单应用,详细教程请搜索iTextSharp进入官网看官方文档(英文版)。

iTextSharp官方文档:https://itextpdf.com/sites/default/files/2019-10/DITO%20Whitepaper%20v12-2_1.pdf

Demo下载地址(附iTextSharp.dll文件):https://download.csdn.net/download/callmejeans/12068398

Demo主要代码如下:

 protected void ExportPDF(object sender, EventArgs e) {
DataTable PDFDataTable = GetDataTable();
PDFObj pdf = new PDFObj();
pdf.PDFRemark = DateTime.Now.ToShortDateString();
ConvertGrdiViewToPdf(PDFDataTable, pdf); } //初始值设定
class PDFObj{
//string fondpath = "C:\\Windows\\Fonts\\simsun.ttc,0";
public string fondpath = @System.Web.HttpContext.Current.Server.MapPath("./Source/Fonts/simsun.ttc") + ",0";//字体设置
public string PDFFilename = "TheSearchData";//文件标题
public float fontsize = ;//主要内容字体大小
public string PDFHeader = "员工信息表";//标题文字
public float PDFHeaderFontSize = ;//标题字体大小
public string PDFRemark;//备注文字
public float PDFRemarkFontSize = ;//备注文字大小
} //得到数据表
private DataTable GetDataTable(){
//新建PDFDemo DataTable
DataTable dt=new DataTable("PDFDemo");
DataColumn dc1=new DataColumn("UserID",Type.GetType("System.String"));
DataColumn dc2=new DataColumn("UserName",Type.GetType("System.String"));
DataColumn dc3=new DataColumn("Sex",Type.GetType("System.String"));
DataColumn dc4=new DataColumn("Birth",Type.GetType("System.DateTime"));
DataColumn dc5=new DataColumn("Nation",Type.GetType("System.String"));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
dt.Columns.Add(dc5);
for(int i=;i<;i++)
{
DataRow dr=dt.NewRow();
dr["UserID"]="No"+(+i).ToString();
dr["UserName"]="张三"+i;
dr["Sex"]="男";
dr["Birth"] = System.DateTime.Now.ToString("yyyy-MM-dd");
dr["Nation"]="China";
dt.Rows.Add(dr);
}
return dt;
} #region convertToPDF
/// <summary>
/// Demo1
/// </summary>
/// <param name="sourcedate"></param>
/// <param name="PDFFileName"></param>
/// <param name="FontPath"></param>
/// <param name="FontSize"></param>
/// <param name="PDFObj"></param>
private static void ConvertGrdiViewToPdf(DataTable sourcedate, PDFObj PDFObj)
{
if (sourcedate != null)
{
string strFileName = PDFObj.PDFFilename + ".pdf";
DataTable dtrn = new DataTable();
int countColumns = sourcedate.Columns.Count;
int countRows = sourcedate.Rows.Count;
if (countColumns != && countRows != )
{
Document document = new Document(PageSize.A4, , , , );
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath(strFileName), FileMode.Create));
try
{
BaseFont baseFont = BaseFont.CreateFont(PDFObj.fondpath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, PDFObj.fontsize);
document.Open();
writer.Open();
//添加表名
if (PDFObj.PDFHeader != null)
{
iTextSharp.text.Font headfont = new iTextSharp.text.Font(baseFont, PDFObj.PDFHeaderFontSize, Font.BOLD | Font.UNDERLINE, new iTextSharp.text.BaseColor(, , ));
Paragraph head = new Paragraph(PDFObj.PDFHeader, headfont);
head.SpacingAfter = ;//设置段后距离
head.Alignment = iTextSharp.text.Rectangle.ALIGN_CENTER;
document.Add(head);
}
//添加备注
if (PDFObj.PDFRemark != null)
{
iTextSharp.text.Font Remarkfont = new iTextSharp.text.Font(baseFont, PDFObj.PDFRemarkFontSize);
Paragraph Remark = new Paragraph(PDFObj.PDFRemark, Remarkfont);
Remark.SpacingAfter = ;//设置段后距离
Remark.IndentationRight = ;//设置右缩进
Remark.Alignment = iTextSharp.text.Rectangle.ALIGN_RIGHT;
document.Add(Remark); }
PdfPTable table = new PdfPTable(countColumns);
table.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY;
for (int j = ; j < countColumns; j++)
{
table.AddCell(new Phrase(sourcedate.Columns[j].ColumnName, font)); // OK
}
table.HeaderRows = ; table.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
for (int i = ; i < countRows; i++)
{
for (int j = ; j < countColumns; j++)
{
table.AddCell(new Phrase((sourcedate.Rows[i][j].ToString() == null || sourcedate.Rows[i][j].ToString() == "&nbsp;") ? "" : sourcedate.Rows[i][j].ToString(), font));
}
}
document.Add(table);
}
catch (Exception)
{
throw;
}
finally
{
document.Close();
writer.Close();
}
try
{
String FullFileName = System.Web.HttpContext.Current.Server.MapPath(strFileName);
FileInfo DownloadFile = new FileInfo(FullFileName);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ClearHeaders();
System.Web.HttpContext.Current.Response.Buffer = false;
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename="
+ System.Web.HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));
System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
}
catch (Exception)
{
throw;
}
finally
{
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}
}
else
{
System.Web.HttpContext.Current.Response.Write
("<script type='text/javascript'>alert('数据为空,不值得导出pdf!');</script>");
}
}
else
{
System.Web.HttpContext.Current.Response.Write
("<script type='text/javascript'>alert('数据为空,请查询后再导出!');</script>");
}
}