c#使用itextsharp的实例

来源:互联网 发布:淘宝发货清单模板下载 编辑:程序博客网 时间:2024/05/16 15:28

在编程中用到将一些报告生成pdf文件,用到了itextsharp版本是4.1.2.0和最新的版本的某些函数有出入

Document doc = new Document(PageSize.A4, 100, 100, 80, 80);//文档A4样式,左右页边距100,上下80
PdfWriter.GetInstance(doc, new FileStream(path + "" + pdfname + ".pdf", FileMode.Create));//创建文档            
HeaderFooter footer = new HeaderFooter(new Phrase(""), true);//页脚加页码居中下面画一条横线footer.SetAlignment("center");            footer.Border = iTextSharp.text.Rectangle.ALIGN_RIGHT;            doc.Footer = footer;

 

 

自带库中的字体不能进行汉语的编辑需要创建汉字的字体

BaseFont bfHei = BaseFont.CreateFont(@"c:\Windows\fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//黑体BaseFont bfSun = BaseFont.CreateFont("C:\\Windows\\Fonts\\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//宋体

上面的两个分别为创建黑体和宋体,需要注意的是宋体是ttc并且后面加一个0

 

 

iTextSharp.text.Font sun12red = new iTextSharp.text.Font(bfSun, 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.RED);//宋体12号红


iTextSharp.text.Font sun12chuti = new iTextSharp.text.Font(bfSun, 12,iTextSharp.text.Font.BOLD);//宋体12号加粗

编辑中可能会用到不同的字号颜色 ,上面两个是具体字体的定义

 

 

            Paragraph bianhao = new Paragraph("编号:"+num+"", sun10);            bianhao.SetAlignment("right");            doc.Add(bianhao);

段落默认是左对齐 也可以right设置为居右,center设置为居中

 

 

PdfPCell cell1 = new PdfPCell(new Phrase("项目", sun12));            cell1.HorizontalAlignment = 1;            PdfPCell cell2 = new PdfPCell(new Phrase("分数", sun12));            cell2.HorizontalAlignment = 1;            PdfPCell cell3 = new PdfPCell(new Phrase("1", sun12));            PdfPCell cell4 = new PdfPCell(new Phrase("2", sun12));            PdfPCell cell5 = new PdfPCell(new Phrase("3", sun12));            PdfPCell cell6 = new PdfPCell(new Phrase("4", sun12));            PdfPCell cell7 = new PdfPCell(new Phrase("5", sun12));            PdfPCell cell8 = new PdfPCell(new Phrase("6", sun12));            PdfPCell cell9 = new PdfPCell(new Phrase("7", sun12));            PdfPCell cell10 = new PdfPCell(new Phrase("8", sun12));            table.AddCell(cell1);            table.AddCell(cell2);            table.AddCell(cell3);            table.AddCell("" + pf + "");            table.AddCell(cell4);            table.AddCell("" + rp + "");            table.AddCell(cell5);            table.AddCell("" + sf + "");            table.AddCell(cell6);            table.AddCell("" + re + "");            table.AddCell(cell7);            table.AddCell("" + bp + "");            table.AddCell(cell8);            table.AddCell("" + gh + "");            table.AddCell(cell9);            table.AddCell("" + vt + "");            table.AddCell(cell10);            table.AddCell("" + mh + "");            doc.Add(table);

上面是进行表格的编辑HorizontalAlignment可以用来设置表格元素的对齐方式

 

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("D:\\reportpdf\\img\\ex.jpg");
            img.ScalePercent(60f);
            doc.Add(img);

图片的添加ScalePercent(60f)用来设置图片显示为原图的比例




 

0 0
原创粉丝点击