iText技术入门

时间:2024-10-16 02:00:04

iText是一种开源的用于创建和编辑PDF的插件,目前最新的版本可以在Github中找到,目前有JAVA和C#两个版本下面我简单的介绍一下iText强大的功能,希望在处理PDF文件中有更多一种途径

工具/原料

工具下载:itextsharp插件

visual studio C#

知道如何运行C#窗体应用程序

创建一个空的PDF文件

1、Document document = new Document(PageSize.A4, 20, 20, 35, 20);string fileName = "文件名.pdf";document.Open();PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));

2、这样就在项目文件中创建了一个"文件名.pdf"文件

iText技术入门

将Bitmap(位图)对象放在PDF的指定位置

1、Document document = new Document(PageSize.A4, 20, 20, 35, 20);string fileName = "文件名5.pdf";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(200, 100);document.Add(imgRed);}

iText技术入门

在PDF中绘制矢量线条,矢量字体

1、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:2canvas.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();//绘制完毕后,解锁画布}

iText技术入门

绘制贝塞尔曲线

1、private void Dire罕铞泱殳ctDrawResume(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;}

iText技术入门

设置图像Alpha通道,在PDF中显示不规则图像

1、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);}

iText技术入门

添加单元格、表格

1、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方法可多次重复使用,遵循从左到右,从上到下的单元格填充规则public void AddCell(Image image);public void AddCell(PdfPCell cell);public void AddCell(PdfPTable table);最后将表格添加到PDF文档中,其中表格单元格的基类都是IElement,所以也可以直接添加单元格到PDF文档public virtual bool Add(IElement element);

2、下面一个方法用来创建了一稍僚敉视个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:2tableBelow.SetWidths(new int[] { 4, 4, 5 });//设置下方表格的列度比为4:4:5Paragraph 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", "邮箱", "[email protected]"));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;}

3、下面一个方法用来创建一个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;}

4、其中的png图像来自本地文件最后调用BasicInfomation()方法创建表格,添加到PDF文档就可以啦document.Add(BasicInfomation());最后的效果如图

iText技术入门

添加水印

1、给一个已创建好的的PDF添加水印public voi蟠校盯昂d WaterMarker(){//输出的PDFstr足毂忍珩ing outputFilePath = @"D:\chenpeng\workfile\VS\PDFReader\PDFReader\bin\Debug\带水印.pdf";//需要添加水印的PDFstring 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);//打开一个存在的PDFiTextSharp.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);//将要创建的PDFString waterMarkName = "随便写点Things~在这";int j = waterMarkName.Length;PdfContentByte under;PdfGState gs = new PdfGState();gs.FillOpacity = 0.2f;// 设置透明度为0.2System.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~-45image.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;}}

iText技术入门
© 手抄报圈