1,引入:iTextSharp.LGPLv2.Core

2,在使用的文件里面引入命名空间

using iTextSharp.text;
using iTextSharp.text.pdf;

3,简单的生成PDF文件,其中Fname为生成文件存放的路径。

简单说一下:
Rectangle对象是用来设置PDF页面尺寸的。
Document对象为页面对象,就像是HTML里面的页面对象一样,用于操作页面内容和格式。

PdfWriter对象是用于将Document对象写入PDF文件。

Rectangle pageSize = new Rectangle(1000, 500);
Document document = new Document(pageSize, 10, 10, 120, 80);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Fname, FileMode.Create));
document.Open();
document.Add(new iTextSharp.text.Paragraph("Hello World"));
document.Close();
writer.Close();

4.设置PDF文档信息,利用Document对象。

document.AddTitle("这里是标题");
document.AddSubject("主题");
document.AddKeywords("关键字");
document.AddCreator("创建者");
document.AddAuthor("作者");

5.向PDF里面添加图片,Fimg为图片路径,创建一个iTextSharp.text.Image对象,将该对象添加到文档里面,SetAbsolutePosition方法是设置图片出现的位置。

string imgurl = @System.Web.HttpContext.Current.Server.MapPath(Fimg);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgurl);
img.SetAbsolutePosition(0, 0);
writer.DirectContent.AddImage(img);

6.向PDF里面添加表格,表格对象为PdfTable对象,该类的构造函数可以设置表格的列数,new float[] { 180, 140, 140, 160, 180, 140, 194 }里面是每列的宽度,也可在构造函数里面直接写列数如:new PdfPTable(3);

接下来需要造单元格扔到表格里面,单元格为PdfPCell对象,构造函数里面可以写入单元格要显示的文本信息,其中fontb为字体,如果是显示中文必须创建中文字体:

BaseFont bsFont = BaseFont.CreateFont(@System.Web.HttpContext.Current.Server.MapPath("./upload/fonts/MSYH.TTC") + ",0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font fontb = new Font(bsFont, Tab_Content_FontSize, Font.BOLD, new BaseColor(0xFF, 0xFF, 0xFF));

单元格创建出来扔到表格中排列方式类似与HTML里面的流式布局,没有行一说,所以造的单元格数量和列数相挂钩才能显示正确。

单元格格式可以进行设置:

HorizontalAlignment:代表单元格内文本的对齐方式

PaddingBottom和PaddingTop:为单元格内间距(下,上)

BorderColor:边框颜色

SetLeading():该方法设置单元格内多行文本的行间距

PdfPTable tablerow1 = new PdfPTable(new float[] { 180, 140, 140, 160, 180, 140, 194 });
tablerow1.TotalWidth = 1000; //表格宽度
tablerow1.LockedWidth = true;

//造单元格

PdfPCell cell11 = new PdfPCell(new Paragraph("单元格内容", fontb));
cell11.HorizontalAlignment = 1;
cell11.PaddingBottom = 10;
cell11.PaddingTop = 10;
cell11.BorderColor = borderColor;
cell11.SetLeading(1.2f, 1.2f);
tablerow1.AddCell(cell11);//将单元格添加到表格中

document.Add(tablerow1);//将表格添加到pdf文档中
7.将文本放到页面指定位置PdfContentByte获取写入的文件流,将文本放到指定位置,位置为x和y坐标,其中y坐标是从下面往上走的。

PdfContentByte cb = writer.DirectContent;
Phrase txt = new Phrase("测试文本", fontb);
ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, txt,425, 460, 0);

8.创建新的页面,如果想要创建出新一页的话需要使用代码:

document.NewPage();
如果创建的新页面需要重新开始计算页数的话,在创建新页面之前:

document.ResetPageCount();
9.添加页眉页脚及水印,页脚需要显示页数,如果正常添加很简单,但需求里面要求有背景色,有水印,而且背景色在最底层,水印在上层,文字表格等在最上层,处理这个需求是整个iTextSharp最难的地方。

先分析一下,如果在创建Rectangle对象的时候添加背景色,那么接下来加水印有两种可选情况:

1.水印加在内容下面,可选,但水印会加到背景色的下面导致水印不显示。

2.水印加在内容上面,不可选,水印会覆盖最上层的文字,实现的效果不好。

为了解决这个问题,找到了iTextSharp提供的一个接口IPdfPageEvent及PdfPageEventHelper,该接口里面有一个方法可以实现,该方法为:OnEndPage当页面创建完成时触发执行。

那么就利用这个方法来实现:先添加背景色,再添加水印,添加在内容下方即可。

实现该方法需要一个类来实现接口:

writer.PageNumber.ToString()为页码。

public class IsHandF : PdfPageEventHelper, IPdfPageEvent
{/// <summary>/// 创建页面完成时发生/// </summary>public override void OnEndPage(PdfWriter writer, Document document){base.OnEndPage(writer, document);//页眉页脚使用字体BaseFont bsFont = BaseFont.CreateFont(@System.Web.HttpContext.Current.Server.MapPath("./upload/fonts/MSYH.TTC") + ",0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);iTextSharp.text.Font fontheader = new iTextSharp.text.Font(bsFont, 30, iTextSharp.text.Font.BOLD);iTextSharp.text.Font fontfooter = new iTextSharp.text.Font(bsFont, 20, iTextSharp.text.Font.BOLD);//水印文件地址string syurl = "./upload/images/sys/black.png";//获取文件流PdfContentByte cbs = writer.DirectContent;cbs.SetCharacterSpacing(1.3f); //设置文字显示时的字间距Phrase header = new Phrase("页眉", fontheader);Phrase footer = new Phrase(writer.PageNumber.ToString(), fontfooter);//页眉显示的位置ColumnText.ShowTextAligned(cbs, Element.ALIGN_CENTER, header,document.Right / 2, document.Top + 40, 0);//页脚显示的位置ColumnText.ShowTextAligned(cbs, Element.ALIGN_CENTER, footer,document.Right / 2, document.Bottom - 40, 0);//添加背景色及水印,在内容下方添加PdfContentByte cba = writer.DirectContentUnder;//背景色Bitmap bmp = new Bitmap(1263, 893);Graphics g = Graphics.FromImage(bmp);Color c = Color.FromArgb(0x33ff33);SolidBrush b = new SolidBrush(c);//这里修改颜色g.FillRectangle(b, 0, 0, 1263, 893);System.Drawing.Image ig = bmp;iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ig, new BaseColor(0xFF, 0xFF, 0xFF));img.SetAbsolutePosition(0, 0);cba.AddImage(img);//水印iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(@System.Web.HttpContext.Current.Server.MapPath(syurl));image.RotationDegrees = 30;//旋转角度PdfGState gs = new PdfGState();gs.FillOpacity = 0.1f;//透明度cba.SetGState(gs);int x = -1000;for (int j = 0; j < 15; j++){x = x + 180;int a = x;int y = -170;for (int i = 0; i < 10; i++){a = a + 180;y = y + 180;image.SetAbsolutePosition(a, y);cba.AddImage(image);}}}}

该类创建完成后,在需要添加页眉页脚水印的页面代码位置添加如下代码,整个文档生成过程中添加一次即可,确保该事件可以触发,添加该代码后在剩余的页面都会触发生成页眉页脚:

writer.PageEvent = new IsHandF();

例子:

/// <summary>
/// 引入
/// iTextSharp.LGPLv2.Core
/// </summary>
public class MyPdf
{private static float PageHeight = 3900f; //private static float PageWidth = 580.7f; //public static void Main2(){//设置pdf宽高iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(PageWidth, PageHeight);//生成pdfDocument document = new Document(pageSize, 5, 5, 5, 0);var fileStream = File.Create("测试5.pdf");PdfWriter pw = PdfWriter.GetInstance(document, fileStream);document.Open();document.PageCount = 2;//指定字体文件,IDENTITY_H:支持中文string fontpath = "simkai.ttf";BaseFont customfont = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);//设置字体颜色样式var baseFont = new Font(customfont){Color = new BaseColor(System.Drawing.Color.Black),  //设置字体颜色Size = 14  //字体大小};#region 写入表格、数据#region 头部//定义table行列数据PdfPTable tableRow_1 = new PdfPTable(1);  //生成只有一列的行数据tableRow_1.DefaultCell.Border = Rectangle.NO_BORDER;  //无边框tableRow_1.DefaultCell.MinimumHeight = 40f; //高度float[] headWidths_1 = new float[] { 500f }; //宽度tableRow_1.SetWidths(headWidths_1);//定义字体样式var headerStyle = new Font(customfont){Color = new BaseColor(System.Drawing.Color.Black),Size = 18,};var Row_1_Cell_1 = new PdfPCell(new Paragraph("用户列表", headerStyle));Row_1_Cell_1.HorizontalAlignment = Element.ALIGN_CENTER;//居中tableRow_1.AddCell(Row_1_Cell_1);PdfPTable tableRow_2 = new PdfPTable(5);tableRow_2.DefaultCell.Border = Rectangle.NO_BORDER;tableRow_2.DefaultCell.MinimumHeight = 40f;float[] headWidths_2 = new float[] { 80f, 100f, 80f, 100f, 140f };tableRow_2.SetWidths(headWidths_2);var Row_2_Cell_1 = new PdfPCell(new Paragraph("姓名", baseFont));tableRow_2.AddCell(Row_2_Cell_1);var Row_2_Cell_2 = new PdfPCell(new Paragraph("手机号", baseFont));tableRow_2.AddCell(Row_2_Cell_2);var Row_2_Cell_3 = new PdfPCell(new Paragraph("性别", baseFont));tableRow_2.AddCell(Row_2_Cell_3);var Row_2_Cell_4 = new PdfPCell(new Paragraph("出生日期", baseFont));tableRow_2.AddCell(Row_2_Cell_4);var Row_2_Cell_5 = new PdfPCell(new Paragraph("身份证号", baseFont));tableRow_2.AddCell(Row_2_Cell_5);document.Add(tableRow_1);document.Add(tableRow_2);#endregion#region 填充List数据var users = new List<User>(){new User{Name="旺旺",Phone ="13000000000",Gender = "男",Birthday="1900-01-01",IdCard = "111111111111111111"},new User{Name="李四",Phone ="13000000001",Gender = "男",Birthday="1900-01-01",IdCard = "111111111111111112"},new User{Name="李四",Phone ="13000000001",Gender = "男",Birthday="1900-01-01",IdCard = "111111111111111112"},new User{Name="李四",Phone ="13000000001",Gender = "男",Birthday="1900-01-01",IdCard = "111111111111111112"}};Type t = new User().GetType();//获得该类的Typefor (int i = 0; i < users.Count; i++){PdfPTable tableRow_3 = new PdfPTable(5);tableRow_3.DefaultCell.Border = Rectangle.NO_BORDER;tableRow_3.DefaultCell.MinimumHeight = 40f;float[] headWidths_3 = new float[] { 80f, 100f, 80f, 100f, 140f };tableRow_3.SetWidths(headWidths_3);foreach (PropertyInfo pi in t.GetProperties())  //遍历属性值{var value = pi.GetValue(users[i]).ToString();var txt = new Paragraph(value, baseFont);var cell = new PdfPCell(txt);tableRow_3.AddCell(cell);}document.Add(tableRow_3);}#endregion#endregion#region 写入图片//图片的高float imageheight = 300;for (int i = 0; i < 13; i++){{string path = Path.GetFullPath("image/2.jpg");Image image = Image.GetInstance(path);//原图尺寸的0.3image.ScalePercent(30f);//设置图片的宽高image.ScaleAbsolute(150f, 250f);//图片居中image.Alignment = Element.ALIGN_CENTER;//设置图片具体位置  PDF左下角为原点//出现在屏幕左下角 图片左下角做为锚点image.SetAbsolutePosition(100, PageHeight - (imageheight * i));//旋转 90度//image.RotationDegrees = 90f;document.Add(image);}{string path = Path.GetFullPath("image/3.jpg");Image image = Image.GetInstance(path);//原图尺寸的0.3image.ScalePercent(3f);//设置图片的宽高image.ScaleAbsolute(150f, 250f);//图片居中image.Alignment = Element.ALIGN_CENTER;//设置图片具体位置  PDF左下角为原点image.SetAbsolutePosition(350, PageHeight - imageheight * i);//出现在屏幕左下角 图片左下角做为锚点//旋转 90度//image.RotationDegrees = 90f;document.Add(image);}}#endregiondocument.Add(new iTextSharp.text.Paragraph("Hello World! Hello People! "));//document.AddTitle("这里是标题");//document.AddSubject("主题");//document.AddKeywords("关键字");//document.AddCreator("创建者");//document.AddAuthor("作者");PdfContentByte cb = pw.DirectContent;Phrase txt2 = new Phrase("测试文本22222222222222222222", baseFont);ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, txt2,425, 460, 0);//页脚PDFFooter footer = new PDFFooter();footer.OnEndPage(pw, document);document.Close();fileStream.Dispose();}
}public class User
{public string Name { get; set; }public string Phone { get; set; }public string Gender { get; set; }public string Birthday { get; set; }public string IdCard { get; set; }
}public class PDFFooter : PdfPageEventHelper
{// write on top of documentpublic override void OnOpenDocument(PdfWriter writer, Document document){base.OnOpenDocument(writer, document);PdfPTable tabFot = new PdfPTable(new float[] { 1F });tabFot.SpacingAfter = 10F;PdfPCell cell;tabFot.TotalWidth = 300F;cell = new PdfPCell(new Phrase("Header"));tabFot.AddCell(cell);tabFot.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent);}// write on start of each pagepublic override void OnStartPage(PdfWriter writer, Document document){base.OnStartPage(writer, document);}// write on end of each pagepublic override void OnEndPage(PdfWriter writer, Document document){base.OnEndPage(writer, document);//PdfPTable tabFot = new PdfPTable(new float[] { 1F });//tabFot.TotalWidth = 700f;//tabFot.DefaultCell.Border = 0;//  var footFont = FontFactory.GetFont("Lato", 12 * 0.667f, new BaseColor(60, 60, 60));//string fontpath = HttpContext.Current.Server.MapPath("~/App_Data");//BaseFont customfont = BaseFont.CreateFont(fontpath + "\\Lato-Regular.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);//var footFont = new Font(customfont, 12 * 0.667f, Font.NORMAL, new Color(170, 170, 170));//PdfPCell cell;//cell = new PdfPCell(new Phrase("@ 2016 . All Rights Reserved", footFont));//cell.VerticalAlignment = Element.ALIGN_CENTER;//cell.Border = 0;//cell.PaddingLeft = 100f;//tabFot.AddCell(cell);//tabFot.WriteSelectedRows(0, -1, 150, document.Bottom, writer.DirectContent);}//write on close of documentpublic override void OnCloseDocument(PdfWriter writer, Document document){base.OnCloseDocument(writer, document);}
}

NetCore 创建、编辑PDF插入表格、图片、文字相关推荐

  1. NetCore 创建、编辑PDF插入表格、图片、文字(二)

    1代码示例 /// <summary>/// 引入/// iTextSharp.LGPLv2.Core/// 部分例子/// </summary>public class My ...

  2. 【selection】 学习光标API并实现编辑区插入表情图片的功能

    目录 场景介绍 selection介绍 selection API range 介绍 range API 实现编辑区插入表情图片 参考资料 场景介绍 在写web版聊天器时,遇到一个需求: 聊天时用户可 ...

  3. PDF如何编辑,怎么编辑PDF文件中的文字

    越来越多的小伙伴会私信小编询问小编关于PDF文件的修改技巧,在使用PDF文件的时候,往往是需要用到PDF编辑器的,编辑文件时,想要修改文件的内容,应该怎么去编辑呢,其实,还是很简单的,不会的小伙伴可以 ...

  4. C# VS2012操作word文档 (二).插入表格图片

    在上一篇文章"C# VS2012创建word文档.(一)"中我们讲述了如何使用VS2012引用COM中Miscrosoft Word 14.0 Object Library实现创建 ...

  5. java poi生成word 插入表格,图片,自动合并单元格,并且可以在已存在的word上追加

    poi版本选3.10以上的 要不然插入图片 word会打不开 <dependency><groupId>org.apache.poi</groupId><ar ...

  6. 怎么把pdf中的图片文字转换成excel

    很多网友经常会问到"怎么把PDF格式文件转换成Excel.XLS格式文档"?PDF转换成Excel本不是一个技术活,利用一些小技巧和工具,其实你会发现PDF转换成Excel是很容易 ...

  7. 怎么修改和编辑PDF文件中的文字内容

    我们不论在工作和学习中都越来越多的用到PDF格式的文件,这也是令我们一个尴尬的事情.因为我们在上学的时候并没有对PDF格式的文件编辑进行过系统的学习.所以我们对于PDF编辑和修改并没有全面的了解.那难 ...

  8. c# 使用word 标签 插入多图片 文字

    c#操作word 通过替换标签 达到 使用word 模板 创建模板 保存为模板 添加引用 using msword=Microsoft.Office.Interop.Word; using Syste ...

  9. PS2021 编辑PDF文件,修改文字

    今天在看一个PDF文档的时候,想要对里面的一些内容进行修改再保存,但是又不想为此去下载一些PDF编辑器类的软件,于是干脆用PS对PDF文档进行一个修改 首先在文件栏打开选择我们要编辑的PDF文档,选择 ...

最新文章

  1. 助力5G行业应用扬帆启航,第二届5G毫米波产业高峰论坛圆满召开
  2. 兴趣点推荐代码_推荐系统模型阿里用户兴趣模型(附完整代码)
  3. CentOs7中resourcemanager启动不了
  4. 库克笑了,说要给股东多分红:换了M1后Mac销售额增长70%,iPhone也增长66%
  5. 第20条:为私有方法名加前缀
  6. 洛谷UVA1328,POJ1961-Period【KMP,字符串】
  7. 该如何高效实用Kotlin?看这一篇就够了!
  8. 唔姆(二次元高清图片收藏)
  9. 使用meterpreter让没有安装python解释器的肉鸡设备执行任意python程序
  10. Nodejs 内置模块的基本使用
  11. Vue使用Axios Ajax封装渲染页面
  12. 使用Attribute简单地扩展WebForm
  13. Codeforces 490F Treeland Tour(离散化 + 线段树合并)
  14. 手机代理上网_ip地址是怎么来的?手机电脑怎么获得IP地址?
  15. 工程数学概率论统计简明教程第二版复习大纲
  16. 常用URL schemes ✨支付宝 、微信、腾讯、百度、网易、银行 、社交 、音频 、工具大集合
  17. UserWarning: Glyph 28857 (\N{CJK UNIFIED IDEOGRAPH-70B9}) missing from current font. FigureCanvasA
  18. 戴尔游匣 G15 2022 高配版参数配置
  19. IObit Driver Booster 无法更新驱动的解决办法
  20. 081020_文本分类(Text Classification)

热门文章

  1. 秒懂算法 | 蒙特卡罗算法
  2. 阿里终面:每天100w次登陆请求, 8G 内存该如何设置JVM参数?
  3. 在ASP网页中如何设置背景图片
  4. ES6日期函数整理(常用)
  5. 游承超:手机贴膜,你真的选对了吗?(31P)
  6. 爬虫系列笔记十一Phantomjs和Chrom handless
  7. iOS 应用苹果地图
  8. 百度指数-返回结果解密
  9. Ubuntu搭建PPTP和连接到PPTP
  10. 佑华SD-B3881 SD卡 TF卡写保护CID信息获取中英对照手册