Fork me on GitHub
iTextSharp:创建一个新pdf文件

代码:

    //添加文本

            //创建文档对象
            Document document = new Document();
            //实例化生成的文档
            PdfWriter.GetInstance(document, new FileStream("C:\\c.pdf", FileMode.Create));
            //打开文档
            document.Open();
            //在文档中添加文本内容
            document.Add(new Paragraph("Hello World!"));
            //关闭文档对象
            document.Close();

 

            //加页眉页脚

            //创建文档对象
            document = new Document();
            // 创建文档写入实例
            PdfWriter.GetInstance(document, new FileStream("C:\\d.pdf", FileMode.Create));

            //添加页脚
            HeaderFooter footer = new HeaderFooter(new Phrase("foot"), true);
            footer.Border = iTextSharp.text.Rectangle.NO_BORDER;
            document.Footer = footer;

            //添加页眉
            HeaderFooter header = new HeaderFooter(new Phrase("header"), false);
            header.BorderColor = iTextSharp.text.Color.BLUE;
            document.Header = header;

            //打开文档内容对象
            document.Open();

            //设计各页的内容
            document.Add(new Paragraph("This is First Page"));
            //新添加一个页
            document.NewPage();
            //第2页中添加文本
            document.Add(new Paragraph("This is second page"));
            //重置页面数量
            document.ResetPageCount();
            //关闭文档对象
            document.Close();


            //转换数据表为PDF文档

            //初始化一个目标文档类
            document = new Document();
            //调用PDF的写入方法流
            PdfWriter pdfWriter = PdfWriter.GetInstance(document, new FileStream("C:\\e.pdf", FileMode.Create));
            //打开目标文档对象
            document.Open();
            //创建PDF文档中的字体
            BaseFont baseFont = BaseFont.CreateFont();
            //根据字体路径和字体大小属性创建字体
            float f = 12;
            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, f);
            PdfPTable table = new PdfPTable(6);
            //遍历原table的内容
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 6; j++)
                {
                    table.AddCell(new Phrase(Convert.ToString(i + 1) + ":" + Convert.ToString(j + 1), font));
                }


            }
            //在目标文档中添加转化后的表数据
            document.Add(table);
            //关闭目标文件
            document.Close();

posted on 2009-12-30 15:39  HackerVirus  阅读(467)  评论(0编辑  收藏  举报