itextcsharp使用

http://www.cnblogs.com/islands/archive/2008/06/27/1231288.html

http://itextsharp.sourceforge.net/index.html

http://www.koders.com/csharp/fid9CD533EF4F80FA1F37332A8D9570B4D9BD4A2129.aspx?s=file

 

 

using System;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Collections.Generic;
using System.Data;


namespace DomainModel.Common
{
  public  class ItextSharpHelper
    { /// <summary>
        /// Document对象共有三个构造函数
        ///  PDF文档默认选项为A4纸,每边36磅页边距
        /// 如果你修改了页面尺寸,仅仅影响到下一页,如果你修改了页边距,则影响到全部,故慎用。
        /// </summary>
        /// <param name="rect">如果传入Null那么实现默认的格式</param>
        /// <returns></returns>
        public static Document CreateDocument(Rectangle rect)
        {
            Document document;
            if (rect == null)
            {
                document = new Document();
            }
            else
            {
                document = new Document(rect);
            }

        //document.AddAuthor("邮乐采购系统");
            document.AddCreationDate();
        //document.AddSubject("采购系统生成单据");
     
            return document;
        }

        /// <summary>
        /// PDF(目前计划的PDF只需要这些)文件的内部内容的组成
        /// (仅仅文字,仅仅图片,仅仅表格,文字-图片,文字-表格,图片,表格)
        /// </summary>
        /// <param name="strText"></param>
        public static PdfWriter GetPdfWriter(Document document, string strPass)
        {
          return  PdfWriter.GetInstance(document, new FileStream(strPass, FileMode.Create,FileAccess.ReadWrite));
        }

        ///// <summary>
        ///// 创建字体
        ///// </summary>
        ///// <param name="strFontName">字体名请参考FontFactory对象</param>
        ///// <param name="FontSize">字体大小</param>
        /////  <param name="TextColor">文字颜色请参考Color对象(iTextSharp.text命名空间)</param>
        ///// <param name="FontStyle">字体样式请参考Font对象</param>
        ///// <returns></returns>
        //public static Font CreateFont(string strFontName, float FontSize, Color TextColor, int FontStyle)
        //{
        //    Font font = FontFactory.GetFont(strFontName, FontSize, FontStyle, TextColor);
        //    return font;
        //}

        /// <summary>
        /// 创建中文字体(实现中文)
        /// </summary>
        /// <returns></returns>
        public static BaseFont CreateChineseFont()
        {
            string currentDir = System.Environment.CurrentDirectory;
            BaseFont.AddToResourceSearch(Path.Combine(currentDir,"iTextAsian.dll"));
            BaseFont.AddToResourceSearch(Path.Combine(currentDir,"iTextAsianCmaps.dll"));
            BaseFont basefont = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

         //  Font font = new Font(basefont, 11, Font.NORMAL, BaseColor.BLACK);
            return basefont;
        }

        ///// <summary>
        ///// 将一个DataTable对象的值转换为PDF文件中的表格
        ///// </summary>
        ///// <param name="DT">传入table,具体样式你可以在外部定义</param>
        //public static Table CreateTable(DataTable DT)
        //{
        //    int columnsCount = DT.Columns.Count;
        //    Table table = new Table(columnsCount);
        //    Font font = CreateChineseFont();
        //    for (int rowsindex = 0; rowsindex < DT.Rows.Count; rowsindex++)
        //    {
        //        for (int columnindex = 0; columnindex < columnsCount; columnindex++)
        //        {
        //            table.AddCell(new Paragraph(DT.Rows[rowsindex][columnindex].ToString(), font));
        //        }
        //    }
        //    return table;
        //}

        /// <summary>
        /// 建立一个类似于列表(HTML当中的OL或者是UL)
        /// </summary>
        /// <param name="strContent">如果传入True,那么列表符号为数字(1,2,3....)</param>
        /// <param name="blNumber">输入内容</param>
        public static List CreateList(bool blNumber, params string[] strContent)
        {
            List list = new List(blNumber, strContent.Length);
            foreach (string str in strContent)
            {
                list.Add(str);
            }
            return list;
        }

        /// <summary>
        /// 建立一个图片集合(输入图片地址)
        /// </summary>
        /// <param name="strLink"></param>
        /// <returns></returns>
        public static Image[] CreateImages(params string[] strLink)
        {
            int length = strLink.Length;
            Image[] images = new Image[length];
            for (int index = 0; index < length; index++)
            {
                images[index] = Image.GetInstance(strLink[index]);
            }
            return images;
        }

        /// <summary>
        /// 将多个图片流添加到Document对象当中
        /// 在调用这个方法之前必须打开对象
        /// </summary>
        /// <param name="images">传入图片集合</param>
        /// <param name="document">传入文档对象</param>
        public static void UpdateDocumentByImages(Image[] images, ref Document document)
        {
            foreach (Image img in images)
            {
                document.Add(img);
            }
        }
    }
}

 

 

using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using DomainModel.Entities.Pms;
using DomainModel.Repositories.Pms;
using iTextSharp.text;
using iTextSharp.text.pdf;
using log4net;

namespace DomainModel.Common.ExportFiles
{
    public class ExportPdf
    {
        private static readonly ILog Mylogger = LogManager.GetLogger("PushOrder");
        private static readonly string basePoDir = string.Empty;
        private static readonly string basehttpContextDir = string.Empty;
        private static readonly tab_configRepository _tabConfigRepository = new tab_configRepository();
        private static readonly tab_userinfoRepository _tab_userinfoRepository = new tab_userinfoRepository();
        private static readonly tab_stockinfoRepository _tab_stockinfoRepository = new tab_stockinfoRepository();
        private static readonly tab_wordsconfigRepository _tab_wordsconfigRepository = new tab_wordsconfigRepository();
        private static readonly string company = string.Empty;
        private static readonly string companyTel = string.Empty;

        static ExportPdf()
        {
            tab_config config = _tabConfigRepository.GetModelByKey("OrderDir");
            basePoDir = null != config ? config.value : "";

            config = _tabConfigRepository.GetModelByKey("HttpContextPath");
            basehttpContextDir = null != config ? config.value : "";

            config = _tabConfigRepository.GetModelByKey("Co_Name");
            company = null != config ? config.value : "";

            config = _tabConfigRepository.GetModelByKey("Co_Tel");
            companyTel = null != config ? config.value : "";
        }


        public static bool ExportRefundOrderPdf(tab_purchaselist pmain, List<tab_purchaseinfo> pinfoList,
                                                out string filepath)
        {
            bool result = false;
            filepath = string.Empty;
            if (null == pmain || pinfoList.Count < 1)
            {
                Mylogger.Info("ExportRefundOrderPdf 无数据不导出pdf");
                return false;
            }

            if (string.IsNullOrEmpty(basePoDir))
            {
                Mylogger.Info(" ExportRefundOrderPdf basePoDir为空");
                return false;
            }

            try
            {
                if (!pmain.createdate.HasValue)
                {
                    Mylogger.Info(" ExportPdf createdate为空");
                    return false;
                }
                DateTime createtime = pmain.createdate.Value;
                string directory = Path.Combine(basePoDir, createtime.ToString("yyyy"),
                                                createtime.ToString("MM.dd"));
             

                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                //

                string filepathname = Path.Combine(directory,
                                                   pmain.purchaseOrderId +
                                                   (pmain.orderStatus == (int) WordsEnum.退货单状态_已完成 ? "_b" : "_t") +
                                                   ".pdf");
                filepath = filepathname;
                //==============================================================
                string logopath = Path.Combine(basehttpContextDir, "images", "title.jpg");
                string notespath = Path.Combine(basehttpContextDir, "notes_refundNotice.txt");
                //
                Document document = ItextSharpHelper.CreateDocument(PageSize.A4.Rotate());
                PdfWriter writer = ItextSharpHelper.GetPdfWriter(document, filepathname);
                BaseFont basefont = ItextSharpHelper.CreateChineseFont();
                float pwidth = document.PageSize.Width;
                float pheight = document.PageSize.Height;
                float offsetx = 10f;
                float offsety = pheight;
                float col2x = 400f;
                document.Open();
                PdfContentByte canvas = writer.DirectContent;
                writer.CompressionLevel = 0;

                #region Titles

                canvas.SaveState();
                canvas.BeginText();

              
              //  Font font=new Font(basefont, 18, Font.NORMAL, BaseColor.BLACK);
                offsety = offsety - 40;
                canvas.SetFontAndSize(basefont, 18);
              
                canvas.ShowTextAligned(Element.ALIGN_LEFT,
                                       (pmain.orderStatus == (int) WordsEnum.退货单状态_已完成 ? "退货报告" : "退货通知单"),
                                       pwidth/2 - 70, offsety, 0);


                //Logo
                Image imgLogo = Image.GetInstance(System.Drawing.Image.FromFile(logopath), ImageFormat.Png);

                offsety = offsety - 10;
                imgLogo.SetAbsolutePosition(15, offsety);
                imgLogo.ScalePercent(80);
                canvas.AddImage(imgLogo);

                //bar
                Image imgbar = Image.GetInstance(BarCode39.GetCode39(pmain.purchaseOrderId), ImageFormat.Png);
                offsety = offsety - 30;
                imgbar.SetAbsolutePosition(10, offsety);
                imgbar.ScalePercent(100);
                canvas.AddImage(imgbar);


                canvas.SetFontAndSize(basefont, 11);
                offsety = offsety - 20;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("退货单号:{0}", pmain.purchaseOrderId), 12,
                                       offsety, 0);

                canvas.ShowTextAligned(Element.ALIGN_LEFT, "", col2x, pheight - 100,
                                       0);

                string settleType = Utility.ToString(pmain.settleType);
                if (!string.IsNullOrEmpty(settleType))
                {
                    string type = settleType;
                    tab_wordsconfig words = _tab_wordsconfigRepository.Get(
                        w => w.belongedId == (int) WordsEnum.销售模式 && w.wordsvalue == type);

                    settleType = null != words ? words.wordscontent : "";
                }

                offsety = offsety - 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("销售类型:{0}", settleType), 12, offsety, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("供应商编号:{0}", pmain.merchantId), col2x,
                                       offsety, 0);

                string dcid = Utility.ToString(pmain.stockId);
                tab_stockinfo stockinfo = _tab_stockinfoRepository.Get(st => st.stockId == dcid);
                string stockaddress = string.Empty;
                string stockcontact = string.Empty;
                if (null != stockinfo)
                {
                    stockaddress = stockinfo.stockAddress;
                    stockcontact = stockinfo.stockContact1 + " " + stockinfo.stockTel;
                }

                offsety = offsety - 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("仓库地址:{0}", stockaddress), 12, offsety, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("供应商名称:{0}", pmain.merchantFullName), col2x,
                                       offsety, 0);

                offsety = offsety - 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("联系人:{0}", stockcontact), 12, offsety, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("供应商地址:{0}", pmain.merchantAddress), col2x,
                                       offsety, 0);


                offsety = offsety - 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT,
                                       string.Format("退货单生成日期:{0}",
                                                     pmain.createdate.HasValue
                                                         ? pmain.createdate.Value.ToString("yyyy.MM.dd")
                                                         : ""), 12,
                                       offsety, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT,
                                       string.Format("供应商联系人:{0}", pmain.contactName + " " + pmain.contactPhone), col2x,
                                       offsety, 0);

                offsety = offsety - 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT,
                                       string.Format("退货截止日期:{0}",
                                                     pmain.validEndDate.HasValue
                                                         ? pmain.validEndDate.Value.ToString("yyyy.MM.dd")
                                                         : ""), 12, offsety, 0);

                if (pmain.orderStatus == (int) WordsEnum.退货单状态_已完成)
                {
                    canvas.ShowTextAligned(Element.ALIGN_LEFT,
                                           string.Format("取货完成日期:{0}",
                                                         pmain.receiverDate.HasValue
                                                             ? pmain.receiverDate.Value.ToString("yyyy.MM.dd")
                                                             : ""), col2x,
                                           offsety, 0);
                }
                else
                {
                    canvas.ShowTextAligned(Element.ALIGN_LEFT,
                                           string.Format("打印日期:{0}", DateTime.Today.ToString("yyyy.MM.dd")), col2x,
                                           offsety, 0);
                }


                string takeType = Utility.ToString(pmain.takeType);
                if (!string.IsNullOrEmpty(takeType))
                {
                    string type = takeType;
                    tab_wordsconfig words = _tab_wordsconfigRepository.Get(
                        w => w.belongedId == (int) WordsEnum.取货方式 && w.wordsvalue == type);

                    takeType = null != words ? words.wordscontent : "";
                }

                offsety = offsety - 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("取货方式:{0}", takeType), 12, offsety, 0);

                if (pmain.orderStatus == (int) WordsEnum.退货单状态_已完成)
                {
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("物流公司:{0}", pmain.shippingCompany), 160,
                                           offsety, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("运单号:{0}", pmain.expressNo), 260, offsety,
                                           0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT,
                                           string.Format("称重:{0}千克",
                                                         (pmain.goodsWight.HasValue
                                                              ? pmain.goodsWight.Value.ToString("F2")
                                                              : "0.00")), 360, offsety, 0);
                }
                canvas.EndText();
                canvas.RestoreState();

                #region title table Info

                var table = new PdfPTable(4);
                var colwidth = new[] {70f, 70f, 70f, 160f};
                var cols = new[]
                               {
                                   "", "姓名", "日期", "有效证件号", "仓库发货人", "", "", "", "商家提货人", "", "", ""
                               };
                table.SetTotalWidth(colwidth);
                table.HorizontalAlignment = Element.ALIGN_CENTER;

                table.DefaultCell.Padding = 3;
                var font = new Font(basefont, 11);
                PdfPCell cell = null;
                foreach (string col in cols)
                {
                    cell = new PdfPCell(new Phrase(col, font));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(cell);
                }

                table.CompleteRow();
                table.WriteSelectedRows(0, -1, pwidth/2 + 25, pheight - 25, canvas);

                #endregion

                #endregion

                #region 明细数据

                int colnum = pmain.orderStatus == (int) WordsEnum.退货单状态_已完成 ? 12 : 13;
                table = new PdfPTable(colnum);

                cell = null;
                cols = new[]
                           {
                               "序号", "物品ID", "国标码", "店内码", "商品名称", "规格/颜色", "供货价(含税)", "税率", "箱装数量", "退货数量", "订单金额",
                               "备注"
                           };
                colwidth = new[] {28f, 50f, 75f, 75f, 190f, 100f, 40f, 35f, 35f, 40f, 80f, 70f};

                if (pmain.orderStatus != (int) WordsEnum.退货单状态_已完成)
                {
                    cols = new[]
                               {
                                   "序号", "物品ID", "国标码", "店内码", "商品名称", "规格/颜色", "供货价(含税)", "税率", "箱装数量", "退货数量", "订单金额",
                                   "实退数", "备注"
                               };
                    colwidth = new[] { 28f, 50f, 75f, 75f, 180f, 100f, 40f, 35f, 35f, 40f, 60f, 40f, 65f };
                }

                table.SetTotalWidth(colwidth);
                table.HorizontalAlignment = Element.ALIGN_CENTER;

                table.DefaultCell.Padding = 3;
                font = new Font(basefont, 11);
                foreach (string col in cols)
                {
                    cell = new PdfPCell(new Phrase(col, font));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(cell);
                }

                int refundNum = 0; //退货总数量
                double realamount = 0; //退货总金额
                int page = 1;
                offsety = offsety - 7;
                for (int rowidnex = 0; rowidnex < pinfoList.Count; rowidnex++)
                {
                    if (page == 1)
                    {
                        if (table.TotalHeight > offsety - 20)
                        {
                            table.CompleteRow();
                            table.WriteSelectedRows(0, -1, 12, offsety, canvas);

                            document.NewPage();
                            //============
                            table = new PdfPTable(colnum);
                            table.SetTotalWidth(colwidth);
                            table.HorizontalAlignment = Element.ALIGN_CENTER;

                            table.DefaultCell.Padding = 3;
                            font = new Font(basefont, 11);
                            foreach (string col in cols)
                            {
                                cell = new PdfPCell(new Phrase(col, font));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.VerticalAlignment = Element.ALIGN_CENTER;
                                table.AddCell(cell);
                            }
                            //=============================
                            page++;
                            offsety = pheight - 5;
                        }
                    }
                    else
                    {
                        if (table.TotalHeight > pheight - 20)
                        {
                            table.CompleteRow();
                            table.WriteSelectedRows(0, -1, 12, offsety, canvas);
                            document.NewPage();
                            //============
                            table = new PdfPTable(colnum);
                            table.SetTotalWidth(colwidth);
                            table.HorizontalAlignment = Element.ALIGN_CENTER;

                            table.DefaultCell.Padding = 3;
                            font = new Font(basefont, 11);
                            foreach (string col in cols)
                            {
                                cell = new PdfPCell(new Phrase(col, font));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.VerticalAlignment = Element.ALIGN_CENTER;
                                table.AddCell(cell);
                            }
                            //=============================
                            page++;
                            offsety = pheight - 5;
                        }
                    }
                    double purchaseprice = 0;
                    int amt = 0;
                    tab_purchaseinfo pinfo = pinfoList[rowidnex];
                    for (int colindex = 1; colindex <= cols.Length; colindex++)
                    {
                     
                        switch (colindex)
                        {
                            case 1:
                                {
                                    cell = new PdfPCell(new Phrase(Utility.ToString(rowidnex + 1), font));
                                }
                                break;
                            case 2:
                                {
                                    cell = new PdfPCell(new Phrase(Utility.ToString(pinfo.itemId), font));
                                }
                                break;
                            case 3:
                                {
                                    cell = new PdfPCell(new Phrase(pinfo.itemUPC, font));
                                }
                                break;
                            case 4:
                                {
                                    cell = new PdfPCell(new Phrase(pinfo.storeCode, font));
                                }
                                break;
                            case 5:
                                {
                                    cell = new PdfPCell(new Phrase(pinfo.itemName, font));
                                }
                                break;
                            case 6:
                                {
                                    cell = new PdfPCell(new Phrase(pinfo.itemAttribute, font));
                                }
                                break;
                            case 7:
                                {
                                    if (pinfo.purchasePrice.HasValue)
                                    {
                                        purchaseprice = pinfo.purchasePrice.Value;
                                    }

                                    cell = new PdfPCell(new Phrase(purchaseprice.ToString("N2"), font));
                                }

                                break;
                            case 8:
                                {
                                    cell = new PdfPCell(new Phrase(pinfo.taxRate, font));
                                }
                                break;
                            case 9:
                                {
                                    int packageamount = Utility.ToInt(pinfo.packageAmount, 0).Value;

                                    cell = new PdfPCell(new Phrase(packageamount.ToString("N0"), font));
                                }

                                break;
                            case 10:
                                {
                                    if (pmain.orderStatus == (int) WordsEnum.退货单状态_已完成)
                                    {
                                        amt = Utility.ToInt(pinfo.receiveAmount, 0).Value;
                                    }
                                    else if (pmain.orderStatus == (int) WordsEnum.退货单状态_备货完成)
                                    {
                                        amt = Utility.ToInt(pinfo.prepareAmount, 0).Value;
                                    }

                                    cell = new PdfPCell(new Phrase(amt.ToString("N0"), font));
                                }

                                break;
                            case 11:
                                {
                                    refundNum += amt;
                                    realamount += purchaseprice*amt;
                                    double orderamount = purchaseprice*amt;
                                    cell = new PdfPCell(new Phrase(orderamount.ToString("N2"), font));
                                }
                                break;
                            case 12:
                            {
                                    if (pmain.orderStatus == (int) WordsEnum.退货单状态_备货完成)
                                    {
                                        int receiveAmount = Utility.ToInt(pinfo.receiveAmount, 0).Value;

                                        cell = new PdfPCell(new Phrase(receiveAmount>0?receiveAmount.ToString("N0"):"", font));
                                    }else
                                    {
                                        cell = new PdfPCell(new Phrase(pinfo.purchaseNotes, font));
                                    }
                            }
                            break;
                            case 13:
                            {
                                if (pmain.orderStatus == (int)WordsEnum.退货单状态_备货完成)
                                {
                                    cell = new PdfPCell(new Phrase(pinfo.purchaseNotes, font));
                                }
                                else
                                {
                                    cell = null;
                                }
                             
                            }
                            break;
                              
                        }

                        if (null != cell)
                        {
                            cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            cell.VerticalAlignment = Element.ALIGN_CENTER;
                            table.AddCell(cell);
                        }
                    }
                }

                //for (int i = 0; i < pinfoList.Count; i++)
                //{
                //    for (int j = 0; j < cols.Length; j++)
                //    {
                //      cell=  table.GetRow(i).GetCells()[j];
                //      cell.HorizontalAlignment = Element.ALIGN_CENTER;
                //      cell.VerticalAlignment = Element.ALIGN_CENTER;
                //    }
                //}
                cell =
                    new PdfPCell(new Phrase(string.Format("退货总数量:{0:N0};退货总金额:¥{1:N2}", refundNum, realamount), font));
                cell.Colspan = pmain.orderStatus == (int)WordsEnum.退货单状态_已完成 ? 12 : 13;
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                table.AddCell(cell);

                table.CompleteRow();
                table.WriteSelectedRows(0, -1, 10, offsety, canvas);
                offsety -= table.TotalHeight;
                //table.CompleteRow();
                //offsety = pheight - 185;
                //table.WriteSelectedRows(0, -1, 12, offsety, canvas);

                #endregion

                canvas.SaveState();
                canvas.BeginText();
                canvas.SetFontAndSize(basefont, 11);

                //offsety = pheight - 200 - table.TotalHeight;
                offsety -= 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("备注:{0}", pmain.remark), 12,
                                       offsety, 0);

                #region 读取notes

                try
                {
                    using (var dr = new StreamReader(notespath, Encoding.UTF8))
                    {
                        offsety = offsety - 15;
                        string nodes = dr.ReadLine();
                         while (null != nodes)
                        {
                            if (!string.IsNullOrEmpty(nodes))
                            {
                                offsety = offsety - 15f;

                                if (offsety < 15)
                                {
                                    canvas.EndText();
                                    canvas.RestoreState();

                                    document.NewPage();
                                    canvas.SaveState();
                                    canvas.BeginText();
                                    canvas.SetFontAndSize(basefont, 11);
                                    offsety = pheight - 30;
                                }
                                canvas.ShowTextAligned(Element.ALIGN_LEFT, nodes, 12,
                                                       offsety, 0);
                            }

                            nodes = dr.ReadLine();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Mylogger.Info("export pdf notes 读取异常:" + Common.GetExceptionMessage(ex));
                }

                #endregion

                canvas.EndText();
                canvas.RestoreState();
                document.Close();
                Mylogger.Info(string.Format("单据{0}pdf文件生成完成", pmain.purchaseOrderId));
                result = true;
            }
            catch (Exception ex)
            {
                Mylogger.Info(string.Format("{0}生成pdf异常:{1}", pmain.purchaseOrderId, Common.GetExceptionMessage(ex)));
                result = false;
            }
            return result;
        }

        /// <summary>
        /// PO单pdf生成
        /// </summary>
        /// <param name="pmain"></param>
        /// <param name="pinfoList"></param>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static bool ExportPoPdf(tab_purchaselist pmain, List<tab_purchaseinfo> pinfoList, out string filepath)
        {
            bool result = false;
            filepath = string.Empty;
            if (null == pmain || pinfoList.Count < 1)
            {
                Mylogger.Info("ExportPdf 无数据不导出pdf");
                return false;
            }

            if (string.IsNullOrEmpty(basePoDir))
            {
                Mylogger.Info(" ExportPdf basePoDir为空");
                return false;
            }

            try
            {
                if(!pmain.createdate.HasValue)
                {
                    Mylogger.Info(" ExportPdf createdate为空");
                    return false;
                }
                DateTime createtime = pmain.createdate.Value;
                string directory = Path.Combine(basePoDir, createtime.ToString("yyyy"),
                                                createtime.ToString("MM.dd"));

                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                //
                string filepathname = Path.Combine(directory, pmain.purchaseOrderId + ".pdf");
                filepath = filepathname;
                //==============================================================
                string logopath = Path.Combine(basehttpContextDir, "images", "title.jpg");
                string notespath = Path.Combine(basehttpContextDir, "notes.txt");
                //
                Document document = ItextSharpHelper.CreateDocument(PageSize.A4.Rotate());
                PdfWriter writer = ItextSharpHelper.GetPdfWriter(document, filepathname);
                BaseFont basefont = ItextSharpHelper.CreateChineseFont();
                float pwidth = document.PageSize.Width;
                float pheight = document.PageSize.Height;
                float offsetx = 10f;
                float offsety = pheight;
                document.Open();
                PdfContentByte canvas = writer.DirectContent;
                writer.CompressionLevel = 0;

                #region Titles

                canvas.SaveState();
                canvas.BeginText();

                offsety = offsety - 40;
                canvas.SetFontAndSize(basefont, 18);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, "商品采购订单", pwidth/2 - 70, offsety, 0);


                //Logo
                Image imgLogo = Image.GetInstance(System.Drawing.Image.FromFile(logopath), ImageFormat.Png);

                offsety = offsety - 10;
                imgLogo.SetAbsolutePosition(15, offsety);
                imgLogo.ScalePercent(80);
                canvas.AddImage(imgLogo);

                //bar
                Image imgbar = Image.GetInstance(BarCode39.GetCode39(pmain.purchaseOrderId), ImageFormat.Png);
                offsety = offsety - 30;
                imgbar.SetAbsolutePosition(10, offsety);
                imgbar.ScalePercent(100);
                canvas.AddImage(imgbar);


                canvas.SetFontAndSize(basefont, 11);
                offsety = offsety - 20;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("订单号:{0}", pmain.purchaseOrderId), 12,
                                       offsety, 0);
                string validPeriod = string.Empty;
                if (pmain.validStartDate.HasValue)
                    validPeriod = pmain.validStartDate.Value.ToString("yyyy.MM.dd");
                if (pmain.validEndDate.HasValue)
                    validPeriod += "-" + pmain.validEndDate.Value.ToString("yyyy.MM.dd");
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("订单有效期:{0}", validPeriod), 400, pheight - 100,
                                       0);

                offsety = offsety - 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("订购公司:{0}", company), 12, offsety, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("供应商编号:{0}", pmain.merchantId), 400,
                                       offsety, 0);

                string telphone = string.Empty;
                if (!string.IsNullOrEmpty(pmain.createUserName) || !string.IsNullOrEmpty(pmain.applyUser))
                {
                    var userinfo = new tab_userinfo();
                    if (!string.IsNullOrEmpty(pmain.createUserName))
                    {
                        userinfo = _tab_userinfoRepository.Get(u => u.username == pmain.createUserName);
                    }
                    else if (!string.IsNullOrEmpty(pmain.applyUser))
                    {
                        userinfo = _tab_userinfoRepository.Get(u => u.useremail == pmain.applyUser);
                    }

                    if (null != userinfo && !string.IsNullOrEmpty(userinfo.persontel))
                    {
                        telphone = companyTel + "*" + userinfo.persontel;
                    }
                }

                offsety = offsety - 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("联系电话:{0}", telphone), 12, offsety, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("供应商名称:{0}", pmain.merchantFullName), 400,
                                       offsety, 0);

                string dcid = Utility.ToString(pmain.stockId);
                tab_stockinfo stockinfo = _tab_stockinfoRepository.Get(st => st.stockId == dcid);
                string stockaddress = string.Empty;
                string stockcontact = string.Empty;
                if (null != stockinfo)
                {
                    stockaddress = stockinfo.stockAddress;
                    stockcontact = stockinfo.stockContact + " " + stockinfo.stockTel;
                }
                offsety = offsety - 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("仓库地址:{0}", stockaddress), 12, offsety, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("供应商地址:{0}", pmain.merchantAddress), 400,
                                       offsety, 0);

                offsety = offsety - 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("联系人:{0}", stockcontact), 12, offsety, 0);
                canvas.ShowTextAligned(Element.ALIGN_LEFT,
                                       string.Format("供应商联系人:{0}", pmain.contactName + " " + pmain.contactPhone), 400,
                                       offsety, 0);

                string listingtype = Utility.ToString(pmain.listingType);
                if (!string.IsNullOrEmpty(listingtype))
                {
                    tab_wordsconfig words = _tab_wordsconfigRepository.Get(
                        w => w.belongedId == (int) WordsEnum.顾客类型 && w.wordsvalue == (listingtype));

                    listingtype = null != words ? words.wordscontent : "";
                }

                offsety = offsety - 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("顾客类型:{0}", listingtype), 12, offsety, 0);
                canvas.EndText();
                canvas.RestoreState();

                #endregion

                #region 明细数据

                var table = new PdfPTable(13);

                PdfPCell cell = null;
                var cols = new[]
                               {
                                   "序号", "物品ID", "国标码", "店内码", "商品名称", "规格/颜色", "供货价(含税)", "税率", "箱装数量", "订货数量", "订单金额",
                                   "实收数", "备注"
                               };
                var colwidth = new[] {28f, 50f, 75f, 75f, 185f, 100f, 40f, 35f, 35f, 40f, 60f, 40f, 50f};

                table.SetTotalWidth(colwidth);
                table.HorizontalAlignment = Element.ALIGN_CENTER;

                table.DefaultCell.Padding = 3;
                var font = new Font(basefont, 11);
                foreach (string col in cols)
                {
                    cell = new PdfPCell(new Phrase(col, font));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(cell);
                }

                double amount = 0; //订单总金额
                double realamount = 0; //实际订单总金额
                int page = 1;
                offsety = offsety - 7;
                for (int rowidnex = 0; rowidnex < pinfoList.Count; rowidnex++)
                {
                    if (page == 1)
                    {
                        if (table.TotalHeight > offsety - 20)
                        {
                            table.CompleteRow();
                            table.WriteSelectedRows(0, -1, 12, offsety, canvas);

                            document.NewPage();
                            //============
                            table = new PdfPTable(13);
                            table.SetTotalWidth(colwidth);
                            table.HorizontalAlignment = Element.ALIGN_CENTER;

                            table.DefaultCell.Padding = 3;
                            font = new Font(basefont, 11);
                            foreach (string col in cols)
                            {
                                cell = new PdfPCell(new Phrase(col, font));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.VerticalAlignment = Element.ALIGN_CENTER;
                                table.AddCell(cell);
                            }
                            //=============================
                            page++;
                            offsety = pheight - 5;
                        }
                    }
                    else
                    {
                        if (table.TotalHeight > pheight - 20)
                        {
                            table.CompleteRow();
                            table.WriteSelectedRows(0, -1, 12, offsety, canvas);
                            document.NewPage();
                            //============
                            table = new PdfPTable(13);
                            table.SetTotalWidth(colwidth);
                            table.HorizontalAlignment = Element.ALIGN_CENTER;

                            table.DefaultCell.Padding = 3;
                            font = new Font(basefont, 11);
                            foreach (string col in cols)
                            {
                                cell = new PdfPCell(new Phrase(col, font));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.VerticalAlignment = Element.ALIGN_CENTER;
                                table.AddCell(cell);
                            }
                            //=============================
                            page++;
                            offsety = pheight - 5;
                        }
                    }

                    tab_purchaseinfo pinfo = pinfoList[rowidnex];
                    for (int colindex = 1; colindex <= cols.Length; colindex++)
                    {
                        switch (colindex)
                        {
                            case 1:
                                {
                                    cell = new PdfPCell(new Phrase(Utility.ToString(rowidnex + 1), font));
                                }
                                break;
                            case 2:
                                {
                                    cell = new PdfPCell(new Phrase(Utility.ToString(pinfo.itemId), font));
                                }
                                break;
                            case 3:
                                {
                                    cell = new PdfPCell(new Phrase(pinfo.itemUPC, font));
                                }
                                break;
                            case 4:
                                {
                                    cell = new PdfPCell(new Phrase(pinfo.storeCode, font));
                                }
                                break;
                            case 5:
                                {
                                    cell = new PdfPCell(new Phrase(pinfo.itemName, font));
                                }
                                break;
                            case 6:
                                {
                                    cell = new PdfPCell(new Phrase(pinfo.itemAttribute, font));
                                }
                                break;
                            case 7:
                                {
                                    double purchaseprice = 0;

                                    if (pinfo.purchasePrice.HasValue)
                                    {
                                        purchaseprice = pinfo.purchasePrice.Value;
                                    }

                                    amount += purchaseprice*Utility.ToInt(pinfo.bookAmount, 0).Value;
                                    realamount += purchaseprice*Utility.ToInt(pinfo.receiveAmount, 0).Value;

                                    cell = new PdfPCell(new Phrase(purchaseprice.ToString("N2"), font));
                                }

                                break;
                            case 8:
                                {
                                    cell = new PdfPCell(new Phrase(pinfo.taxRate, font));
                                }
                                break;
                            case 9:
                                {
                                    int packageamount = Utility.ToInt(pinfo.packageAmount, 0).Value;

                                    cell = new PdfPCell(new Phrase(packageamount.ToString("N0"), font));
                                }

                                break;
                            case 10:
                                {
                                    int bookAmount = Utility.ToInt(pinfo.bookAmount, 0).Value;

                                    cell = new PdfPCell(new Phrase(bookAmount.ToString("N0"), font));
                                }

                                break;
                            case 11:
                                {
                                    double orderAmount = 0;

                                    if (pinfo.orderAmount.HasValue)
                                        orderAmount = pinfo.orderAmount.Value;

                                    cell = new PdfPCell(new Phrase(orderAmount.ToString("N2"), font));
                                }

                                break;
                            case 12:
                                {
                                    int receiveAmount = Utility.ToInt(pinfo.receiveAmount, 0).Value;

                                    cell = new PdfPCell(new Phrase(receiveAmount.ToString("N0"), font));
                                }
                                break;
                            case 13:
                                {
                                    cell = new PdfPCell(new Phrase(pinfo.purchaseNotes, font));
                                }
                                break;
                        }

                        if (null != cell)
                        {
                            cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            cell.VerticalAlignment = Element.ALIGN_CENTER;
                            table.AddCell(cell);
                        }
                    }
                }

                //for (int i = 0; i < pinfoList.Count; i++)
                //{
                //    for (int j = 0; j < cols.Length; j++)
                //    {
                //      cell=  table.GetRow(i).GetCells()[j];
                //      cell.HorizontalAlignment = Element.ALIGN_CENTER;
                //      cell.VerticalAlignment = Element.ALIGN_CENTER;
                //    }
                //}
                cell = new PdfPCell(new Phrase(string.Format("订单总金额:¥{0:N2};订单实际总金额:¥{1:N2}", amount, realamount), font));
                cell.Colspan = 13;
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                table.AddCell(cell);

                table.CompleteRow();
                table.WriteSelectedRows(0, -1, 12, offsety, canvas);
                offsety -= table.TotalHeight;
                //table.CompleteRow();
                //offsety = pheight - 185;
                //table.WriteSelectedRows(0, -1, 12, offsety, canvas);

                #endregion

                canvas.SaveState();
                canvas.BeginText();
                canvas.SetFontAndSize(basefont, 11);

                //offsety = pheight - 200 - table.TotalHeight;
                offsety -= 15;
                canvas.ShowTextAligned(Element.ALIGN_LEFT, string.Format("备注:{0}", pmain.remark), 12,
                                       offsety, 0);

                #region 读取notes

                try
                {
                    using (var dr = new StreamReader(notespath, Encoding.UTF8))
                    {
                        offsety = offsety - 15;
                        string nodes = dr.ReadLine();
                        while (null != nodes)
                        {
                            if (!string.IsNullOrEmpty(nodes))
                            {
                                offsety = offsety - 15f;

                                if (offsety < 15)
                                {
                                    canvas.EndText();
                                    canvas.RestoreState();

                                    document.NewPage();
                                    canvas.SaveState();
                                    canvas.BeginText();
                                    canvas.SetFontAndSize(basefont, 11);
                                    offsety = pheight - 30;
                                }
                                canvas.ShowTextAligned(Element.ALIGN_LEFT, nodes, 12,
                                                       offsety, 0);
                            }

                            nodes = dr.ReadLine();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Mylogger.Info("export pdf notes 读取异常:" + Common.GetExceptionMessage(ex));
                }

                #endregion

                canvas.EndText();
                canvas.RestoreState();
                document.Close();
                Mylogger.Info(string.Format("单据{0}pdf文件生成完成", pmain.purchaseOrderId));
                result = true;
            }
            catch (Exception ex)
            {
                Mylogger.Info(string.Format("{0}生成pdf异常:{1}", pmain.purchaseOrderId, Common.GetExceptionMessage(ex)));
                result = false;
            }
            return result;
        }
    }
}

 

 

你可能感兴趣的:(itext)