引入包
用nuget安装itext和itext.bouncy-castle-adapter包:
创建pdf
string path = "a.pdf";
PdfWriter writer = new PdfWriter(path);
PdfDocument pdfDoc = new PdfDocument(writer);
var doc=new Document(pdfDoc);
Paragraph p = new Paragraph("hello,测试一下");
PdfFont font = PdfFontFactory.CreateFont(@"C:\Windows\Fonts\SIMKAI.TTF", PdfEncodings.IDENTITY_H);
p.SetFont(font);
doc.Add(p);
doc.Close();
操作表格
string path = "a.pdf";
PdfWriter writer = new PdfWriter(path);
PdfDocument pdfDoc = new PdfDocument(writer);
var doc = new Document(pdfDoc);
var headerTexts = new[] {
"标识", "姓名"
};
var table = new Table(headerTexts.Length) // 设置表格列数
.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);
//设置字体
PdfFont font = PdfFontFactory.CreateFont(@"C:\Windows\Fonts\SIMKAI.TTF", PdfEncodings.IDENTITY_H);
table.SetFont(font);
//添加表头
foreach (var header in headerTexts)
{
table.AddHeaderCell(new Cell()
.Add(new Paragraph(header))
.SetBold()//设置粗体
);
}
//第一行
table.AddCell(new Cell(0, 1).Add(new Paragraph("1"))//序号
.SetVerticalAlignment(iText.Layout.Properties.VerticalAlignment.MIDDLE))
.AddCell(new Cell(0, 1).Add(new Paragraph("abc,测试")).SetMinWidth(25)//姓名 设置最小列宽25,方便名字横向显示
.SetVerticalAlignment(iText.Layout.Properties.VerticalAlignment.MIDDLE));
//增加一行
table.StartNewRow();
//第二行
table.AddCell(new Cell(0, 1).Add(new Paragraph("2"))//序号
.SetVerticalAlignment(iText.Layout.Properties.VerticalAlignment.MIDDLE))
.AddCell(new Cell(0, 1).Add(new Paragraph("abc,测试2")).SetMinWidth(25)//姓名 设置最小列宽25,方便名字横向显示
.SetVerticalAlignment(iText.Layout.Properties.VerticalAlignment.MIDDLE));
//增加到文档
doc.Add(table);
//关闭文档
doc.Close();