C#.NET iTextSharp生成PDF文件源码大全(生成表格、透明水印,页脚页眉页码等)


  C#.NET iTextSharp生成PDF文件源码大全(生成表格、透明水印,页脚页眉页码等)


贴图图片-自动创建PDF


测试 iTextSharp 生成PDF文件:

C# Code:

string fileName = string.Format("{0}.pdf", DateTime.Now.ToString("yyyyMMddHHmmss"));
string filePath = AppDomain.CurrentDomain.BaseDirectory + "Template\\" + fileName;

string str = CSFrameworkPDF.GetInstance().GeneratePDF(filePath);

//来源:C/S框架网 | www.csframework.com | QQ:23404761





iTextSharp 生成PDF文件:


C# Code:


/// <summary>
/// 生成PDF文件
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public string GeneratePDF(string filePath)
{
  
try
  {
    
//A4纸尺寸:595*420,单位:磅
    
//doc = new Document(PageSize.A4);//默认边距,36磅
    
_doc = new Document(PageSize.A5, 36, 36, 36, 36);
    
    
//doc.SetMargins(0, 0, 0, 0);//移除页边距
    

    FileStream fs
= new FileStream(filePath, FileMode.Create);
    PdfWriter writer
= PdfWriter.GetInstance(_doc, fs);
    writer.CloseStream
= false;//把doc内容写入流中
    

    _doc.Open();
    
    
//创建页眉+图片+下划线
    
CreatePageHeader();
    
    _doc.AddTitle(
"生成PDF文件");
    _doc.AddSubject(
"生成PDF文件");
    _doc.AddKeywords(
"生成PDF文件");
    _doc.AddCreator(
"www.csframework.com|C/S框架网");
    _doc.AddAuthor(
"www.csframework.com|C/S框架网");
    
    
//中间内容
    
_doc.Add(new Paragraph("Hello World"));
    _doc.Add(
new Paragraph("标题字体:我是中国人/I'm Chinease!", fontTitle));
    _doc.Add(
new Paragraph("内容字体:我是中国人/I'm Chinease!", fontContent));
    
    
//Phrase类用法,同一行,短语拼接
    
Phrase p1 = new Phrase("/我是", fontContentUnderline);
    Phrase p2
= new Phrase("/测试", fontContent);
    Phrase p3
= new Phrase("/工程师www.csframework.com|C/S框架网", fontContentRed);
    
    _doc.Add(p1);
    _doc.Add(p2);
    _doc.Add(p3);
    
    
//Chunk类用法,下划线中英文文本
    
Chunk chunk1 = new Chunk("单行下横线文本/www.csframework.com|C/S框架网", fontContentUnderline);
    _doc.Add(
new Paragraph(chunk1));
    
    _doc.Add(
new Paragraph(" "));//添加空行
    

    CreateTable(CreateDemoData());
    
    
    
//在固定位置显示文本
    
CreateText(writer, "在固定位置显示文本111111111", new Rectangle(100, 0, 333, 300), fontContentRed);
    CreateText(writer,
"在固定位置显示文本222222222", new Rectangle(100, 0, 333, 200), fontContent);
    CreateText(writer,
"www.csframework.com|C/S框架网", new Rectangle(100, 0, 333, 100), fontContent);
    
    AddPageNumberContent(writer,
1, 1); //添加页码
    

    _doc.Close();
//关闭文档
    
    
//保存PDF文件
    
MemoryStream ms = new MemoryStream();
    
if (fs != null)
    {
      
byte[] bytes = new byte[fs.Length];//定义一个长度为fs长度的字节数组
      
fs.Read(bytes, 0, (int)fs.Length);//把fs的内容读到字节数组中
      
ms.Write(bytes, 0, bytes.Length);//把字节内容读到流中
      
fs.Flush();
      fs.Close();
    }
    
    
//设置水印
    
SetWaterMark(filePath);
  }
  
catch (DocumentException ex)
  {
    
throw new Exception(ex.Message);
  }
  
return filePath;
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761








iTextSharp 设置自定义字体


C# Code:

//中文字体-宋体
private static string fontCHN = (AppDomain.CurrentDomain.BaseDirectory + "Template\\simsun.ttf").Replace("\\", "/");
private static BaseFont bfCHN = BaseFont.CreateFont(fontdb, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

//宋体标题-深灰色
private static Font fontTitle = new Font(bfCHN, (float)10, 1, BaseColor.DARK_GRAY);

//宋体正文内容
private static Font fontContent = new Font(BaseFont.CreateFont(fontCHN, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), (float)10, 1, BaseColor.DARK_GRAY);

//宋体正文内容-下划线字体
private static Font fontContentUnderline = new Font(BaseFont.CreateFont(fontCHN, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), (float)10, 1, BaseColor.DARK_GRAY);

//宋体正文内容-红色
private static Font fontContentRed = new Font(BaseFont.CreateFont(fontCHN, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), (float)10, 1, BaseColor.RED);


//来源:C/S框架网 | www.csframework.com | QQ:23404761




iTextSharp 给PDF文件创建半透明图片水印:



C# Code:

/// <summary>
/// 设置水印
/// </summary>
/// <param name="pdfFilePath"></param>
private void SetWaterMark(string pdfFilePath)
{
  PdfReader reader
= null;
  PdfStamper stamper
= null;
  
string newPDFFileName = "";
  
  
try
  {
    reader
= new PdfReader(pdfFilePath);
    
    
string waterPDF = Path.GetDirectoryName(pdfFilePath);
    
string fileWater = Path.GetFileName(pdfFilePath).Replace(".pdf", "") + "-Stamper.pdf";
    
    newPDFFileName
= Path.Combine(waterPDF, fileWater);
    
    stamper
= new PdfStamper(reader, new FileStream(newPDFFileName, FileMode.OpenOrCreate));
    
    
string imgPath = AppDomain.CurrentDomain.BaseDirectory + "\\Template\\logo.png";
    
    iTextSharp.text.Image img
= iTextSharp.text.Image.GetInstance(imgPath);
    
    
float width = _doc.PageSize.Width;
    
float height = _doc.PageSize.Height;
    
    
float waterMarkWidth = 150;
    
    
//像素
    
float percent = waterMarkWidth / img.Width;
    img.ScaleAbsoluteWidth(waterMarkWidth);
//缩放图片指定宽度
    
img.ScaleAbsoluteHeight(img.Height * percent);//等比例缩放高度
    
img.SetAbsolutePosition((width - waterMarkWidth) / 2, (height - img.Height * percent) / 2);//设置水印位置
    
img.Rotation = 95;//旋转角度
    
    
//指定颜色透明,如:白色
    
img.Transparency = new int[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
    
    
//设置透明度
    
//create new graphics state and assign opacity
    
PdfGState graphicsState = new PdfGState();
    graphicsState.FillOpacity
= 0.2F; // (or whatever)
    
//set graphics state to pdfcontentbyte
    
PdfContentByte contentByte;
    
int j = 0;
    
int n = reader.NumberOfPages;
    
while (j < n)
    {
      j++;
      contentByte
= stamper.GetOverContent(j);
      contentByte.SetGState(graphicsState);
//设置透明度
      
contentByte.AddImage(img);
    }
  }
  
finally
  {
    
if (stamper != null) stamper.Close();
    
if (stamper != null) reader.Close();
    
    
//改名
    
if (File.Exists(newPDFFileName))
    {
      File.Delete(pdfFilePath);
      FileInfo fi
= new FileInfo(newPDFFileName);
      fi.MoveTo(pdfFilePath);
    }
  }
}



//来源:C/S框架网 | www.csframework.com | QQ:23404761



iTextSharp 创建带图片LOGO的页眉:


C# Code:

private static void CreatePageHeader()
{
  PdfPTable table
= new PdfPTable(1);//一个单元格的
  
table.TotalWidth = 350;//设置绝对宽度
  
table.LockedWidth = true;//使绝对宽度模式生效
  
table.PaddingTop = 0;
  
  PdfPCell cell
= new PdfPCell();
  Image gif
= Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + "Template\\logo.png");
  gif.ScaleAbsoluteWidth(
100);//缩放图片
  
cell.AddElement(gif);
  cell.BorderWidth
= 0f;
  cell.BorderWidthBottom
= 0.1f;//底部画线
  
cell.BorderColorBottom = BaseColor.DARK_GRAY;
  
  table.AddCell(cell);
  _doc.Add(table);
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761




iTextSharp 在固定位置输出页码:


C# Code:

/// <summary>
/// 在固定位置生成页码
/// </summary>
/// <param name="writer"></param>
/// <param name="totalPage"></param>
/// <param name="currentPage"></param>
private static void AddPageNumberContent(PdfWriter writer, int totalPage, int currentPage)
{
  
//string text = String.Format("共 {0} 页 第 {1} 页", totalPage, currentPage);
  
string text = String.Format("第 {0} 页", currentPage);
  ColumnText ct
= new ColumnText(writer.DirectContent);
  ct.SetSimpleColumn(
new Rectangle(200, 0, 533, 50));
  ct.AddElement(
new Paragraph(text, fontPageNo));
  ct.Go();
}


//来源:C/S框架网 | www.csframework.com | QQ:23404761




iTextSharp 在PDF页面固定位置输出文本



C# Code:


/// <summary>
/// 在PDF页面固定位置输出文本
/// </summary>
/// <param name="writer"></param>
/// <param name="text"></param>
/// <param name="rect"></param>
/// <param name="font"></param>
private void CreateText(PdfWriter writer, string text, Rectangle rect, Font font)
{
  
//在固定位置显示文本
  
ColumnText ct = new ColumnText(writer.DirectContent);
  ct.SetSimpleColumn(rect);
  ct.AddElement(
new Paragraph(text, font));
  ct.Go();
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761



iTextSharp 在PDF生成表格


C# Code:


/// <summary>
/// 在PDF生成表格
/// </summary>
private void CreateTable(DataTable dt)
{
  iTextSharp.text.pdf.PdfPTable datatable
= new PdfPTable(6);
  
float[] headerwidths = { 50, 100, 40, 40, 100, 80 };
  datatable.SetWidths(headerwidths);
  datatable.WidthPercentage
= 100;
  datatable.HeaderRows
= 1;
  datatable.PaddingTop
= 5;
  
  
for (int i = 0; i <= dt.Columns.Count - 1; i++)
  {
    Phrase ph
= new Phrase(dt.Columns[i].ColumnName, fontContent);
    iTextSharp.text.pdf.PdfPCell cell1
= new PdfPCell(ph);
    cell1.HorizontalAlignment
= Element.ALIGN_CENTER;
    cell1.BackgroundColor
= new iTextSharp.text.BaseColor(0xC0, 0xC0, 0xC0);
    datatable.AddCell(cell1);
  }
  
  
foreach (DataRow R in dt.Rows)
  {
    datatable.AddCell(
new Phrase(R["ID"].ToString(), fontContent));
    datatable.AddCell(
new Phrase(R["Name"].ToString(), fontContent));
    datatable.AddCell(
new Phrase(R["Sex"].ToString(), fontContent));
    datatable.AddCell(
new Phrase(R["Age"].ToString(), fontContent));
    datatable.AddCell(
new Phrase(R["Phone"].ToString(), fontContent));
    datatable.AddCell(
new Phrase(R["Address"].ToString(), fontContent));
  }
  
  _doc.Add(datatable);
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761



iTextSharp Demo总结:

从代码上不难看出,普遍用到的标签大多为Document、Paragraph、Table、Cell、Chunck、Font、Element,通过这些标签大概能组合出自己想要的效果。



iTextSharp 页面尺寸度量单位:

度量单位:厘米、英寸或象素,事实上,默认的度量系统以排版单位磅为基础得出其他单位的近似值,
如1英寸=72磅,如果你想在A4页面的PDF中创建一个矩形,你需要计算以下数据: 
21 厘米 / 2.54 = 8.2677 英寸 
8.2677英寸* 72 = 595 磅 
29.7 厘米 / 2.54 = 11.6929 英寸 
11.6929英寸* 72 = 842 磅 

默认边距为36磅即半英寸。 




C/S框架网|原创精神.创造价值.打造精品

扫一扫加微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务


版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
C/S框架网
上一篇:ASP.NET WebApi框架异步实现MultipartContent方式上传文件
下一篇:ASP.NET通过HttpContext获取IP地址
评论列表

发表评论

评论内容
昵称:
关联文章

C#.NET iTextSharp生成PDF文件大全生成表格透明页眉页码
DevExpress表格打印预览及自定义页眉并绘制图片(C# Winform)
C#图片加(Generate Watermark Picture)
C#导出数据到Excel 大全
C#制作透明背景GIF动画(演示+
HTTP状态大全-System.Net.HttpStatusCode
C# 将PDF转为线性化PDF
DevExpress导出不同的格式的文件Excel文件(*.xls)|Word文件(*.doc)|PDF文件(*.pdf)
关于FastReport.Net 1.x导出PDF/XLS文件出现中文乱解决方案
C# CodeHighlighter生成的高亮着色HTML格式化
FastReport报表输出PDF中文乱输出包含字体文件
CSFramework.CodeGeneratorV6.0-生成
C#-Windows服务管理器,实现安装,卸载,启动和停止服务功能
C#.Net WCF实例详解及下载
FastReport for .Net 报表开发实例(C#下载)
C#.Net组件开发(高级篇) - 设计时在窗体设计器文件生成组件的代码
软件开发框架培训内容大全 - CSFrameworkV5.1旗舰版
Winform框架通用导入Excel文件下载
C#进程管理器(Managing .Net Process C#)
C#.Net组件开发(高级篇) - 全部下载

热门标签
.NET5 .NET6 .NET7 APP Auth-软件授权注册系统 Axios B/S B/S开发框架 Bug Bug记录 C#加密解密 C#源码 C/S CHATGPT CMS系统 CodeGenerator CSFramework.DB CSFramework.EF CSFrameworkV1学习版 CSFrameworkV2标准版 CSFrameworkV3高级版 CSFrameworkV4企业版 CSFrameworkV5旗舰版 CSFrameworkV6.0 DAL数据访问层 Database datalock DbFramework Demo教学 Demo下载 DevExpress教程 DOM EF框架 Element-UI EntityFramework ERP ES6 Excel FastReport GIT HR IDatabase IIS JavaScript LINQ MES MiniFramework MIS NavBarControl Node.JS NPM OMS ORM PaaS POS Promise API Redis SAP SEO SQL SQLConnector TMS系统 Token令牌 VS2022 VSCode VUE WCF WebApi WebApi NETCore WebApi框架 WEB开发框架 Windows服务 Winform 开发框架 Winform 开发平台 WinFramework Workflow工作流 Workflow流程引擎 版本区别 报表 踩坑日记 操作手册 代码生成器 迭代开发记录 基础资料窗体 架构设计 角色权限 开发sce 开发技巧 开发教程 开发框架 开发平台 开发指南 客户案例 快速搭站系统 快速开发平台 秘钥 密钥 权限设计 软件报价 软件测试报告 软件简介 软件开发框架 软件开发平台 软件开发文档 软件体系架构 软件下载 软著证书 三层架构 设计模式 生成代码 实用小技巧 收钱音箱 数据锁 数据同步 微信小程序 未解决问题 文档下载 喜鹊ERP 喜鹊软件 系统对接 详细设计说明书 行政区域数据库 需求分析 疑难杂症 蝇量级框架 蝇量框架 用户管理 用户开发手册 用户控件 在线支付 纸箱ERP 智能语音收款机 自定义窗体 自定义组件 自动升级程序