iTextSharp使用入门(二)【MVC4下使用】

Models文件夹实体类:

  public class Person
    {
        public string Name { get; set; }
        public string Address { get; set; }
    }
    public class NameToColName
    {
        public string ModelName { get; set; }
        public string ColName { get; set; }
    }

PdfDemoController.cs控制器:

public class PdfDemoController : Controller
    {
        //
        // GET: /PdfDemo/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetPdf()
        {
            it.Font font = new it.Font(BaseFont.CreateFont("C:\\Windows\\Fonts\\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10);

            MemoryStream ms = new MemoryStream();
            it.Document document = new it.Document();

            PdfWriter.GetInstance(document, ms);

            document.Open();

            document.Add(new it.Paragraph("Yes Master!"));
            document.Add(new it.Paragraph("其疾如风,其徐如林,侵掠如火,不动如山,难知如阴,动如雷震", font));

            document.Close();
            return File(ms.ToArray(), "application/pdf", "ceshi.pdf");
        }
        public ActionResult ImagePdf()
        {
            return View();
        }
        public ActionResult SendImagePdfUrl(string ImageUrl)
        {
            JsonResult j = new JsonResult();
            string fileName = System.Guid.NewGuid().ToString();
            if (!string.IsNullOrEmpty(ImageUrl))
            {
                Image pdfImage = base64ToPic(ImageUrl);
                pdfImage.Save(Server.MapPath("~") + "/pdfimage/" + fileName + "1.jpg");
                var data = new { message = "success", filename = fileName };
                j.Data = data;//返回单个对象;  
            }
            else
            {
                var data = new { message = "未提供Url" };
                j.Data = data;//返回单个对象; 
            }
            return j;
        }
        public ActionResult GetImagePdf(string ID)
        {
            it.Font font = new it.Font(BaseFont.CreateFont("C:\\Windows\\Fonts\\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10);
            MemoryStream ms = new MemoryStream();
            it.Document document = new it.Document();
            PdfWriter.GetInstance(document, ms);
            document.Open();
            document.Add(new it.Paragraph("Yes Master!"));
            document.Add(new it.Paragraph("其疾如风,其徐如林,侵掠如火,不动如山,难知如阴,动如雷震", font));
            List<string> imageStringList = GetImageString(ID, 1);

            foreach (var item in imageStringList)
            {
                try
                {
                    //如果传过来的是Base64
                    //it.Image image = it.Image.GetInstance(base64ToPic(item), System.Drawing.Imaging.ImageFormat.Jpeg);
                    //如果传过来的是地址
                    it.Image image = it.Image.GetInstance(Server.MapPath("~") + "/pdfimage/" + item + ".jpg");

                    image.Alignment = it.Image.ALIGN_LEFT;
                    image.ScalePercent(30);
                    document.Add(image);
                }
                catch (Exception e)
                {
                    document.Add(new it.Paragraph("图片" + item + "不存在"));
                }
            }
            document.Close();
            document.Dispose();
            return File(ms.ToArray(), "application/pdf", "ceshi.pdf");
        }
        public ActionResult TablePdf()
        {
            return View();
        }
        public ActionResult GetTablePdf()
        {
            it.Font font = new it.Font(BaseFont.CreateFont("C:\\Windows\\Fonts\\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10);
            MemoryStream ms = new MemoryStream();
            it.Document document = new it.Document();
            PdfWriter.GetInstance(document, ms);
            document.Open();
            document.Add(new it.Paragraph("Yes Master!"));
            document.Add(new it.Paragraph("其疾如风,其徐如林,侵掠如火,不动如山,难知如阴,动如雷震", font));
            List<Person> personList = new List<Person>();
            personList.Add(new Person {Name="wlz",Address="1111"});
            personList.Add(new Person { Name = "xiaoming", Address = "1112" });
            personList.Add(new Person { Name = "xiaohong", Address = "1113" });
            List<NameToColName> nameList = new List<NameToColName>();
            nameList.Add(new NameToColName { ModelName = "Name", ColName = "姓名" });
            nameList.Add(new NameToColName { ModelName = "Address", ColName = "地址" });
            var properties = personList.First().GetType().GetProperties() as System.Reflection.PropertyInfo[];
            PdfPTable nameTable = new PdfPTable(properties.Length);
            //创建表头
            for (int i = 0; i < properties.Length; i++)
            {
                var property = properties[i];
                string colName = (nameList.Where(p => p.ModelName == property.Name).ToList())[0].ColName;
                nameTable.AddCell(new it.Phrase(colName,font));//注意加上中文字体
            }

            personList.ForEach(item =>
            {                              
                for (int i = 0; i < properties.Length; i++)
                {
                    var property = properties[i];
                    nameTable.AddCell(new it.Phrase(property.GetValue(item, null).ToString(),font));
                }
            });
            document.Add(nameTable);

            document.Close();
            document.Dispose();
            return File(ms.ToArray(), "application/pdf", "TableDemo.pdf");
        }
        /// <summary>
        /// //对字节数组字符串进行Base64解码并生成图片
        /// </summary>
        /// <param name="ImageUrl"></param>
        /// <returns></returns>
        public Image base64ToPic(string ImageUrl)
        {

            if (ImageUrl == null) //图像数据为空
            {
                return null;
            }
            try
            {
                //将一开始的data:png等信息去掉,只剩base64字符串
                String[] url = ImageUrl.Split(',');
                String u = url[1];
                //Base64解码
                byte[] imageBytes = Convert.FromBase64String(u);
                Image image;
                //生成图片
                using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
                {  
                    ms.Write(imageBytes, 0, imageBytes.Length);
                    image = Image.FromStream(ms, true);
                }
                return image;
            }
            catch (Exception e)
            {
                return null;
            }
        }
        /// <summary>
        /// 得到这一系列Image的Url
        /// </summary>
        /// <param name="ID">相同部分</param>
        /// <param name="count">共有几张</param>
        /// <returns></returns>
        public List<string> GetImageString(string ID, int count)
        {
            List<string> ImageStringList = new List<string>();

            for (int i = 0; i < count; i++)
            {
                ImageStringList.Add(ID + count.ToString());
            }
            return ImageStringList;
        }

    }

ImagePdf.cshtml视图:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ImagePdf</title>
    <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.js"></script>
</head>
<body>
    <div>
        <button id="btnSearch" tabindex="999999" class="slbutton" style="border-style: none;">
            导出</button>
        <div id="main" style="height: 400px"></div><input id="maininput" type="hidden"/>
        <iframe id="exportContainer" style="display: none;"></iframe>
        <script src="http://echarts.baidu.com/build/dist/echarts.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#btnSearch").bind("click", function () {
                    ExportPDF();
                });
            });
            // 路径配置
            require.config({
                paths: {
                    echarts: 'http://echarts.baidu.com/build/dist'
                }
            });

            // 使用
            require(
                [
                    'echarts',
                    'echarts/chart/bar' // 使用柱状图就加载bar模块,按需加载
                ],
                function (ec) {
                    // 基于准备好的dom,初始化echarts图表
                    var myChart = ec.init(document.getElementById('main'));

                    var option = {
                        animation :false,
                        tooltip: {
                            show: true
                        },
                        legend: {
                            data: ['销量']
                        },
                        xAxis: [
                            {
                                type: 'category',
                                data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
                            }
                        ],
                        yAxis: [
                            {
                                type: 'value'
                            }
                        ],
                        series: [
                            {
                                "name": "销量",
                                "type": "bar",
                                "data": [5, 20, 40, 10, 10, 20]
                            }
                        ]
                    };

                    // 为echarts对象加载数据 
                    myChart.setOption(option);
                    $("#maininput").val(myChart.getDataURL('jpg'));                    
                }
            );
            function ExportPDF() {

                var imgurl = $("#maininput").val();                    
                $.ajax({
                    async: true,
                    type: "POST",
                    url: "/PdfDemo/SendImagePdfUrl",
                    cache: false,
                    timeout: 60 * 60 * 1000,
                    dataType: "json",
                    data: {
                        ImageUrl: imgurl

                    },
                    success: function (result) {
                        if (result != null && result.message == "success") {
                            var src = "/PdfDemo/GetImagePdf?ID=" + result.filename;
                            $("#exportContainer").attr("src", src);
                            }
                            else {
                                if (result != null) {
                                    alert(result.Message);
                                }
                            }
                        },
                        beforeSend: function () {
                            $("#btnSearch").prop("disabled",true);
                        },
                        complete: function () {
                            $("#btnSearch").prop("disabled", false);
                        }
                });
            }
        </script>
    </div>
</body>
</html>

运行结果:

这里写图片描述


这里写图片描述

Index.cshtml视图:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.js"></script>
</head>
<body>

    <div>
        <button id="btnSearch" tabindex="999999" class="slbutton" style="border-style: none;">
            导出</button>
    </div>
    <iframe id="exportContainer" style="display: none;"></iframe>
    <script type="text/javascript">
        $(function () {
            $("#btnSearch").bind("click", function () {
                Search();
            });
        });
        function Search() {            
            //导出Csv
            var src = "/PdfDemo/GetPdf";
            $("#exportContainer").attr("src", src);

        };
    </script>
</body>
</html>

TablePdf.cshtml视图:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.js"></script>
</head>
<body>

    <div>
        <button id="btnSearch" tabindex="999999" class="slbutton" style="border-style: none;">
            导出</button>
    </div>
    <iframe id="exportContainer" style="display: none;"></iframe>
    <script type="text/javascript">
        $(function () {
            $("#btnSearch").bind("click", function () {
                Search();
            });
        });
        function Search() {
            //导出Csv
            var src = "/PdfDemo/GetTablePdf";
            $("#exportContainer").attr("src", src);

        };
    </script>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值