NetCore 创建、编辑PDF插入表格、图片、文字
NetCore 创建、编辑PDF插入表格、图片、文字(二)
NetCore 创建、编辑PDF插入表格、图片、文字(三)
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);
//生成pdf
Document 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();//获得该类的Type
for (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.3
image.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.3
image.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);
}
}
#endregion
document.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 document
public 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 page
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
}
// write on end of each page
public 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 document
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
}
}