iTextSharp 导出 PDF 文件
引用DLL
using iTextSharp.text;
using iTextSharp.text.pdf;
创建表格PDF
private void CreateTablePdf(string fileName, string filePath, DataTable dt_tooling, string start, string end, string sType) { //绝对路径创建PDF文件 FileStream fs = new FileStream(filePath, FileMode.Create); //自定义宽高 //Rectangle rec = new Rectangle(2000, 800); //每页宽高 A4纸横屏宽高 会按此高度自动分页 float w = PageSize.A4.Rotate().Width; float h = PageSize.A4.Rotate().Height; Rectangle rec = new Rectangle(0, 0, w, h); //Rectangle rec = PageSize.A4.Rotate(); //初始化文档 边距均为 0 Document document = new Document(rec, 0f, 0f, 0f, 0f); PdfWriter pdfwriter = PdfWriter.GetInstance(document, fs); document.Open(); var colCount = 27; var leftCount = 20; var rightCount = 7; PdfPTable pdftable = new PdfPTable(colCount); pdftable.HorizontalAlignment = 1; //设置列宽 float[] cellwidth = {7f, 4.5f, 12f, 12f, 4.6f, 4.6f, 4.6f, 4.6f, 4.6f, 4.8f, 4.8f, 5.8f , 4.5f, 4.5f, 4.5f, 4.5f, 5.8f , 4.5f, 4.5f, 4.5f, 4.5f, 5.8f , 4.5f, 4.5f, 4.5f, 4.5f, 5.8f }; pdftable.SetWidths(cellwidth); //设置前4行作为每页的表头,每页重复 pdftable.HeaderRows = 4; //添加表头 //定义字体 Font pdffont_i = FontFactory.GetFont("Times New Roman", 14, Font.ITALIC); Font pdffont_b = FontFactory.GetFont("Arial", 22, Font.BOLD); //中文字体 string fontpath = "C:\\WINDOWS\\FONTS\\msyh.ttf"; if (!File.Exists(fontpath)) { fontpath = "C:\\WINDOWS\\FONTS\\SIMYOU.TTF"; } BaseFont baseFont = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font pdffont_ct = new iTextSharp.text.Font(baseFont, 14); Font pdffont_cb = new iTextSharp.text.Font(baseFont, 8); Font pdffont_c = new iTextSharp.text.Font(baseFont, 7); Font pdffont = FontFactory.GetFont("Arial", 6); //摘要信息 + 表头 BuildTableHeader(start, end, sType, colCount, leftCount, rightCount, pdftable, pdffont_ct, pdffont_cb, pdffont_c); //写入数据 for (int i = 0; i < dt_tooling.Rows.Count; i++) { foreach (DataColumn item in dt_tooling.Columns) { var use_font = pdffont; if (item.ColumnName == "工程" || item.ColumnName == "部位" || item.ColumnName == "标号") { use_font = pdffont_c; } var cellData = dt_tooling.Rows[i][item.ColumnName].ToString(); if (string.IsNullOrEmpty(cellData)) { cellData = "/"; } PdfPCell cell = new PdfPCell(new Phrase(cellData, use_font)); cell.HorizontalAlignment = 1; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 4f; pdftable.AddCell(cell); } } document.Add(pdftable); document.Close(); //pdf 下载 //FileStream filestream = new FileStream(HttpContext.Current.Server.MapPath(savePath), FileMode.Open); //long filesize = filestream.Length; //var bytes = new byte[(int)filesize]; //filestream.Read(bytes, 0, bytes.Length); //filestream.Close(); ////删除生成的文件 //File.Delete(HttpContext.Current.Server.MapPath(savePath)); //HttpContext.Current.Response.ContentType = "application/octet-stream"; //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(pdfName, System.Text.Encoding.UTF8)); //HttpContext.Current.Response.AddHeader("Content-Length", filesize.ToString()); //HttpContext.Current.Response.BinaryWrite(bytes); //HttpContext.Current.Response.Flush(); //HttpContext.Current.Response.End(); //HttpContext.Current.Response.Close(); } private static void BuildTableHeader(string start, string end, string sType, int colCount, int leftCount, int rightCount, PdfPTable pdftable, iTextSharp.text.Font pdffont_ct, iTextSharp.text.Font pdffont_cb, iTextSharp.text.Font pdffont_c) { PdfPCell cell = new PdfPCell(new Phrase(("混凝土试件抗压记录"), pdffont_ct)); cell.Colspan = colCount; cell.Padding = 5f; cell.Border = 0; cell.BackgroundColor = new BaseColor(0xFF, 0xFA, 0xCD); cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; pdftable.AddCell(cell); cell = new PdfPCell(new Phrase("起始时间:" + start + ",截止时间:" + end + ",类型:" + sType + "\n", pdffont_cb)); cell.Colspan = leftCount; cell.FixedHeight = 16f; cell.PaddingLeft = 6f; cell.Border = 0; cell.BackgroundColor = new BaseColor(0xFF, 0xFA, 0xCD); cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT; pdftable.AddCell(cell); cell = new PdfPCell(new Phrase("导出时间: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n", pdffont_cb)); cell.Colspan = rightCount; cell.FixedHeight = 16f; cell.Border = 0; cell.BackgroundColor = new BaseColor(0xFF, 0xFA, 0xCD); cell.HorizontalAlignment = 1; pdftable.AddCell(cell); List<string> tooling_header = new List<string>(); string[] arrMain = { "编号", "成型日期", "工程", "部位", "标号", "水", "水泥", "矿粉", "煤灰", "砂", "石", "减水剂" }; tooling_header.AddRange(arrMain); string[] arrInsp = { "试压日期", "强度值", "3d/Mpa", "试压日期", "强度值", "7d/Mpa", "试压日期", "强度值", "28d/Mpa" }; string[] arrInsp1 = { "1", "2", "3", "强度", "1", "2", "3", "强度", "1", "2", "3", "强度" }; tooling_header.AddRange(arrInsp); tooling_header.AddRange(arrInsp1); for (int i = 0; i < tooling_header.Count; i++) { string col = tooling_header[i]; cell = new PdfPCell(new Phrase(col, pdffont_c)); if (col == "强度值") { cell.Colspan = 3; } else if (col == "1" || col == "2" || col == "3" || col == "强度" || col.Contains("Mpa")) { } else { cell.Rowspan = 2; } cell.HorizontalAlignment = 1; cell.VerticalAlignment = Element.ALIGN_MIDDLE; cell.BackgroundColor = new BaseColor(0xC0, 0xC0, 0xC0); pdftable.AddCell(cell); } }
添加文档信息
/// <summary> /// 设置页面大小、作者、标题等相关信息设置 /// </summary> private void CreatePdfSetInfo() { string fileName = string.Empty; //设置页面大小 iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(216f, 716f); pageSize.BackgroundColor = new iTextSharp.text.BaseColor(0xFF, 0xFF, 0xDE); //设置边界 Document document = new Document(pageSize, 36f, 72f, 108f, 180f); PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create)); // 添加文档信息 document.AddTitle("压试块"); document.AddSubject("Demo of PDFInfo"); document.AddKeywords("Info, PDF, Demo"); document.AddCreator("SetPdfInfoDemo"); document.AddAuthor("同之杰"); document.Open(); // 添加文档内容 for (int i = 0; i < 5; i++) { document.Add(new iTextSharp.text.Paragraph("Hello World! Hello People! " + "Hello Sky! Hello Sun! Hello Moon! Hello Stars!")); } document.Close(); }
空白换行
//设置一个空白换行 float normalLineHeight = 25f; Paragraph pBlank = new Paragraph(" ", normalFont); pBlank.Leading = normalLineHeight; document.Add(pBlank);
模板应用
public void AAA() { string filename = DateTime.Now.ToString("yyyyMMddHHmmss").ToString() + ".pdf"; var filePath = WebAppSettings.ErpUploadRootPath + "\\BizImages\\YaliJi\\" + filename; float w = PageSize.A4.Width; float h = PageSize.A4.Height; Rectangle rect = new Rectangle(0, 0, w, 3 * h); Document document = new Document(rect); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); Rectangle crop = new Rectangle(0, 2 * h, w, 3 * h); writer.CropBoxSize = crop; document.Open(); PdfContentByte content = writer.DirectContent; PdfTemplate template = content.CreateTemplate(rect.Width, rect.Height); template.SaveState(); template.SetColorFill(new BaseColor(0xFF, 0xFA, 0xCD)); template.Rectangle(0, 0, w, h); template.FillStroke(); template.RestoreState(); template.SaveState(); template.SetColorFill(new BaseColor(0xFF, 0xFA, 0xCD)); template.Rectangle(0, h, w, h); template.FillStroke(); template.RestoreState(); template.SaveState(); template.SetColorFill(new BaseColor(0xFF, 0xFA, 0xCD)); template.Rectangle(0, 2 * h, w, h / 2); template.FillStroke(); template.RestoreState(); content.AddTemplate(template, 1, 0, 0, -1, 0, rect.Height); crop = new Rectangle(0, h, w, 2 * h); writer.CropBoxSize = crop; document.NewPage(); content.AddTemplate(template, 1, 0, 0, -1, 0, rect.Height); crop = new Rectangle(0, 0, w, h); writer.CropBoxSize = crop; document.NewPage(); content.AddTemplate(template, 1, 0, 0, -1, 0, rect.Height); document.Close(); }
基础应用 :ITextSharp使用说明
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律