itextsharp简单使用

  itextsharp 用于生成PDF文件,主要五个步骤,

1.创建一个iTextsharp.text.Document 对象的实例

2.为该Document创建一个Writer实例

3.打开当前Document

4.为当前Document添加内容

5.关闭Document

--示例代码
Document doc = new Document(PageSize.A4.Rotate()); FileStream fs = new FileStream(context.Server.MapPath("~/TempFile/" + filename), FileMode.Create); PdfWriter.GetInstance(doc, fs); doc.Open();
/*设置字体字形*/ BaseFont bfChinese
= BaseFont.CreateFont(@"c:\windows\fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font fontChinese = new Font(bfChinese, 10, Font.NORMAL, new iTextSharp.text.Color(0, 0, 0)); /*doc添加各种元素*/ ... doc.Close()

块,短句和段落

1.Chunk: 能被添加到文档的最小单位,Chunk  c1 = new Chunk("销售订单",font)

2.Phrase :比Chunk大一点,可添加多个Chunk

3.Paragraph:

public void AddParagraph(Document document, string para, int align, Font font)
{
  Paragraph p = new Paragraph(para, font);
  p.Alignment
= align;   document.Add(p); }

列表

iTextSharp.text.List li = new iTextSharp.text.List(List.ORDERED);
li.IndentationLeft = 210f;
foreach (DataRow row in ds.Tables[0].Rows)
{
  li.Add(new ListItem(new Phrase(row["file_name"].ToString(), fontChinese)));
}

表格

//添加datatable
public void AddTable(Document document, float[] f, DataTable Dt, Font font, float totalwidth, bool islock)
{
  PdfPTable table = new PdfPTable(f);
  table.TotalWidth = totalwidth;
  table.LockedWidth = islock;
  table.SpacingBefore = 10f;
  for (int i = 0; i < Dt.Rows.Count; i++)
  {
    for (int j = 0; j < Dt.Columns.Count; j++)
    {
      table.AddCell(new Phrase(Dt.Rows[i][j].ToString(), font));
    }
  }
  document.Add(table);
}
//增加表格元素
        public PdfPCell SetCell(string str, Font font, float padding, int align,int border,int colspan,int vertical)
        {
            PdfPCell cell = new PdfPCell(new Phrase(str, font));
            cell.PaddingBottom = padding + 1f;
            cell.PaddingLeft = padding;
            cell.PaddingRight = padding;
            cell.PaddingTop = padding;
            cell.HorizontalAlignment = align;//查看Element  1水平居中
            //switch (vertical) {
            //    case 0: cell.VerticalAlignment = Element.ALIGN_JUSTIFIED; break;
            //    case 1: cell.VerticalAlignment = Element.ALIGN_MIDDLE; break;
            //    default: break;
            //}
            //cell.VerticalAlignment = Element.ALIGN_JUSTIFIED;
            //cell.VerticalAlignment = Element.ALIGN_CENTER;
            cell.VerticalAlignment = Element.ALIGN_MIDDLE; ;
            cell.Border = border;
            cell.Colspan = colspan;
            return cell;
        }

 

 

转载于:https://www.cnblogs.com/tonyqiu/p/3625554.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值