iText 技術簡介

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", "郵箱", "[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;
}

下面一個方法用來創建一個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;
        }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章