使用iTextSharp生成pdf文件,需要引用ItextSharp.dll和ICSharpCode.SharpZipLib.dll.相关dll可以下载附件
创建第一个简单的pdf文件:
//定义pdf采用a4页大小
iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(PageSize.A4.Width, PageSize.A4.Height);
//设置pdf的背景颜色
rect.BackgroundColor = new BaseColor(ColorTranslator.FromHtml("#cccccc"));
//构建pdf document对象
iTextSharp.text.Document doc = new Document(rect);
PdfWriter pw=PdfWriter.GetInstance(doc, new System.IO.FileStream("c:\\test.pdf", System.IO.FileMode.OpenOrCreate));
doc.Open();
//添加段落内容
doc.Add(new Paragraph("this is test"));
//添加一个简单的图片
System.Drawing.Bitmap bmp = new Bitmap(100, 200);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.Red);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] buffer = ms.ToArray();
g.Dispose();
bmp.Dispose();
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(buffer);
Chunk ck = new Chunk(image, 100, 0);
doc.Add(ck);
//添加一个书签到外部链接
PdfAction action = new PdfAction("http://wangfu-02.iteye.com/");
PdfContentByte aa= pw.DirectContent;
PdfOutline outline = new PdfOutline(aa.RootOutline, action, "链接到http://wangfu-02.iteye.com/");
//添加一个内部锚点
//定义锚点链接内容
Anchor ah = new iTextSharp.text.Anchor("asdfasdfasdf,this is test");
ah.Name = "aaa";//链接内容名称
doc.Add(ah);
//定义锚点
Anchor ah1 = new iTextSharp.text.Anchor("click to aaa");
ah1.Reference = "#aaa"; //锚点指到的链接内容名称
doc.Add(ah1);
doc.Close()
上面就创建了一个简单的pdf文件。