iTextSharp生成pdf的一个简单例子

效果图:

代码:

  /// <summary>
        /// Compare页面生成pdf功能。
        /// </summary>
        /// <param name="country">国家</param>
        /// <param name="pns">pn</param>
        /// <param name="language">语言</param>
        /// <returns>响应对象</returns>
        public string ComparePdf(string country, string[] pns, string language)
        {
            var result = "";
            //生成pdf
            Document document = new Document();

            //这样写:是生成一个文件到某目录中
            //var directory = HttpContext.Current.Server.MapPath("~/pdf");
            //string host = HttpContext.Current.Request.Url.Host;
            //int port = HttpContext.Current.Request.Url.Port;
            //if (!Directory.Exists(directory))
            //{
            //    Directory.CreateDirectory(directory);
            //}
            //var fileName = "";
            //foreach (var item in pns)
            //{
            //    fileName += "_" + item + "_";
            //}
            //fileName = "Compare" + fileName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
            //var pdfPath = directory + "\\" + fileName;
            //var fileStream = new FileStream(pdfPath, FileMode.Create);
            //PdfWriter pw = PdfWriter.GetInstance(document, fileStream);

         //这样写:是生成文件到内存中去
            var memoryStream = new MemoryStream();
            PdfWriter pw = PdfWriter.GetInstance(document, memoryStream);//生成到内存中

            //数据
            var list = Compare(country, pns, language);
            document.Open();//打开文件
            //写入数据
            //注册字体
            string fontpath = HttpContext.Current.Server.MapPath("~/App_Data");
            BaseFont customfont = BaseFont.CreateFont(fontpath + "\\Lato-Regular.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
            var baseFont = new Font(customfont, 14 * 0.667f, Font.NORMAL, new Color(68, 68, 68));
            var leftFont = new Font(customfont, 14 * 0.667f, Font.BOLD, new Color(68, 68, 68));
            #region 头部
            PdfPTable tableLogo = new PdfPTable(3);
            tableLogo.DefaultCell.Border = Rectangle.NO_BORDER;
            tableLogo.DefaultCell.MinimumHeight = 40f;
            float[] headWidths = new float[] { 60f, 60f, 150f };
            tableLogo.SetWidths(headWidths);
            //logo
            var logo = iTextSharp.text.Image.GetInstance("http://d1fyvoqprbjuee.cloudfront.net/smartfindimages/logo.png");
            logo.ScaleToFit(130 * 0.667f, 43 * 0.667f);
            var logoCell = new PdfPCell();
            logoCell.PaddingLeft = -1f;
            logoCell.MinimumHeight = 45f;
            logoCell.HorizontalAlignment = Element.ALIGN_LEFT;
            logoCell.Border = 0;
            logoCell.AddElement(logo);
            tableLogo.AddCell(logoCell);

             var headFont = new Font(customfont, 26 * 0.667f, Font.BOLD, new Color(68, 68, 68));
            var sCell = new PdfPCell(new Paragraph("SmartFind", headFont));
            sCell.Border = 0;
            sCell.PaddingLeft = 3f;
            sCell.PaddingBottom = 17f;
            sCell.MinimumHeight = 45f;
            sCell.HorizontalAlignment = Element.ALIGN_LEFT;
            sCell.VerticalAlignment = Element.ALIGN_BOTTOM;
            tableLogo.AddCell(sCell);

            var aCell = new PdfPCell();
            aCell.Border = 0;
            aCell.MinimumHeight = 45f;
            aCell.PaddingBottom = 17f;
            aCell.HorizontalAlignment = Element.ALIGN_LEFT;
            aCell.VerticalAlignment = Element.ALIGN_BOTTOM;
            var accFont = new Font(customfont, 18 * 0.667f, Font.NORMAL, new Color(170, 170, 170));
            var acc = new Paragraph("|  Accessories", accFont);
            aCell.AddElement(acc);
            tableLogo.AddCell(aCell);

            document.Add(tableLogo);
            #endregion

            document.Add(new Paragraph(""));

            #region 中间的表格
            PdfPTable table = new PdfPTable(list.Count + 1);//n列的表格
            table.DefaultCell.Border = 0;
            table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
            table.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;

            //根据图片数量确定列数及列宽
            if (pns.Count() == 1)
            {
                float[] widths = new float[] { 2f, 3f };
                table.SetWidths(widths);
            }
            else if (pns.Count() == 2)
            {
                float[] widths = new float[] { 2f, 3f, 3f };
                table.SetWidths(widths);
            }
            else if (pns.Count() == 3)
            {
                float[] widths = new float[] { 2f, 3f, 3f, 3f };
                table.SetWidths(widths);
            }
            else if (pns.Count() == 4)
            {
                float[] widths = new float[] { 2f, 3f, 3f, 3f, 3f };
                table.SetWidths(widths);
            }
            //左单元格
            var leftCell = new PdfPCell(new Paragraph("Images", leftFont));
            leftCell.MinimumHeight = 40f;
           leftCell.BackgroundColor = new Color(242, 242, 242);
            leftCell.HorizontalAlignment = Element.ALIGN_CENTER;
            leftCell.VerticalAlignment = Element.ALIGN_MIDDLE;
            table.AddCell(leftCell);

            //右单元格
            var rightCell = new PdfPCell();
            rightCell.HorizontalAlignment = Element.ALIGN_CENTER;
            rightCell.VerticalAlignment = Element.ALIGN_MIDDLE;
            rightCell.MinimumHeight = 40f;

            foreach (var item in list)
            {
                var imageCell = new PdfPCell();
                imageCell.Padding = 1f;
                //根据图片数量确定左边距,确保图片在中间显示。这个地方写的不好,暂时这样
                if (list.Count == 2)
                {
                    imageCell.PaddingLeft = 30f;
                }
                if (list.Count == 1)
                {
                    imageCell.PaddingLeft = 80f;
                }
                if (list.Count == 3)
                {
                    imageCell.PaddingLeft = 10f;
                }
                //确保网络图片存在
                if (!string.IsNullOrEmpty(item.Url) && Helper.IsExists(item.Url + "-218.png"))
                {
                    var image = iTextSharp.text.Image.GetInstance(item.Url + "-218.png");
                    if (list.Count == 4)
                    {
                        image.ScaleToFit(80f, 80f);
                    }
                    else
                    {
                        image.ScaleToFit(100f, 100f);
                    }
                    imageCell.AddElement(image);
                }
                table.AddCell(imageCell);
            }

            //Product Title
            leftCell.Phrase = new Paragraph("Product Title", leftFont);
            var titleFont = new Font(customfont, 14 * 0.667f, Font.NORMAL, new Color(255, 105, 0));
            table.AddCell(leftCell);
            foreach (var item in list)
            {
                rightCell.Phrase = new Paragraph(item.Title, titleFont);
                table.AddCell(rightCell);
            }

            //List Price
            leftCell.Phrase = new Paragraph("List Price", leftFont);
            table.AddCell(leftCell);
            foreach (var item in list)
            {
                rightCell.Phrase = new Paragraph(item.Currency + item.Price, baseFont);
                table.AddCell(rightCell);
            }

            //Part Number
            leftCell.Phrase = new Paragraph("Part Number", leftFont);
            table.AddCell(leftCell);
            foreach (var item in list)
            {
                rightCell.Phrase = new Paragraph(item.PN, baseFont);
                table.AddCell(rightCell);
            }

            //facet
            var first = list.FirstOrDefault();
            foreach (var item in first.Facets)
            {
                leftCell.Phrase = new Paragraph(item.Key, leftFont);
                table.AddCell(leftCell);
                rightCell.Phrase = new Paragraph(item.Value, baseFont);
                table.AddCell(rightCell);
                //其余的
                list.Remove(first);
                var other = list;
                foreach (var one in other)
                {
                    rightCell.Phrase = new Paragraph(one.Facets.FirstOrDefault(o => o.Key == item.Key).Value, baseFont);
                    table.AddCell(rightCell);
                }
            }
            document.Add(table);
            #endregion

            //页脚
            PDFFooter footer = new PDFFooter();
            footer.OnEndPage(pw, document);
            document.Close();
            var bytes = memoryStream.ToArray();
            result = Convert.ToBase64String(bytes);

            return result;
        }

/// <summary>
    /// 页脚类
    /// </summary>
    public class PDFFooter : PdfPageEventHelper
    {
        // write on top of document
        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            base.OnOpenDocument(writer, document);
            PdfPTable tabFot = new PdfPTable(new float[] { 1F });
            tabFot.SpacingAfter = 10F;
            PdfPCell cell;
            tabFot.TotalWidth = 300F;
            cell = new PdfPCell(new Phrase("Header"));
            tabFot.AddCell(cell);
            tabFot.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent);
        }

        // write on start of each page
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            base.OnStartPage(writer, document);
        }

        // write on end of each page
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);
            PdfPTable tabFot = new PdfPTable(new float[] { 1F });
            tabFot.TotalWidth = 700f;
            tabFot.DefaultCell.Border = 0;
          //  var footFont = FontFactory.GetFont("Lato", 12 * 0.667f, new Color(60, 60, 60));
            string fontpath = HttpContext.Current.Server.MapPath("~/App_Data");
            BaseFont customfont = BaseFont.CreateFont(fontpath + "\\Lato-Regular.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
            var footFont = new Font(customfont, 12 * 0.667f, Font.NORMAL, new Color(170, 170, 170));

            PdfPCell cell;
            cell = new PdfPCell(new Phrase("@ 2016 . All Rights Reserved", footFont));
            cell.VerticalAlignment = Element.ALIGN_CENTER;
            cell.Border = 0;
            cell.PaddingLeft = 100f;
            tabFot.AddCell(cell);
            tabFot.WriteSelectedRows(0, -1, 150, document.Bottom, writer.DirectContent);
        }

        //write on close of document
        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);
        }
    }

  

 /// <summary>
        /// 判断网络文件是否存在
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool IsExists(string url)
        {
            try
            {
                using (new WebClient().OpenRead(url)) { }
                return true;
            }
            catch (WebException)
            {
                return false;
            }
        }

  

时间: 2024-12-08 08:22:59

iTextSharp生成pdf的一个简单例子的相关文章

ITextSharp用来生成 PDF 的一个组件

iTextSharp 是用来生成  PDF 的一个组件,在 1998 年夏天的时候,Bruno Lowagie ,iText 的创作者,参与了学校的一个项目,当时使用 HTML 来生成报告,但是,使用 HTML 打印的效果很不理想.最后,他发现,使用 PDF 可以完美解决打印问题,为了能够在各个系统中使用,iText 组件库诞生了. 网页上面浏览pdf,目前一般是先转成swf格式,再查看. http://sourceforge.net/projects/itextsharp/files/

从一个简单例子来理解js引用类型指针的工作方式

? 1 2 3 4 5 6 7 <script> var a = {n:1};  var b = a;   a.x = a = {n:2};  console.log(a.x);// --> undefined  console.log(b.x);// --> [object Object]  </script> 上面的例子看似简单,但结果并不好了解,很容易把人们给想绕了--"a.x不是指向对象a了么?为啥log(a.x)是undefined?".&

C语言多线程的一个简单例子

多线程的一个简单例子: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> void * print_a(void *); void * print_b(void *); int main(){ pthread_t t0; pthread_t t1; // 创建线程A if(pthread_creat

生产者与消费者的一个简单例子

生产者 #include<fstream> #include<iostream> #include<Windows.h> using namespace std; int main(void) { ofstream out; const char ch = '*'; long long k = 0; DWORD64 time = GetTickCount64(); while (true) { if (GetTickCount64() - time > 5000)

使用ITextSharp生成PDF文件心得

最近公司在做一个项目,需要把数据导出成PDF格式的文件,然后再网上搜了一下发现开源的组件还挺多的,用的比较多的就是itextsharp,itextsharp由java的itext演变而来,并且提供的丰富的功能,能够制作表格.插入图片等,这是官网的下载地址:http://sourceforge.net/projects/itextsharp/,下面就来简单介绍一下使用itextsharp的心得. 首先创建一个winform应用程序,并且添加itextsharp的引用,在按钮的单击事件写上生成pdf

词法分析程序 LEX和VC6整合使用的一个简单例子

词法分析的理论知识不少,包括了正规式.正规文法.它们之间的转换以及确定的有穷自动机和不确定的有穷自动机等等... 要自己写一个词法分析器也不会很难,只要给出了最简的有穷自动机,就能很方便实现了,用if.switch-case来写一通所谓的状态转换就可以,我近期会写一个简单的词法分析程序来作为例子... 现在已经有人发明了一个叫LEX的工具让你去应用,那我们就省了不少力气,毕竟没到万不得已的时候,我们都没必要重新发明轮子,从另一个角度来说,使用工具是我们人类知识继承的一种方法,也是我们比其他动物优

PyQt安装与一个简单例子

PyQt在Windows+Visual Studio下安装所需文件如下: python-2.7.3.msi (www.python.org/download) sip-4.14.2.zip (www.riverbankcomputing.co.uk/software/sip/download) PyQt-Py2.7-x86-gpl-4.9.6-1.exe(www.riverbankcomputing.co.uk/software/pyqt/download) 安装方法: 首先安装python2.

Spring MVC:使用SimpleUrlHandlerMapping的一个简单例子

实现一个控制器ShirdrnController,如下所示: package org.shirdrn.spring.mvc; import java.util.Date; import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log;import org.apache.commons.logging.

一个简单例子了解使用互斥量线程同步

在刚开始学习学习线程同步时总是认为两个线程或是多个线程共同运行,但是那样是做的. 同步就是协同步调,按预定的先后次序进行运行.如:你说完,我再说. "同"字从字面上容易理解为一起动作. 其实不是,"同"字应是指协同.协助.互相配合. 如进程.线程同步,可理解为进程或线程A和B一块配合,A执行到一定程度时要依靠B的某个结果,于是停下来,示意B运行:B依言执行,再将结果给A:A再继续操作. 所谓同步,就是在发出一个功能调用时,在没有得到结果之前,该调用就不返回,同时其它