在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#文件解析和处理 → ITextSharp 生成PDF实例,实例中还包含调用模版生成Word功能 附完整源码

ITextSharp 生成PDF实例,实例中还包含调用模版生成Word功能 附完整源码

C#文件解析和处理

下载此实例
  • 开发语言:C#
  • 实例大小:2.61M
  • 下载次数:360
  • 浏览次数:11413
  • 发布时间:2013-04-13
  • 实例类别:C#文件解析和处理
  • 发 布 人:crazycode
  • 文件格式:.zip
  • 所需积分:2
 相关标签: Word pdf ITextSharp

实例介绍

【实例简介】

压缩包中包含 ITextSharp中文教程用C#制作PDF文件全攻略.pdf 以及 用C#生成PDF文件、调用模版生成Word文档 等很多比较实用的实例,详见压缩包与截图,其中附完整源码
【实例截图】

生成后的pdf文档如下图:

生成的word如下图:

附件中包含的《ITextSharp中文教程用C#制作PDF文件全攻略.pdf》截图如下:


【核心代码】
default.aspx 前台代码:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WordExportTest._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div styled="display:none;">
        <asp:Button ID="Button1" runat="server" Text="调用WORD模板" OnClick="Button1_Click" />

        <asp:Button ID="Button2" runat="server" Text="iTextSharpPDF示例" 
            onclick="Button2_Click" />
        <asp:Button ID="Button3" runat="server" Text="iTextSharpWord示例" 
            onclick="Button3_Click"  />
        <asp:Button ID="Button4" runat="server" Text="0802" onclick="Button4_Click" />

        <asp:Button ID="Button5" runat="server" onclick="Button5_Click" 
            style="height: 26px" Text="0804" />
        <asp:Button ID="Button6" runat="server" onclick="Button6_Click" Text="1004" />

        <asp:Button ID="Button7" runat="server" onclick="Button7_Click" Text="0302列表" />
        <asp:Button ID="Button8" runat="server" onclick="Button8_Click" Text="0404画线" />
        <asp:Button ID="Button9" runat="server" onclick="Button9_Click" Text="封装调用" />


    </div>
    <div>
        <asp:Label ID="Label1" runat="server" Text="模板文件"></asp:Label>
        <asp:TextBox ID="txtTemplate" runat="server">附表1</asp:TextBox>
        <asp:Button ID="Button10" runat="server" Text="模板调用" onclick="Button10_Click" />
    </div>
    </form>
</body>
</html>

后台实现:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using iTextSharp.text;
using System.IO;
using System.Drawing;
using iTextSharp.text.rtf;
using iTextSharp.text.pdf;

namespace WordExportTest
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Hashtable column=new Hashtable();
            column.Add("0","#年度#");
            column.Add("1","#案由#");
            column.Add("2","#经办人#");

            IList<Hashtable> repValue=new List<Hashtable>();
            Hashtable colval=new Hashtable();
            colval.Add("0","2010");
            colval.Add("1","食堂伙食不好");
            colval.Add("2","张学友");
            repValue.Add(colval);
            CallWordTemplate callwordtemplate = new CallWordTemplate();
            string strFileName = "案件移送审批表_"   System.DateTime.Now.ToString("yyyyMMddhhmmssff")   ".doc";
            callwordtemplate.CallDotTemplate(column, repValue, "案件移送审批表.doc", strFileName);
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            //Document:(文档)生成pdf必备的一个对象,生成一个Document示例
            Document document = new Document(PageSize.A4, 30, 30, 5, 5);
            //为该Document创建一个Writer实例: 
            string strPdfFileName = System.AppDomain.CurrentDomain.BaseDirectory   "PDFOutput\\"   "测试PDF文件_"   System.DateTime.Now.ToString("yyyyMMddhhmmssff")   ".pdf";
            //string strDocFileName = System.AppDomain.CurrentDomain.BaseDirectory   "WordOutput\\"   "测试PDF文件_"   System.DateTime.Now.ToString("yyyyMMddhhmmssff")   ".doc";
            iTextSharp.text.pdf.PdfWriter.getInstance(document, new FileStream(strPdfFileName, FileMode.Create));
            //iTextSharp.text.rtf.RtfWriter.getInstance(document, new FileStream(strDocFileName, FileMode.Create));
            //打开当前Document
            document.Open();

            //为当前Document添加内容:
            document.Add(new Paragraph("Hello World"));
            //另起一行。有几种办法建立一个段落,如: 
            Paragraph p1 = new Paragraph(new Chunk("This is my first paragraph.\n", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            Paragraph p2 = new Paragraph(new Phrase("This is my second paragraph.", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            Paragraph p3 = new Paragraph("This is my third paragraph.", FontFactory.getFont(FontFactory.HELVETICA, 12));
            //所有有些对象将被添加到段落中:
            p1.Add("you can add string here\n\t");
            p1.Add(new Chunk("you can add chunks \n")); p1.Add(new Phrase("or you can add phrases.\n"));
            document.Add(p1); document.Add(p2); document.Add(p3);

            //创建了一个内容为“hello World”、红色、斜体、COURIER字体、尺寸20的一个块: 
            Chunk chunk = new Chunk("Hello world", FontFactory.getFont(FontFactory.COURIER, 20, iTextSharp.text.Font.COURIER, new iTextSharp.text.Color(255, 0, 0)));
            document.Add(chunk);
            //如果你希望一些块有下划线或删除线,你可以通过改变字体风格简单做到: 
            Chunk chunk1 = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED));
            Chunk chunk2 = new Chunk("This font is of type ITALIC | STRIKETHRU", FontFactory.getFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.ITALIC | iTextSharp.text.Font.STRIKETHRU));
            //改变块的背景
            chunk2.setBackground(new iTextSharp.text.Color(0xFF, 0xFF, 0x00));
            //上标/下标
            chunk1.setTextRise(5);
            document.Add(chunk1);
            document.Add(chunk2);

            //外部链接示例: 
            //BaseFont bfSun1 = BaseFont.createFont(@"C:\WINDOWS\Fonts\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            //iTextSharp.text.Font font1 = new iTextSharp.text.Font(bfSun1, 16);
            //string text = "iTextSharp网站";
            Anchor anchor = new Anchor("iTextSharp网站", FontFactory.getFont(@"C:\WINDOWS\Fonts\SIMHEI.TTF", 12, iTextSharp.text.Font.UNDEFINED, new iTextSharp.text.Color(0, 0, 255)));
            anchor.Reference = "http://itextsharp.sourceforge.net/";
            anchor.Name = "website";
            //内部链接示例:
            //BaseFont bfSun = BaseFont.createFont(@"c:\winnt\fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            BaseFont bfSun = BaseFont.createFont(@"C:\WINDOWS\Fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font font = new iTextSharp.text.Font(bfSun, 16);
            string text = "这是字体集合中的新宋体测试和一个内部链接!\n\n";
            //Anchor anchor1 = new Anchor(new Paragraph(text, font));
            //anchor1.Name = "link1";
            //Anchor anchor2 = new Anchor("点击将跳转到内部链接\n\f");
            //anchor2.Reference = "#link1";
            //document.Add(anchor); document.Add(anchor1); document.Add(anchor2);
            BaseFont bfHei = BaseFont.createFont(@"c:\WINDOWS\fonts\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
             font = new iTextSharp.text.Font(bfHei, 32);
             text = "这是黑体字测试!";
            document.Add(new Paragraph(text, font));

            TextWordPDF wordpdf = new TextWordPDF();
            string sFontName = wordpdf.GetFontName(TextWordPDF.FontName.黑体);
            bfSun = BaseFont.createFont(sFontName, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            font = new iTextSharp.text.Font(bfSun, 16);
            text = "这是字体集合中的新宋体测试!";
            document.Add(new Paragraph(text, font));

            //排序列表示例: 
            List list = new List(true, 20);
            list.Add(new iTextSharp.text.ListItem("First line"));
            list.Add(new iTextSharp.text.ListItem("The second line is longer to see what happens once the end of the line is reached. Will it start on a new line?"));
            list.Add(new System.Web.UI.WebControls.ListItem("Third line"));
            document.Add(list);

            //文本注释: 
            Annotation a = new Annotation("authors", "Maybe its because I wanted to be an author myself that I wrote iText.");
            document.Add(a);

            //包含页码没有任何边框的页脚。 
            HeaderFooter footer = new HeaderFooter(new Phrase("This is page: "), true);
            footer.Border = iTextSharp.text.Rectangle.NO_BORDER;
            document.Footer = footer;


            //Chapter对象和Section对象自动构建一个树:
            iTextSharp.text.Font f1 = new iTextSharp.text.Font();
            f1.setStyle(iTextSharp.text.Font.BOLD.ToString());
            Paragraph cTitle = new Paragraph("This is chapter 1", f1);
            Chapter chapter = new Chapter(cTitle, 1);
            Paragraph sTitle = new Paragraph("This is section 1 in chapter 1", f1);
            Section section = chapter.addSection(sTitle, 1);
            document.Add(chapter);

            //构建了一个简单的表: 
            iTextSharp.text.Table aTable = new iTextSharp.text.Table(4, 4);
            aTable.AutoFillEmptyCells = true;
            aTable.addCell("2.2", new Point(2, 2));
            aTable.addCell("3.3", new Point(3, 3));
            aTable.addCell("2.1", new Point(2, 1));
            aTable.addCell("1.3", new Point(1, 3));
            document.Add(aTable);
            //构建了一个不简单的表:
            iTextSharp.text.Table table = new iTextSharp.text.Table(3);
            table.BorderWidth = 1;
            table.BorderColor = new iTextSharp.text.Color(0, 0, 255);
            table.Cellpadding = 5;
            table.Cellspacing = 5;
            Cell cell = new Cell("header");
            cell.Header = true;
            cell.Colspan = 3;
            table.addCell(cell);
            cell = new Cell("example cell with colspan 1 and rowspan 2");
            cell.Rowspan = 2;
            cell.BorderColor = new iTextSharp.text.Color(255, 0, 0);
            table.addCell(cell);
            table.addCell("1.1");
            table.addCell("2.1");
            table.addCell("1.2");
            table.addCell("2.2");
            table.addCell("cell test1");
            cell = new Cell("big cell");
            cell.Rowspan = 2;
            cell.Colspan = 2;
            cell.BackgroundColor = new iTextSharp.text.Color(0xC0, 0xC0, 0xC0);
            table.addCell(cell);
            table.addCell("cell test2");
            // 改变了单元格“big cell”的对齐方式: 
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.VerticalAlignment = Element.ALIGN_MIDDLE;
            document.Add(table);

            Graphic g = new Graphic();
            g.setBorder(3f, 5f);
            document.Add(g);
            document.Add(new Paragraph("Hello World"));
            document.Add(new Paragraph("Hello World\n\n"));
            g = new Graphic();
            g.setHorizontalLine(5f, 100f);
            document.Add(g);
            document.Add(new Paragraph("Hello World"));
            document.Add(new Paragraph("Hello World\n\n"));
            g = new Graphic();
            g.setHorizontalLine(2f, 80f, new iTextSharp.text.Color(0xFF, 0x00, 0x00));
            document.Add(g);
            g = new Graphic();
            g.setHorizontalLine(2f, 80f,new iTextSharp.text.Color(System.Drawing.Color.Black));
            document.Add(g);

            //关闭Document
            document.Close();

        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            Document document = new Document(PageSize.A4, 50, 50, 50, 50);

            string strDocFileName = System.AppDomain.CurrentDomain.BaseDirectory   "WordOutput\\"   "测试PDF文件_"   System.DateTime.Now.ToString("yyyyMMddhhmmssff")   ".doc";
            RtfWriter writer = RtfWriter.getInstance(document, new FileStream(strDocFileName, FileMode.Create)); //RtfWriter2 ,不要用RtfWriter,Server.MapPath服务器上存放文件路径目录

            //writer.SetDataCacheStyle(iTextSharp.text.rtf.document.output.RtfDataCache.CACHE_DISK);

            FontFactory.register("c:\\windows\\fonts\\mingliu.ttc,1", "mingliu1"); //这个字体是特别指定的,一定要先在FontFactory注册,第二个参数是起了一个同名,后面FontFactory.getFont用到这个同名


            //以下是将定义好的table给document.Header,如果需要页尾,也是一样先定义table,然后header.SetHeaderFooter()方法+document.Footer = footertable,在此略去不写

            Phrase phrase = new Phrase("**傢俱股份有限公司", FontFactory.getFont("mingliu1", 12, iTextSharp.text.Font.UNDERLINE));
            //rtfHeaderFooterGroup header = new RtfHeaderFooterGroup();
            //header.SetHeaderFooter(
            //                    new iTextSharp.text.rtf.headerfooter.RtfHeaderFooter(phrase),
            //                    iTextSharp.text.rtf.headerfooter.RtfHeaderFooter.DISPLAY_ALL_PAGES);
            HeaderFooter header = new HeaderFooter(phrase, false);
            document.Header = header;

            //打开文档

            document.Open();

            BaseFont bfSun = BaseFont.createFont(@"c:\WINDOWS\fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font font = new iTextSharp.text.Font(bfSun, 16, iTextSharp.text.Font.BOLD);
            string text = "这是字体集合中的新宋体测试,有下划线!";
            Paragraph pg1 = new Paragraph(text, font);
            pg1.Add("     同一段落的延续");
            Phrase myphrase = new Phrase("  **__________________________________________________________傢俱股份有限公司_____________________________________    ", FontFactory.getFont("mingliu1", 12, iTextSharp.text.Font.UNDERLINE));
            pg1.Add(myphrase);
            pg1.Add(new Phrase("**傢俱股份有限公司", FontFactory.getFont("mingliu1", 12)));
            document.Add(pg1);
            iTextSharp.text.Font font2 = new iTextSharp.text.Font(bfSun, 16, iTextSharp.text.Font.BOLD);
            string text2 = "这是字体集合中的新宋体测试,无下划线!";
            Paragraph ph2=new Paragraph(text2, font2);
            ph2.Alignment = Element.ALIGN_CENTER;
            document.Add(ph2);
            //Chunk chunk1 = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED));

            iTextSharp.text.Table headerTable = new iTextSharp.text.Table(6, 7);

            //正文的编辑
            headerTable.Border = iTextSharp.text.Rectangle.NO_BORDER;
            headerTable.Cellpadding = 2;
            headerTable.Cellspacing = 0;
            int[] columnWidths = { 12, 30, 10, 18, 12, 23 }; // 各个column宽度所占百分比
            headerTable.setWidths(columnWidths);
            headerTable.WidthPercentage = 100; // 整个headertable 100%占满页面

            Cell titleCell = new Cell(new Phrase("**傢俱股份有限公司", FontFactory.getFont("mingliu1", 12, iTextSharp.text.Font.UNDERLINE)));
            titleCell.Colspan = 6;
            titleCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            titleCell.HorizontalAlignment = Element.ALIGN_CENTER;
            headerTable.addCell(titleCell);

            Cell titleCell1 = new Cell(new Phrase("报价单", FontFactory.getFont("mingliu1", 12, iTextSharp.text.Font.BOLD)));
            titleCell1.Colspan = 6;
            titleCell1.Border = iTextSharp.text.Rectangle.NO_BORDER;
            titleCell1.HorizontalAlignment = Element.ALIGN_CENTER;
            headerTable.addCell(titleCell1);
            Cell blankCell = new Cell(new Phrase("", FontFactory.getFont("mingliu1", 12, iTextSharp.text.Font.BOLD)));
            blankCell.Colspan = 6;
            blankCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            headerTable.addCell(blankCell);

            //document.Add(headerTable);


            iTextSharp.text.Table table = new iTextSharp.text.Table(3);
            table.BorderWidth = 1;
            table.BorderColor = new iTextSharp.text.Color(0, 0, 255);
            table.Padding = 5;
            table.Spacing = 5;
            Cell cell = new Cell("header");
            cell.Header = true;
            cell.Colspan = 3;
            table.addCell(cell);
            cell = new Cell("example cell with colspan 1 and rowspan 2");
            cell.Rowspan = 2;
            cell.BorderColor = new iTextSharp.text.Color(255, 0, 0);
            table.addCell(cell);
            table.addCell("1.1");
            table.addCell("2.1");
            table.addCell("1.2");
            table.addCell("2.2");
            table.addCell("cell test1");
            cell = new Cell("big cell");
            cell.Rowspan = 2;
            cell.Colspan = 2;
            cell.BackgroundColor = new iTextSharp.text.Color(0xC0, 0xC0, 0xC0);
            table.addCell(cell);
            table.addCell("cell test2");
            document.Add(table);

            Graphic g = new Graphic();
            g.setBorder(3f, 5f);
            document.Add(g);
            document.Add(new Paragraph("Hello World"));
            document.Add(new Paragraph("Hello World\n\n"));
            g = new Graphic();
            g.setHorizontalLine(5f, 100f);
            document.Add(g);
            document.Add(new Paragraph("Hello World"));
            document.Add(new Paragraph("Hello World\n\n"));
            g = new Graphic();
            g.setHorizontalLine(2f, 80f, new iTextSharp.text.Color(0xFF, 0x00, 0x00));
            document.Add(g);

            //关闭文档

            document.Close();

            //文档编辑完后,我是通过resposne输出
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "UTF8";
            Response.ContentEncoding = System.Text.Encoding.UTF7;
            Response.ContentType = "application/msword";//设置输出文件类型为WORD文件。
            Response.AddHeader("Content-Disposition", "attachment;filename="   strDocFileName);

            Response.WriteFile(strDocFileName);
            Response.Flush();
            Response.End();
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            Document document = new Document(PageSize.A4, 50, 50, 50, 50);

            string strDocFileName = System.AppDomain.CurrentDomain.BaseDirectory   "WordOutput\\"   "测试Word0803.rtf";
            RtfWriter writer = RtfWriter.getInstance(document, new FileStream(strDocFileName, FileMode.Create)); //RtfWriter2 ,不要用RtfWriter,Server.MapPath服务器上存放文件路径目录

            /* We specify that the RTF file has a Title Page */
            writer.HasTitlePage= true;
            /* We create headers and footers for the RTF file */
            RtfHeaderFooters header = new RtfHeaderFooters();
            RtfHeaderFooters footer = new RtfHeaderFooters();
            /* We add a header that will only appear on the first page */
            header.Set(RtfHeaderFooters.FIRST_PAGE, new HeaderFooter(new Phrase("This header is only on the first page"), false));
            /* We add a header that will only appear on left-side pages */
            header.Set(RtfHeaderFooters.LEFT_PAGES, new HeaderFooter(new Phrase("This header is only on left pages"), false));
            /* We add a header that will only appear on right-side pages */
            header.Set(RtfHeaderFooters.RIGHT_PAGES, new HeaderFooter(new Phrase("This header is only on right pages. "), false));
            /* We add a footer that will appear on all pages except the first (because of the title page) 
             * Because the header has different left and right page footers, we have to add the footer 
             * to both the left and right pages. */
            footer.Set(RtfHeaderFooters.LEFT_PAGES, new HeaderFooter(new Phrase("This footer is on all pages except the first. Page: "), true));
            footer.Set(RtfHeaderFooters.RIGHT_PAGES, new HeaderFooter(new Phrase("This footer is on all pages except the first. Page: "), true));
            /* Open the document */
            document.Open();

            //// step 4: we create two chapters and add the same content to both.
            //Paragraph par = new Paragraph("This is some sample content.");
            //Chapter chap1 = new Chapter("Chapter 1", 1);
            //chap1.Add(par);
            //Chapter chap2 = new Chapter("Chapter 2", 2);
            //chap2.Add(par);

            //// step 5: we create the header for the first chapter, set the header and
            //// then add the first chapter.
            //HeaderFooter hf1 = new HeaderFooter(new Phrase("This is chapter 1"), false);
            //document.Header = hf1;
            //document.Add(chap1);

            //// step 6: we create a second header, set this one and then add the second
            //// chapter.
            //HeaderFooter hf2 = new HeaderFooter(new Phrase("This is chapter 2"), false);
            //document.Header = hf2;
            //document.Add(chap2);

            ///* We add the header and footer */
            //document.Header = header;
            //document.Footer = footer;
            /* We add some content */
            Chapter chapter = new Chapter(new Paragraph("Advanced RTF headers and footers", new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 16, iTextSharp.text.Font.BOLD)), 1);
            chapter.Add(new Paragraph("This document demonstrates the use of advanced RTF headers and footers."));
            for (int i = 0;
                i < 300;
                i  )
            {
                chapter.Add(new Paragraph("Line "   i));
            } document.Add(chapter);

            //关闭文档

            document.Close();
        }

        protected void Button5_Click(object sender, EventArgs e)
        {
            Document document = new Document();

            string strDocFileName = System.AppDomain.CurrentDomain.BaseDirectory   "WordOutput\\"   "测试Word0804.doc";
            RtfWriter writer = RtfWriter.getInstance(document, new FileStream(strDocFileName, FileMode.Create)); //RtfWriter2 ,不要用RtfWriter,Server.MapPath服务器上存放文件路径目录
            // step 3: we open the document
            document.Open();
            // step 4: we create a table and add it to the document
            iTextSharp.text.Table table = new iTextSharp.text.Table(3);
            table.BorderWidth = 1;
            table.BorderColor = new iTextSharp.text.Color(0, 0, 255);
            table.Padding = 5;
            table.Spacing = 5;
            Cell cell = new Cell("header");
            cell.Header = true;
            cell.Colspan = 3;
            table.addCell(cell);
            cell = new Cell("example cell with colspan 1 and rowspan 2");
            cell.Rowspan = 2;
            cell.BorderColor = new iTextSharp.text.Color(255, 0, 0);
            table.addCell(cell);
            table.addCell("1.1");
            table.addCell("2.1");
            table.addCell("1.2");
            table.addCell("2.2");
            table.addCell("cell test1");
            cell = new Cell("big cell");
            cell.Rowspan = 2;
            cell.Colspan = 2;
            cell.BackgroundColor = new iTextSharp.text.Color(0xC0, 0xC0, 0xC0);
            table.addCell(cell);
            table.addCell("cell test2");
            document.Add(table);

            document.Close();
        }

        protected void Button6_Click(object sender, EventArgs e)
        {
            Document document = new Document();

            string strDocFileName = System.AppDomain.CurrentDomain.BaseDirectory   "PDFOutput\\"   "测试PDF1004.pdf";
            PdfWriter writer = PdfWriter.getInstance(document, new FileStream(strDocFileName, FileMode.Create)); //RtfWriter2 ,不要用RtfWriter,Server.MapPath服务器上存放文件路径目录
            // step 3: we open the document
            document.Open();

            // step 4: we grab the ContentByte and do some stuff with it
            PdfContentByte cb = writer.DirectContent;

            // we create a PdfTemplate
            PdfTemplate template = cb.createTemplate(50, 50);
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            // we add a number of pages
            int i;
            for (i = 1; i < 5; i  )
            {
                String text = "Page "   writer.PageNumber   " of ";
                float len = bf.getWidthPoint(text, 12);
                cb.beginText();
                cb.setFontAndSize(bf, 12);
                cb.setTextMatrix(280, 40);
                cb.showText(text);
                cb.endText();
                cb.addTemplate(template, 280   len, 40);
                document.newPage();
            }
            template.beginText();
            template.setFontAndSize(bf, 12);
            template.showText((writer.PageNumber - 1).ToString());
            template.endText();


            document.Close();
        }

        protected void Button7_Click(object sender, EventArgs e)
        {
            Document document = new Document();

            string strDocFileName = System.AppDomain.CurrentDomain.BaseDirectory   "WordOutput\\"   "测试Word0302列表.doc";
            RtfWriter writer = RtfWriter.getInstance(document, new FileStream(strDocFileName, FileMode.Create)); //RtfWriter2 ,不要用RtfWriter,Server.MapPath服务器上存放文件路径目录
            // step 3: we open the document
            document.Open();
            List list = new List(true, 10);
            list.IndentationLeft = 10;
            iTextSharp.text.ListItem listItem1=new iTextSharp.text.ListItem("第一行,参考一下System.Environment的东西,比如:   System.Environment.SystemDirectory    System.Environment.GetFolderPath(System.Environment.SpecialFolder.System)");
            list.Add(listItem1);
            //listItem1.Add();
            List sublist;
            sublist = new List(true, 15);
            //sublist.ListSymbol = new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 8));
            sublist.IndentationLeft = 10;
            sublist.Add("第一行下的第一行");
            sublist.Add("The Complete Robot");
            sublist.Add("Caves of Steel");
            sublist.Add("The Naked Sun");
            list.Add(sublist);
            list.Add(new iTextSharp.text.ListItem("第二行"));
            sublist = new List(true, 15);
            //sublist.ListSymbol = new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 8));
            sublist.IndentationLeft = 10;
            sublist.Add("第二行下的第一行");
            sublist.Add("The Complete Robot");
            sublist.Add("Caves of Steel");
            sublist.Add("The Naked Sun");
            list.Add(sublist);
            list.Add(new iTextSharp.text.ListItem("第三行"));
            document.Add(list);

            document.Add(new Paragraph("some books I really like:"));
            iTextSharp.text.ListItem listItem;
            list = new List(true, 10);
            listItem = new iTextSharp.text.ListItem("When Harlie was one", FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN, 12));
            listItem.Add(new Chunk(" by David Gerrold", FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN, 11, iTextSharp.text.Font.ITALIC)));
            list.Add(listItem);
            listItem = new iTextSharp.text.ListItem("The World according to Garp", FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN, 12));
            listItem.Add(new Chunk(" by John Irving", FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN, 11, iTextSharp.text.Font.ITALIC)));
            list.Add(listItem);
            listItem = new iTextSharp.text.ListItem("Decamerone", FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN, 12));
            listItem.Add(new Chunk(" by Giovanni Boccaccio", FontFactory.getFont(FontFactory.TIMES_NEW_ROMAN, 11, iTextSharp.text.Font.ITALIC)));
            list.Add(listItem);
            document.Add(list);

            Paragraph paragraph = new Paragraph("some movies I really like:\n");
            list = new List(true, 15);
            list.Add("Wild At Heart");
            list.Add("Casablanca");
            list.Add("When Harry met Sally");
            list.Add("True Romance");
            list.Add("Le mari de la coiffeuse");
            paragraph.Add(list);
            document.Add(paragraph);

            document.Add(new Paragraph("Some authors I really like:"));
            list = new List(false, 20);
            list.ListSymbol = new Chunk("\u2022", FontFactory.getFont(FontFactory.HELVETICA, 20, iTextSharp.text.Font.BOLD));
            listItem = new iTextSharp.text.ListItem("Isaac Asimov");
            list.Add(listItem);
            //List sublist;
            sublist = new List(true, 10);
            sublist.ListSymbol = new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 8));
            sublist.Add("The Foundation Trilogy");
            sublist.Add("The Complete Robot");
            sublist.Add("Caves of Steel");
            sublist.Add("The Naked Sun");
            list.Add(sublist);
            listItem = new iTextSharp.text.ListItem("John Irving");
            list.Add(listItem);
            sublist = new List(true, 10);
            sublist.ListSymbol = new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 8));
            sublist.Add("The World according to Garp");
            sublist.Add("Hotel New Hampshire");
            sublist.Add("A prayer for Owen Meany");
            sublist.Add("Widow for a year");
            list.Add(sublist);
            listItem = new iTextSharp.text.ListItem("Kurt Vonnegut");
            list.Add(listItem);
            sublist = new List(true, 10);
            sublist.ListSymbol = new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 8));
            sublist.Add("Slaughterhouse 5");
            sublist.Add("Welcome to the Monkey House");
            sublist.Add("The great pianola");
            sublist.Add("Galapagos");
            list.Add(sublist);
            document.Add(list);


            document.Close();
        }

        protected void Button8_Click(object sender, EventArgs e)
        {
            string sSystemPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.System);
            int p = sSystemPath.LastIndexOf('\\');
            string parent = sSystemPath.Substring(0, p);
            string fullPath = Path.Combine(parent, "Fonts");

            Document document = new Document();

            string strDocFileName = System.AppDomain.CurrentDomain.BaseDirectory   "WordOutput\\"   "测试Word0404列表.doc";
            RtfWriter writer = RtfWriter.getInstance(document, new FileStream(strDocFileName, FileMode.Create)); //RtfWriter2 ,不要用RtfWriter,Server.MapPath服务器上存放文件路径目录
            // step 3: we open the document
            document.Open();
            // step 4: we add a Graphic to the document
            Graphic grx = new Graphic();
            // add a rectangle
            grx.rectangle(100, 700, 100, 100);
            // add the diagonal
            grx.moveTo(100, 700);
            grx.lineTo(200, 800);
            // stroke the lines
            grx.stroke();
            document.Add(grx);

            document.Close();
        }

        protected void Button9_Click(object sender, EventArgs e)
        {
            TextWordPDF textWord = new TextWordPDF();
            textWord.ExportDocType = TextWordPDF.DocType.Word;
            textWord.ExportFileName = "测试封装的WORD文件_"   System.DateTime.Now.ToString("yyyyMMddhhmmssff")   ".doc"; ;
            Document document = textWord.CreateDocument();

            string sHeiTi=textWord.GetFontName(TextWordPDF.FontName.黑体);
            Phrase phrase = new Phrase("**傢俱股份有限公司", FontFactory.getFont(sHeiTi, 12, iTextSharp.text.Font.UNDERLINE));
            //rtfHeaderFooterGroup header = new RtfHeaderFooterGroup();
            //header.SetHeaderFooter(
            //                    new iTextSharp.text.rtf.headerfooter.RtfHeaderFooter(phrase),
            //                    iTextSharp.text.rtf.headerfooter.RtfHeaderFooter.DISPLAY_ALL_PAGES);
            HeaderFooter header = new HeaderFooter(phrase, false);
            document.Header = header;

            //打开文档

            document.Open();

            BaseFont bfSun = BaseFont.createFont(@"c:\WINDOWS\fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font font = new iTextSharp.text.Font(bfSun, 16, iTextSharp.text.Font.BOLD);
            string text = "这是字体集合中的新宋体测试,有下划线!";
            Paragraph pg1 = new Paragraph(text, font);
            pg1.Add("     同一段落的延续");
            Phrase myphrase = new Phrase("  **_______________________________________--------_傢俱股份有限公司_____________________________________    ", FontFactory.getFont("mingliu1", 12,7));// iTextSharp.text.Font.UNDERLINE | iTextSharp.text.Font.BOLD|iTextSharp.text.Font.ITALIC));
            pg1.Add(myphrase);
            pg1.Add(new Phrase("**傢俱股份有限公司", FontFactory.getFont("mingliu1", 12)));
            document.Add(pg1);
            iTextSharp.text.Font font2 = new iTextSharp.text.Font(bfSun, 16, iTextSharp.text.Font.BOLD);
            string text2 = "这是字体集合中的新宋体测试,无下划线!";
            Paragraph ph2 = new Paragraph(text2, font2);
            ph2.Alignment = Element.ALIGN_CENTER;
            document.Add(ph2);
            //Chunk chunk1 = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED));

            iTextSharp.text.Table headerTable = new iTextSharp.text.Table(6, 7);

            //正文的编辑
            headerTable.Border = iTextSharp.text.Rectangle.NO_BORDER;
            headerTable.Cellpadding = 2;
            headerTable.Cellspacing = 0;
            int[] columnWidths = { 12, 30, 10, 18, 12, 23 }; // 各个column宽度所占百分比
            headerTable.setWidths(columnWidths);
            headerTable.WidthPercentage = 100; // 整个headertable 100%占满页面

            Cell titleCell = new Cell(new Phrase("**傢俱股份有限公司", FontFactory.getFont(sHeiTi, 12, iTextSharp.text.Font.UNDERLINE)));
            titleCell.Colspan = 6;
            titleCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            titleCell.HorizontalAlignment = Element.ALIGN_CENTER;
            headerTable.addCell(titleCell);

            Cell titleCell1 = new Cell(new Phrase("报价单", FontFactory.getFont(sHeiTi, 12, iTextSharp.text.Font.BOLD)));
            titleCell1.Colspan = 6;
            titleCell1.Border = iTextSharp.text.Rectangle.NO_BORDER;
            titleCell1.HorizontalAlignment = Element.ALIGN_CENTER;
            headerTable.addCell(titleCell1);
            Cell blankCell = new Cell(new Phrase("", FontFactory.getFont(sHeiTi, 12, iTextSharp.text.Font.BOLD)));
            blankCell.Colspan = 6;
            blankCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            headerTable.addCell(blankCell);

            //document.Add(headerTable);


            iTextSharp.text.Table table = new iTextSharp.text.Table(3);
            table.BorderWidth = 1;
            table.BorderColor = new iTextSharp.text.Color(0, 0, 255);
            table.Padding = 5;
            table.Spacing = 5;
            Cell cell = new Cell("header");
            cell.Header = true;
            cell.Colspan = 3;
            table.addCell(cell);
            cell = new Cell("example cell with colspan 1 and rowspan 2");
            cell.Rowspan = 2;
            cell.BorderColor = new iTextSharp.text.Color(255, 0, 0);
            table.addCell(cell);
            table.addCell("1.1");
            table.addCell("2.1");
            table.addCell("1.2");
            table.addCell("2.2");
            table.addCell("cell test1");
            cell = new Cell("big cell");
            cell.Rowspan = 2;
            cell.Colspan = 2;
            cell.BackgroundColor = new iTextSharp.text.Color(0xC0, 0xC0, 0xC0);
            table.addCell(cell);
            table.addCell("cell test2");
            document.Add(table);

            Graphic g = new Graphic();
            g.setBorder(3f, 5f);
            document.Add(g);
            document.Add(new Paragraph("Hello World"));
            document.Add(new Paragraph("Hello World\n\n"));
            g = new Graphic();
            g.setHorizontalLine(5f, 100f);
            document.Add(g);
            document.Add(new Paragraph("Hello World"));
            document.Add(new Paragraph("Hello World\n\n"));
            g = new Graphic();
            g.setHorizontalLine(2f, 80f, new iTextSharp.text.Color(0xFF, 0x00, 0x00));
            document.Add(g);

            //关闭文档

            document.Close();

            //文档编辑完后,我是通过resposne输出
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "UTF8";
            Response.ContentEncoding = System.Text.Encoding.UTF7;
            Response.ContentType = "application/msword";//设置输出文件类型为WORD文件。
            Response.AddHeader("Content-Disposition", "attachment;filename="   Server.HtmlDecode(textWord.ExportFileName));

            Response.WriteFile(textWord.ExportFullFileName);
            Response.Flush();
            Response.End();
        }

        protected void Button10_Click(object sender, EventArgs e)
        {
            string sTxtTemplate = txtTemplate.Text.Trim();
            TextWordPDF textword = new TextWordPDF();
            textword.ExportFileName = sTxtTemplate   System.DateTime.Now.ToString("yyyyMMddhhmmssff")   ".doc";
            textword.TemplateFileName =sTxtTemplate  ".xml";
            string sReturn =textword.ExportFromTemplate();
            if (sReturn != "")
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(),"show",
                    string.Format("<script type=\"text/javascript\" language=\"javascript\">alert('{0}');</script>", sReturn));
            }

            //文档编辑完后,我是通过resposne输出
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.ContentType = "application/msword";//设置输出文件类型为WORD文件。
            Response.AddHeader("Content-Disposition", "attachment;filename="   HttpUtility.UrlEncode(textword.ExportFileName, System.Text.Encoding.UTF8).ToString());

            Response.WriteFile(textword.ExportFullFileName);
            Response.Flush();
            Response.End();
        }
    }
}

 

标签: Word pdf ITextSharp

实例下载地址

ITextSharp 生成PDF实例,实例中还包含调用模版生成Word功能 附完整源码

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

第 1 楼 lanerry 发表于: 2014-07-28 19:10 22
正好需要这个的东西。。谢谢楼主

支持(0) 盖楼(回复)

第 2 楼 lixiaoxiong 发表于: 2014-09-11 18:01 19
正好需要这个的东西。。谢谢楼主

支持(0) 盖楼(回复)

第 3 楼 guoquan913 发表于: 2015-01-26 14:35 32
我来说两句...

支持(0) 盖楼(回复)

第 4 楼 guoquan913 发表于: 2015-01-26 14:35 48
没有积分啊

支持(0) 盖楼(回复)

第 5 楼 kinglsat 发表于: 2015-10-15 15:20 04
我来说两句...好 不错不错 很有用,最近正好用到这个 受教了

支持(0) 盖楼(回复)

第 6 楼 1192351152 发表于: 2016-01-27 10:33 21
正好需要这个的东西。。谢谢楼主

支持(0) 盖楼(回复)

第 7 楼 clearair2002 发表于: 2016-05-12 15:22 26
没积分

支持(0) 盖楼(回复)

第 8 楼 clearair2002 发表于: 2016-05-12 15:22 42
怎么下载?

支持(0) 盖楼(回复)

第 9 楼 tzzyw 发表于: 2016-06-27 19:50 46
东西不错,感谢分享

支持(0) 盖楼(回复)

第 10 楼 擦肩后的回眸 发表于: 2016-08-26 13:54 42
111111111111

支持(0) 盖楼(回复)

第 11 楼 hdg3707 发表于: 2016-10-17 14:48 26
正好需要这个的东西。。谢谢楼主

支持(0) 盖楼(回复)

第 12 楼 hdg3707 发表于: 2016-10-17 14:48 33
正好需要这个的东西。。谢谢楼主

支持(0) 盖楼(回复)

第 13 楼 hdg3707 发表于: 2016-10-17 14:48 43
正好需要这个的东西。。谢谢楼主

支持(0) 盖楼(回复)

第 14 楼 hdg3707 发表于: 2016-10-17 14:48 53
正好需要这个的东西。。谢谢楼主

支持(0) 盖楼(回复)

第 15 楼 樊隆庆 发表于: 2016-10-21 11:29 44
怎么运行出现错误了?求解

支持(0) 盖楼(回复)

第 16 楼 樊隆庆 发表于: 2016-10-21 11:31 27
我来说两句...好 不错不错 很有用,最近正好用到这个 受教了

kinglsat 2015-10-15 15:20 04

你好,这个运行出现了错误,求指教

支持(0) 盖楼(回复)

第 17 楼 q2515595169 发表于: 2017-09-08 16:21 03
没积分

支持(0) 盖楼(回复)

第 18 楼 liu_yls@163.com 发表于: 2018-02-01 09:04 19
没积分

支持(0) 盖楼(回复)

第 19 楼 ycailr 发表于: 2018-04-24 10:47 30
代码运行之后在哪里找生成的pdf

支持(0) 盖楼(回复)

第 20 楼 星火燎原 发表于: 2018-04-24 23:12 06
代码运行之后在哪里找生成的pdf

ycailr 2018-04-24 10:47 30

生成的文件在 PDFOutput 目录

支持(0) 盖楼(回复)

第 21 楼 ycailr 发表于: 2018-10-12 14:27 41
实例代码在哪里呢?WordExportTest是空的,打不开,什么也没有

支持(0) 盖楼(回复)

发表评论

(您的评论需要经过审核才能显示)

查看所有21条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警