1. 创建一个空的PDF文件
Documentdocument = new Document(PageSize.A4, 20, 20, 35, 20);
stringfileName = "文件名.pdf";
document.Open();
PdfWriterwriter = PdfWriter.GetInstance(document, new FileStream(fileName,FileMode.Create));
2. 将Bitmap(位图)对象放在PDF的指定位置
Documentdocument = new Document(PageSize.A4, 20, 20, 35, 20);
stringfileName = "文件名5.pdf";
using(document)
{
PdfWriterwriter = PdfWriter.GetInstance(document, new FileStream(fileName,FileMode.Create));
document.Open();
Bitmap img = new Bitmap(100, 300);
Graphics g = Graphics.FromImage(img);
g.FillRectangle(Brushes.Red, 0, 0, 100, 300);
g.FillRectangle(Brushes.Blue, 50, 100, 50, 100);
iTextSharp.text.Image imgRed = iTextSharp.text.Image.GetInstance((System.Drawing.Image)img, System.Drawing.Imaging.ImageFormat.Png);
imgRed.ScalePercent(100);//图像缩放比例
imgRed.SetAbsolutePosition(200,100);
document.Add(imgRed);
}
3. 在PDF中绘制矢量线条,矢量字体
Document document = new Document(PageSize.A4, 20, 20, 35, 20);
string fileName = "文件名5.pdf";
BaseFont BF_Light = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
using (document)
{
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
document.Open();
Bitmap img = new Bitmap(100, 300);
Graphics g = Graphics.FromImage(img);
g.FillRectangle(Brushes.Red, 0, 0, 100, 300);
g.FillRectangle(Brushes.Blue, 50, 100, 50, 100);
iTextSharp.text.Image imgRed = iTextSharp.text.Image.GetInstance((System.Drawing.Image)img, System.Drawing.Imaging.ImageFormat.Png);
imgRed.ScalePercent(100);
imgRed.SetAbsolutePosition(100, 50);
document.Add(imgRed);
//PdfContentByte canvas = writer.DirectContentUnder;//在PDF底层画东西
PdfContentByte canvas = writer.DirectContent;//在PDF顶层画东西
//画线
canvas.SaveState();//先锁定画布
canvas.SetLineWidth(0.1f);//设置线宽
for (int i = 0; i < 595; i += 50)//A4纸:595*842像素,每隔50像素绘制一条折线
{
for (int j = 0; j < 842; j += 50)
{
canvas.SetColorStroke(new CMYKColor(0.3f, 0.9f, 0f, 0f));//设置曲线颜色
canvas.SetLineDash(1f, 2f);//设置点划线,间隔比例1:2
canvas.MoveTo(i + 25, j);//设置折线的起始点
canvas.LineTo(i, j);//连接到另一个点,向左移动25像素
canvas.LineTo(i, j + 25);//连接到另一个点,向上移动25像素
canvas.Stroke();//折线结束
ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("(" + i + "," + j + ")", new iTextSharp.text.Font(BF_Light, 6, iTextSharp.text.Font.NORMAL, new CMYKColor(0.9f, 0.9f, 0f, 0f))), i, j, 0);//在坐标(i,j)处添加矢量字,显示该点的坐标
}
}
canvas.RestoreState();//绘制完毕后,解锁画布
}
4. 绘制贝塞尔曲线
private void DirectDrawResume(PdfContentByte canvas)
{
PicRidus = 90;
float PicPositonRate = 0.3f;
int ItemLength = 550;
ItemHeigth = 90;
ItemBaseStart = 750;
double openAngle = 100;
int numberSpace = 10;
float SpaceRate = 0.3f;
openAngle = openAngle * Math.PI / 180;
canvas.SetLineWidth(1);
canvas.SetColorFill(BaseColor.GRAY);
PicCirclePoint = new PointF(ItemLength * PicPositonRate, ItemBaseStart);
PointF Beiseir2 = new PointF(PicCirclePoint.X - PicRidus * (float)Math.Sin(openAngle / 2), PicCirclePoint.Y + PicRidus * (float)Math.Cos(openAngle / 2));
PointF Beiseir1 = new PointF(PicCirclePoint.X - PicRidus - 1 / 2 * PicRidus * PicRidus * (float)Math.Sin(Math.Asin(ItemHeigth / 2f / PicRidus) - openAngle / 2), PicCirclePoint.Y + ItemHeigth / 2);
PointF BeiseirControl = new PointF(Beiseir2.X - (Beiseir2.Y - Beiseir1.Y) / (float)Math.Tan(openAngle / 2), Beiseir1.Y);
canvas.Rectangle(0, Beiseir1.Y - ItemHeigth, ItemLength, ItemHeigth);
canvas.Fill();
canvas.Arc(ItemLength - ItemHeigth / 2, ItemBaseStart - ItemHeigth / 2, ItemLength + ItemHeigth / 2, ItemBaseStart + ItemHeigth / 2, 90, -180);
canvas.Fill();
//填充贝塞尔
canvas.MoveTo(PicCirclePoint.X, PicCirclePoint.Y);
canvas.LineTo(Beiseir1.X, Beiseir1.Y);
canvas.CurveTo(BeiseirControl.X, BeiseirControl.Y, Beiseir2.X, Beiseir2.Y);
canvas.Fill();
canvas.MoveTo(PicCirclePoint.X, PicCirclePoint.Y);
canvas.LineTo(2 * PicCirclePoint.X - Beiseir2.X, Beiseir2.Y);
canvas.CurveTo(2 * PicCirclePoint.X - BeiseirControl.X, BeiseirControl.Y, 2 * PicCirclePoint.X - Beiseir1.X, Beiseir1.Y);
canvas.Fill();
canvas.MoveTo(PicCirclePoint.X, PicCirclePoint.Y);
canvas.LineTo(2 * PicCirclePoint.X - Beiseir1.X, Beiseir1.Y - ItemHeigth);
canvas.CurveTo(2 * PicCirclePoint.X - BeiseirControl.X, BeiseirControl.Y - ItemHeigth, 2 * PicCirclePoint.X - Beiseir2.X, 2 * PicCirclePoint.Y - Beiseir2.Y);
canvas.Fill();
canvas.MoveTo(PicCirclePoint.X, PicCirclePoint.Y);
canvas.LineTo(Beiseir2.X, 2 * PicCirclePoint.Y - Beiseir2.Y);
canvas.CurveTo(BeiseirControl.X, BeiseirControl.Y - ItemHeigth, Beiseir1.X, Beiseir1.Y - ItemHeigth);
canvas.Fill();
for (int i = 0; i < numberSpace; i++)
{
canvas.Arc(PicCirclePoint.X - PicRidus, PicCirclePoint.Y - PicRidus, PicCirclePoint.X + PicRidus, PicCirclePoint.Y + PicRidus, (float)(90 + openAngle * 90 / Math.PI - openAngle * 180 / Math.PI * SpaceRate / (numberSpace + SpaceRate) - openAngle * 180 / Math.PI / (numberSpace + SpaceRate) * i), (float)(-openAngle * 180 / Math.PI * (1 - SpaceRate) / (numberSpace + SpaceRate)));
canvas.LineTo(PicCirclePoint.X, PicCirclePoint.Y);
canvas.Fill();
}
for (int i = 0; i < numberSpace; i++)
{
canvas.Arc(PicCirclePoint.X - PicRidus, PicCirclePoint.Y - PicRidus, PicCirclePoint.X + PicRidus, PicCirclePoint.Y + PicRidus, (float)(openAngle * 90 / Math.PI - 90 - openAngle * 180 / Math.PI * SpaceRate / (numberSpace + SpaceRate) - openAngle * 180 / Math.PI / (numberSpace + SpaceRate) * i), (float)(-openAngle * 180 / Math.PI * (1 - SpaceRate) / (numberSpace + SpaceRate)));
canvas.LineTo(PicCirclePoint.X, PicCirclePoint.Y);
canvas.Fill();
}
canvas.Circle(PicCirclePoint.X, PicCirclePoint.Y, PicRidus * 0.9f);
canvas.Fill();
PicRidus = PicRidus * 0.8f;
}
5. 设置图像Alpha通道,在PDF中显示不规则图像
private void headHandle(Document doc)
{
Bitmap oldHead = new Bitmap("me.jpg");
int headraduio = oldHead.Width / 2;
Bitmap newHead = new Bitmap(headraduio * 2, headraduio * 2);
BitmapData oldData = oldHead.LockBits(new System.Drawing.Rectangle(0, 0, newHead.Width, newHead.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);
BitmapData newData = newHead.LockBits(new System.Drawing.Rectangle(0, 0, newHead.Width, newHead.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb);
unsafe
{
byte* pin = (byte*)(oldData.Scan0.ToPointer());
byte* pout = (byte*)(newData.Scan0.ToPointer());
for (int i = 0; i < newHead.Width; i++)
{
for (int j = 0; j < newHead.Height; j++)
{
int off = (j * newHead.Width + i) * 4;
if ((i - headraduio) * (i - headraduio) + (j - headraduio) * (j - headraduio) < headraduio * headraduio)
{
pout[off + 3] = 255;
pout[off + 2] = pin[off + 2];
pout[off + 1] = pin[off + 1];
pout[off + 0] = pin[off + 0];
}
else
{
pout[off + 3] = 0;
}
}
}
newHead.UnlockBits(newData);
oldHead.UnlockBits(oldData);
}
iTextSharp.text.Image head = iTextSharp.text.Image.GetInstance((System.Drawing.Image)newHead, System.Drawing.Imaging.ImageFormat.Png);
float scaleRate = (float)PicRidus / headraduio;
head.ScalePercent(scaleRate * 100);
head.SetAbsolutePosition(PicCirclePoint.X - PicRidus, PicCirclePoint.Y - PicRidus); doc.Add(head);
}
6. 添加单元格、表格
Itext有几个重要的对象Paragraph->PdfPCell->PdfPTable->Document
首先定义一个段落Paragraph,定义的时候可以指定字体,首行缩进等等
public Paragraph(string str, Font font);
public Paragraph(float leading, string str, Font font);
然后定义一个单元格,将Paragraph放入单元格中,也可以将图像,表格放入单元格中
public PdfPCell(Image image);
public PdfPCell(PdfPCell cell);
public PdfPCell(PdfPTable table);
public PdfPCell(Image image, bool fit);
public PdfPCell(PdfPTable table, PdfPCell style);
再定义一个表格,可以将图像,单元格,表格等放入表格中,表格对象的AddCell方法可多次重复使用,遵循从左到右,从上到下的单元格填充规则
publicvoid AddCell(Image image);
publicvoid AddCell(PdfPCell cell);
publicvoid AddCell(PdfPTable table);
最后将表格添加到PDF文档中,其中表格单元格的基类都是IElement,所以也可以直接添加单元格到PDF文档
publicvirtualbool Add(IElement element);
下面一个方法用来创建了一个PdfPTable表格对象
private PdfPTable BasicInfomation()
{
BaseFont Wryhbd = BaseFont.CreateFont(@"C:\Windows\Fonts\msyhbd.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
PdfPTable tableALL = new PdfPTable(1);//定义一张表格,只有一列
tableALL.WidthPercentage = 60f;//定义表格占据页面的宽度
tableALL.SpacingAfter = 0;//定义行后宽度
tableALL.SpacingBefore = 100;//定义行前宽度
tableALL.HorizontalAlignment = Element.ALIGN_RIGHT;//设置单元格靠右显示
PdfPTable tableAbove = new PdfPTable(2);//在表格的第一行设置一个2列的表格
PdfPTable tableBelow = new PdfPTable(3);//在表格的第二行设置一个3列的表格
tableAbove.SetWidths(new int[] { 1, 2 });//设置上方表格的列度比为1:2
tableBelow.SetWidths(new int[] { 4, 4, 5 });//设置下方表格的列度比为4:4:5
Paragraph p = new Paragraph("张三", new iTextSharp.text.Font(Wryhbd, 25, iTextSharp.text.Font.NORMAL, BaseColor.WHITE));
PdfPCell cell = new PdfPCell(p);
cell.Top = ItemBaseStart + ItemHeigth / 2;
//cell.BorderWidthBottom = 3f;//设置表格线宽
//cell.BorderWidthTop = 3f;//设置表格线宽
cell.PaddingBottom = 10f;//设置表格线宽
cell.PaddingLeft = 20f;
cell.PaddingTop = 20f;
//cell.BorderWidth = 50f;
cell.Border = iTextSharp.text.Rectangle.NO_BORDER;//不显示网格线
tableAbove.AddCell(cell);//将单元格对象添加到上方表格对象
p = new Paragraph("写点东西:今天吃啥好呢", new iTextSharp.text.Font(BF_Light, 15, 1, BaseColor.WHITE));
cell = new PdfPCell(p);
cell.Top = ItemBaseStart + ItemHeigth / 2;
cell.BorderWidthBottom = 3f;
cell.BorderWidthTop = 3f;
cell.BorderWidthTop = 3f;
cell.PaddingBottom = 10f;
cell.PaddingLeft = 20f;
cell.PaddingTop = 30f;
tableAbove.WidthPercentage = 100f;
cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
tableAbove.AddCell(cell);
cell = new PdfPCell(tableAbove);
cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
tableALL.AddCell(cell);
tableBelow.AddCell(info("生日.png", "生日", "1993.11.25"));
tableBelow.AddCell(info("手机.png", "手机", "13212734173"));
tableBelow.AddCell(info("邮箱.png", "邮箱", "1596058469@qq.com"));
tableBelow.AddCell(info("地址.png", "地址", "地球村"));
tableBelow.AddCell(info("性别.png", "性别", "男"));
tableBelow.AddCell(info("爱好.png", "爱好", "难道你看不出来吗?"));
cell = new PdfPCell(tableBelow);
cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
tableALL.AddCell(cell);
return tableALL;
}
下面一个方法用来创建一个PdfPCell单元格对象
private PdfPCell info(String icon, String name, String content)
{
PdfPTable table = new PdfPTable(3);
table.SetWidths(new int[] { 1, 3, 6 });
table.WidthPercentage = 100f;
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(icon);
PdfPCell cell = new PdfPCell(image, true);
cell.PaddingBottom = 3f;
cell.PaddingTop = 3f;
cell.HorizontalAlignment = Element.ALIGN_RIGHT;
cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
//将单元格放入表格的第一列中
table.AddCell(cell);
Paragraph p = new Paragraph(name + ": ", new iTextSharp.text.Font(BF_Light, 8, iTextSharp.text.Font.BOLD, BaseColor.WHITE));
cell = new PdfPCell(p);
cell.PaddingBottom = 3f;
cell.HorizontalAlignment = Element.ALIGN_LEFT;
cell.PaddingTop = 3f;
cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
table.AddCell(cell);
p = new Paragraph(content, new iTextSharp.text.Font(BF_Light, 8, iTextSharp.text.Font.NORMAL, BaseColor.WHITE));
cell = new PdfPCell(p);
cell.PaddingBottom = 3f;
cell.PaddingTop = 3f;
cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
table.AddCell(cell);
cell = new PdfPCell(table);
cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
return cell;
}
其中的png图像来自本地文件
最后调用BasicInfomation()方法创建表格,添加到PDF文档就可以啦
document.Add(BasicInfomation());
最后的效果
7. 添加水印
给一个已创建好的的PDF添加水印
public void WaterMarker()
{
//输出的PDF
string outputFilePath = @"D:\chenpeng\workfile\VS\PDFReader\PDFReader\bin\Debug\带水印.pdf";
//需要添加水印的PDF
string inputFilePath = @"D:\chenpeng\note\SAPUI5笔记.pdf";
//string inputFilePath = "文件名5.pdf";
try
{
using (Stream inputPdfStream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream outputPdfStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
PdfReader reader = new PdfReader(inputPdfStream);//打开一个存在的PDF
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(new Bitmap("me.jpg"), BaseColor.RED);
//image.Rotation = -20;//旋转 弧度
// image.ScaleAbsolute(200,100);//自定义大小
PdfStamper stamper = new PdfStamper(reader, outputPdfStream);//将要创建的PDF
String waterMarkName = "随便写点Things~在这";
int j = waterMarkName.Length;
PdfContentByte under;
PdfGState gs = new PdfGState();
gs.FillOpacity = 0.2f;// 设置透明度为0.2
System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix();
for (int i = 0; i < reader.NumberOfPages; i++)
{
under = stamper.GetUnderContent(i + 1);//获取PDF指定页的画布
under.SetGState(gs);//设置透明度
under.SetColorStroke(BaseColor.RED);//设置线条颜色
under.SetColorFill(BaseColor.BLUE);//设置填充颜色
for (int pi = 0; pi < 7; pi++)//每页加8个水印
{
image.RotationDegrees = 45 - pi * 15;//旋转 角度45~-45
image.SetAbsolutePosition(100 + pi * 32, 650 - pi * 90);//坐标,线性变化
image.ScalePercent((pi - 3.5f) * (pi - 3.5f) / 3.5f / 3.5f * 50 + 50);//缩放100%到50%再到100%,遵循二次函数规律
under.AddImage(image, true);// 添加图片
under.BeginText();
matrix.Reset();
matrix.Translate(160 + pi * 32, 660 - pi * 90);//坐标系变换:平移
matrix.Rotate(45 - pi * 15);//坐标系变换:旋转
under.SetTextMatrix(matrix);
under.SetFontAndSize(BF_Light, -(pi - 3.5f) * (pi - 3.5f) / 3.5f / 3.5f * 20 + 30);
under.ShowText(waterMarkName);
under.EndText();// 结束文本块
under.Ellipse(150 + pi * 32, 700 - pi * 90, 200 + pi * 32, 750 - pi * 90);//绘制椭圆
under.Fill();//填充颜色
under.SetLineWidth(1f);
under.Stroke();
}
}
stamper.Close();
reader.Close();
}
}
catch (Exception ex)
{
this.textBox1.Text = ex.Message;
}
}