PDF C#操作

一:PDF

1.Adobe Acrobat 8 Professional 可以修改和制作模板

2.向模板插入数据(代码)例子,需要用到itextsharp.dll引用文件

 

using System;
using System.Collections.Generic;
using System.Web;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.pdf;
using System.Data;
using Suryani.Commerce.Core.Common;
using System.Text;
using Suryani.Commerce.Core.Order_Mgmt;
using Diapers.Intranet.Manager;

/// <summary>
/// Summary description for InvoiceEmailGenerator
/// </summary>
public class InvoiceEmailGenerator
{
    private const string DIAPERS_CUSTOMER_TEMPLATE_NAME = "customerEmail_PDF_Invoice_Diapers";
    private const string SOAP_CUSTOMER_TEMPLATE_NAME = "customerEmail_PDF_Invoice_Soap";
    private const string BEAUTYBAR_CUSTOMER_TEMPLATE_NAME = "customerEmail_PDF_Invoice_BeautyBar";
    private const string WAG_CUSTOMER_TEMPLATE_NAME = "customerEmail_PDF_Invoice_Wag";
    private const string YOYO_CUSTOMER_TEMPLATE_NAME = "customerEmail_PDF_Invoice_Yoyo";
    private const string CASA_CUSTOMER_TEMPLATE_NAME = "customerEmail_PDF_Invoice_Casa";
    private const string USER_TEMPLATE_NAME = "1800diapers_PdfInvoiceForUser";
    private const string USER_TEMPLATE_NAME_POREINVOICE = "customerEmail_PDF_Invoice_PoOrder";
    private int CatalogID = 1;  //default is diapers
    private int SentTime = 1;  //default is diapers
    public InvoiceEmailGenerator()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    /// <summary>
    /// this function is for send invoice for customer
    /// </summary>
    /// <param name="orderId"></param>
    /// <param name="email"></param>
    /// <param name="templatePath"></param>
    /// <param name="isSendToCustomer"></param>
    /// <param name="shipmentId"></param>
    /// <returns></returns>
    public string GenerateAndSendInvoiceEmail(int orderId, string email, string templatePath, bool isSendToCustomer, int shipmentId,string dueDate)
    {
        if (orderId != -1 && !string.IsNullOrEmpty(email))
        {
            CatalogID = GetOrderCatalog(orderId);
            SentTime = GetPoOrderInvoiceTimes(orderId);
            //get catalog info
            DataTable catalog = new CatalogManager().GetAllCatalog();
            DataRow[] row = catalog.Select("CatalogId='" + CatalogID + "'");
            string contractPhoneInfo =row[0]["AddressToName"].ToString()+": " + row[0]["ShipperPhone"].ToString();
            string catalogName = row[0]["catalogName"].ToString();

            string fileName = "InvoiceTemplate" + System.DateTime.Now.Millisecond.ToString() + new Random().Next().ToString() + ".pdf";
            //sendResultLable.InnerText = "";
            Suryani.Commerce.Core.Order_Mgmt.Order order = new Suryani.Commerce.Core.Order_Mgmt.Order_Manager().GetOrder(orderId);
            string trackingNumber = string.Empty;
            bool isNotPaid = CheckPOOrderPaid(order);
            if (order != null && order.OrderItems != null && order.OrderItems.Rows.Count > 0)
            {
                Document document = null;
                FileStream invoicePdfStream = null;
                PdfCopy copy = null;
                PdfReader template1 = null;
                PdfReader template2_1 = null;
                PdfReader template2_2 = null;
                PdfStamper stamper = null;
                AcroFields fields = null;
                document = new Document();
                invoicePdfStream = new FileStream(string.Format("{0}\\{1}", templatePath, fileName), FileMode.Create);
                copy = new PdfCopy(document, invoicePdfStream);
                copy.SetFullCompression();
                copy.CloseStream = true;
                document.Open();
                //judge orderitems first,if the num of orderItems less than 16,we use template1
                //or we use template 2_1(29 rows) and template 2_2(15 rows), and how many template 2_1 will used result with this num.
                if (order.OrderItems.Rows.Count <= 16)
                {
                    template1 = GetTemplateByCatalogId(templatePath, 1);// new PdfReader(string.Format("{0}\\InvoiceTemplate1.pdf", templatePath));
                    MemoryStream invoiceStream = new MemoryStream();
                    stamper = new PdfStamper(template1, invoiceStream);
                    stamper.SetFullCompression();
                    fields = stamper.AcroFields;
                    if (order.OrderShippings != null && order.OrderShippings.Length > 0)
                    {
                        FillBillToAndShipTo(order, fields, contractPhoneInfo, dueDate, SentTime);
                        //Order List
                        int rowIndex = 0;
                        foreach (DataRow orderItem in order.OrderItems.Rows)
                        {
                            FillOneOrderItem(fields, rowIndex, orderItem);
                            rowIndex++;
                        }
                        FillTotal(order, fields,catalogName,dueDate);
                    }
                    stamper.FormFlattening = true;
                    stamper.Close();
                    template1 = new PdfReader(invoiceStream.ToArray());
                    template1.RemoveUnusedObjects();
                    copy.AddPage(copy.GetImportedPage(template1, 1));
                }
                else
                {
                    template2_1 = GetTemplateByCatalogId(templatePath, 2);// new PdfReader(string.Format("{0}\\InvoiceTemplate2_1.pdf", templatePath));
                    template2_2 = GetTemplateByCatalogId(templatePath, 3);// new PdfReader(string.Format("{0}\\InvoiceTemplate2_2.pdf", templatePath));
                    int template2_1Num = order.OrderItems.Rows.Count / 29;
                    bool isNeedReserve = false;
                    if (order.OrderItems.Rows.Count % 29 > 15)
                    {
                        template2_1Num += 1;
                        isNeedReserve = true;
                    }
                    if (order.OrderItems.Rows.Count % 29 == 0)
                    {
                        isNeedReserve = true;
                    }
                    int totalItemsOfTemp2_1 = order.OrderItems.Rows.Count;
                    if (isNeedReserve)
                    {
                        totalItemsOfTemp2_1 -= 2;
                    }
                    for (int i = 0; i < template2_1Num; i++)  //how many template2_1 will used
                    {
                        template2_1 = GetTemplateByCatalogId(templatePath, 2);
                        MemoryStream template2_1InvoiceStream = new MemoryStream();
                        stamper = new PdfStamper(template2_1, template2_1InvoiceStream);
                        stamper.SetFullCompression();
                        //begin to fill fields
                        fields = stamper.AcroFields;
                        if (order.OrderShippings != null && order.OrderShippings.Length > 0)
                        {
                            FillBillToAndShipTo(order, fields, contractPhoneInfo, dueDate, SentTime);
                            //Order List
                            int rowIndex = 0;
                            int pageNst = i * 29;
                            for (int j = i * 29; j < (pageNst + 29) && j < totalItemsOfTemp2_1; j++)
                            {
                                DataRow orderItem = order.OrderItems.Rows[j];
                                FillOneOrderItem(fields, rowIndex, orderItem);
                                rowIndex++;
                            }
                            fields.SetField("CurrentPage", (i + 1).ToString());
                            fields.SetField("TotalPage", (template2_1Num + 1).ToString());
                        }
                        stamper.FormFlattening = true;
                        stamper.Close();
                        template2_1 = new PdfReader(template2_1InvoiceStream.ToArray());
                        template2_1.RemoveUnusedObjects();
                        copy.AddPage(copy.GetImportedPage(template2_1, 1));
                    }
                    //one template2_2 will used
                    MemoryStream template2_2InvoiceStream = new MemoryStream();
                    stamper = new PdfStamper(template2_2, template2_2InvoiceStream);
                    stamper.SetFullCompression();
                    fields = stamper.AcroFields;
                    if (order.OrderShippings != null && order.OrderShippings.Length > 0)
                    {
                        FillBillToAndShipTo(order, fields, contractPhoneInfo, dueDate, SentTime);
                        //Order List
                        if (order.OrderItems.Rows.Count % 29 <= 15 && order.OrderItems.Rows.Count % 29 > 0)
                        {
                            int rowIndex = order.OrderItems.Rows.Count % 29 - 1;
                            int lastRowIndex = order.OrderItems.Rows.Count - 1;
                            if (rowIndex >= 0)
                            {
                                for (int k = rowIndex; k >= 0; k--)
                                {
                                    DataRow orderItem = order.OrderItems.Rows[lastRowIndex];
                                    FillOneOrderItem(fields, rowIndex, orderItem);
                                    rowIndex--;
                                    lastRowIndex--;
                                }
                            }
                        }
                        else  //reserve 2 records for InvoiceTemplate2_2
                        {
                            int rowIndex = 0;
                            for (int i = order.OrderItems.Rows.Count - 2; i < order.OrderItems.Rows.Count; i++)
                            {
                                DataRow orderItem = order.OrderItems.Rows[i];
                                FillOneOrderItem(fields, rowIndex, orderItem);
                                rowIndex++;
                            }
                        }
                        fields.SetField("CurrentPage", (template2_1Num + 1).ToString());
                        fields.SetField("TotalPage", (template2_1Num + 1).ToString());
                        FillTotal(order, fields,catalogName,dueDate);
                    }
                    stamper.FormFlattening = true;
                    stamper.Close();
                    template2_2 = new PdfReader(template2_2InvoiceStream.ToArray());
                    template2_2.RemoveUnusedObjects();
                    copy.AddPage(copy.GetImportedPage(template2_2, 1));
                }

                document.Close();
                if (invoicePdfStream != null)
                {
                    invoicePdfStream.Close();
                }
                if (template1 != null)
                {
                    template1.Close();
                }
                if (template2_1 != null)
                {
                    template2_1.Close();
                }
                if (template2_2 != null)
                {
                    template2_2.Close();
                }

                bool isSuccess = SendEmail(fileName, email, templatePath, isSendToCustomer, orderId, shipmentId, CatalogID, SentTime);
                if (isSuccess)
                {
                    new Order_Manager().UpdatePoInvoiceTimes(orderId, SiCommerce.Intranet.Security.Secure.GetUserName());
                    return "Invoice email has been sent.";
                }
                else
                {
                    return "Customer invoice template lost.";
                }
            }
            else
            {
                throw new Exception("No order item to print.");
            }
        }
        return "";
    }

    private bool CheckPOOrderPaid(Suryani.Commerce.Core.Order_Mgmt.Order order)
    {
        if (order.GL.ToUpper() == "PO" || (order.OrderShippings[0].PaymentInfo != null && order.OrderShippings[0].PaymentInfo.IsPO.Trim().ToUpper() == "Y"))
        {
            if (order.OrderShippings[0].PaymentInfo.Paid == "N")
            {
                return true;
            }
        }
        return false;
    }

    private static void FillBillToAndShipTo(Suryani.Commerce.Core.Order_Mgmt.Order order, AcroFields fields, string contractPhoneInfo,string dueDate,int times)
    {
        fields.SetField("ContractNumber", contractPhoneInfo);
        fields.SetField("InvoiceDate", string.Format("{0:d}", Convert.ToDateTime(order.OrderDate)));
        fields.SetField("InvoiceNumber", order.OrderId.ToString());
        fields.SetField("PONumber", order.OrderShippings[0].ShippingInfo.PO);
        if (times==2)
        {
            fields.SetField("SecondCopy","2nd COPY");
            //fields.SetField("SecondCopy", times.ToString()+"nd COPY");
        }
        else if (times == 3)
        {
            fields.SetField("SecondCopy", "3rd COPY");
            //fields.SetField("SecondCopy", times.ToString()+"nd COPY");
        }
        else if (times >3)
        {
            fields.SetField("SecondCopy", times.ToString() + "th COPY");
        }
        else
        {
            fields.SetField("SecondCopy", " ");
        }
        if (string.IsNullOrEmpty(dueDate))
        {
            dueDate = new Suryani.Commerce.Core.Order_Mgmt.Order_Manager().GetDueDateByOrderId(order.OrderId);
            if (string.IsNullOrEmpty(dueDate))
                dueDate = "Upon Receipt";
        }
        fields.SetField("DueDate", dueDate);
        //Bill To
        int index = 0;
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToName))
        {
            fields.SetField("BillTo" + index, order.OrderShippings[0].PaymentInfo.BillToName);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToAddress1))
        {
            fields.SetField("BillTo" + index, order.OrderShippings[0].PaymentInfo.BillToAddress1);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToAddress2))
        {
            fields.SetField("BillTo" + index, order.OrderShippings[0].PaymentInfo.BillToAddress2);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToAddress3))
        {
            fields.SetField("BillTo" + index, order.OrderShippings[0].PaymentInfo.BillToAddress3);
            index++;
        }
        StringBuilder cityStateZipStringBuilder = new StringBuilder();
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToCity))
        {
            cityStateZipStringBuilder.Append(order.OrderShippings[0].PaymentInfo.BillToCity);
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToState))
        {
            if (cityStateZipStringBuilder.Length > 0)
            {
                cityStateZipStringBuilder.Append(", ");
            }
            cityStateZipStringBuilder.Append(order.OrderShippings[0].PaymentInfo.BillToState);
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToZIP))
        {
            if (cityStateZipStringBuilder.Length > 0)
            {
                cityStateZipStringBuilder.Append(" ");
            }
            cityStateZipStringBuilder.Append(order.OrderShippings[0].PaymentInfo.BillToZIP);
        }
        if (cityStateZipStringBuilder.Length > 0)
        {
            fields.SetField("BillTo" + index, cityStateZipStringBuilder.ToString());
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToCountryCode))
        {
            fields.SetField("BillTo" + index, order.OrderShippings[0].PaymentInfo.BillToCountryCode);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.Phone))
        {
            fields.SetField("BillTo" + index, "Phone: " + order.OrderShippings[0].PaymentInfo.Phone);
        }

        //Ship TO
        index = 0;
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.RecipientName))
        {
            fields.SetField("ShipTo" + index, order.OrderShippings[0].ShippingInfo.RecipientName);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingAddr1))
        {
            fields.SetField("ShipTo" + index, order.OrderShippings[0].ShippingInfo.ShippingAddr1);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingAddr2))
        {
            fields.SetField("ShipTo" + index, order.OrderShippings[0].ShippingInfo.ShippingAddr2);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingAddr3))
        {
            fields.SetField("ShipTo" + index, order.OrderShippings[0].ShippingInfo.ShippingAddr3);
            index++;
        }
        cityStateZipStringBuilder = new StringBuilder();
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingCity))
        {
            cityStateZipStringBuilder.Append(order.OrderShippings[0].ShippingInfo.ShippingCity);
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingState))
        {
            if (cityStateZipStringBuilder.Length > 0)
            {
                cityStateZipStringBuilder.Append(", ");
            }
            cityStateZipStringBuilder.Append(order.OrderShippings[0].ShippingInfo.ShippingState);
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingZip))
        {
            if (cityStateZipStringBuilder.Length > 0)
            {
                cityStateZipStringBuilder.Append(" ");
            }
            cityStateZipStringBuilder.Append(order.OrderShippings[0].ShippingInfo.ShippingZip);
        }
        if (cityStateZipStringBuilder.Length > 0)
        {
            fields.SetField("ShipTo" + index, cityStateZipStringBuilder.ToString());
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingCountry))
        {
            fields.SetField("ShipTo" + index, order.OrderShippings[0].ShippingInfo.ShippingCountry);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.DayPhone))
        {
            fields.SetField("ShipTo" + index, "Phone: " + order.OrderShippings[0].ShippingInfo.DayPhone);
        }
    }

    private static void FillOneOrderItem(AcroFields fields, int rowIndex, DataRow orderItem)
    {
        fields.SetField("ItemNo" + rowIndex, orderItem["sku"].ToString());
        fields.SetField("Description" + rowIndex, orderItem["productname"].ToString());
        fields.SetField("QtyOrdered" + rowIndex, orderItem["quantity"].ToString());
        fields.SetField("QtyShipped" + rowIndex, orderItem["shipQty"].ToString());
        fields.SetField("UnitPrice" + rowIndex, string.Format("{0:c}", Convert.ToDouble(orderItem["discountprice"])));
        fields.SetField("Discount" + rowIndex, string.Format("{0:c}", Convert.ToDouble(orderItem["discount"])));
        fields.SetField("Subtotal" + rowIndex, string.Format("{0:c}", Convert.ToDouble(orderItem["Subtotal"]) - Convert.ToDouble(orderItem["discount"])));
    }

    private static void FillTotal(Suryani.Commerce.Core.Order_Mgmt.Order order, AcroFields fields, string catalogName,string dueDate)
    {
        fields.SetField("Subtotal", string.Format("{0:c}", order.TotalAmount - order.Discount));
        fields.SetField("Shipping", string.Format("{0:c}", order.OrderShippings[0].ShippingInfo.ShippingFee));
        fields.SetField("Credit", "-" + string.Format("{0:c}", order.Credit + order.Commission_Credit + order.GCCredit));
        fields.SetField("Coupon", "-" + string.Format("{0:c}", order.CouponValue));
        fields.SetField("GiftCertificate", "-" + string.Format("{0:c}", order.GCCredit));
        fields.SetField("Tax", string.Format("{0:c}", order.Tax));
        fields.SetField("Total", string.Format("{0:c}", order.TotalAmount + order.Tax - order.Credit + order.OrderShippings[0].ShippingInfo.ShippingFee - order.CouponValue - order.Discount - order.GCCredit - order.Commission_Credit));
        if (string.IsNullOrEmpty(dueDate))
        {
            dueDate = new Suryani.Commerce.Core.Order_Mgmt.Order_Manager().GetDueDateByOrderId(order.OrderId);
            if (string.IsNullOrEmpty(dueDate))
                dueDate = "Upon Receipt";
        }
        if (!dueDate.Equals("Paid"))
        {
            fields.SetField("msg1", "Please make check payable to \"Quidsi Retail LLC.\" and send to:");
            fields.SetField("msg2", catalogName);
            fields.SetField("msg3", "ATTN Accounts Receivable");
            fields.SetField("msg4", "10 Exchange PL, 25th FL");
            fields.SetField("msg5", "Jersey City, NJ 07302");
        }
    }

    private bool SendEmail(string fileName, string email, string templatePath, bool isSendToCustomer, int orderId, int shipmentId,int catalogID,int times)
    {
        string subject = string.Empty;
        string body = string.Empty;
        string from = string.Empty;
        if (isSendToCustomer)
        {
            if (times>1)
            {
                DataTable customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(USER_TEMPLATE_NAME_POREINVOICE);
                if (customerTemplate != null && customerTemplate.Rows.Count > 0)
                {
                    string title = new CatalogManager().GetCatalogCode(catalogID);
                    if (!string.IsNullOrEmpty(title))
                    {
                        title = title + ".com";
                    }
                    //if(catalogID==2)
                    //{
                    //    title="Soap.com";
                    //}
                    //else if(catalogID==3)
                    //{
                    //    title="BeautyBar.com";
                    //}
                    //else if(catalogID==4)
                    //{
                    //    title="Wag.com";
                    //}
                    //else if(catalogID==5)
                    //{
                    //    title="Yoyo.com";
                    //}
                    //else
                    //{
                    //    title="Diapers.com";
                    //}
                    from =customerTemplate.Rows[0]["FromEmailAddress"].ToString();
                    subject = customerTemplate.Rows[0]["Subject"].ToString();
                    body = string.Format(customerTemplate.Rows[0]["Body"].ToString(), title);     
                }
            }
            else
            {
            DataTable customerTemplate = GetInvoiceTemplate(catalogID);
            string fromAddres = "";
            if (SiCommerce.Intranet.Security.Secure.IsPOTeam())
            {
                fromAddres = "[email protected]";
            }
            if (customerTemplate != null && customerTemplate.Rows.Count > 0)
            {   
                from = string.IsNullOrEmpty(fromAddres) ? customerTemplate.Rows[0]["FromEmailAddress"].ToString() : fromAddres; ;
                fromAddres=string.IsNullOrEmpty(fromAddres)?customerTemplate.Rows[0]["ReplyTo"].ToString():fromAddres;
                subject = customerTemplate.Rows[0]["Subject"].ToString();
                body = string.Format(customerTemplate.Rows[0]["Body"].ToString(),fromAddres,fromAddres);     
            }
            }
        }
        else
        {
            DataTable userTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(USER_TEMPLATE_NAME);
            string trackingNumber = new Suryani.Commerce.Core.Shipping_Mgmt.ShipmentData().GetTrackingNumberByShipmentId(shipmentId);
            if (userTemplate != null && userTemplate.Rows.Count > 0)
            {
                subject = string.Format(userTemplate.Rows[0]["Subject"].ToString(), orderId.ToString(), trackingNumber);
                body = string.Format(userTemplate.Rows[0]["Body"].ToString(), orderId, trackingNumber);
            }
        }
        if (!string.IsNullOrEmpty(subject) && !string.IsNullOrEmpty(body) && !string.IsNullOrEmpty(from))
        {
            new MailManager().BeginInvoiceSend(from, email, string.Format("{0}\\{1}", templatePath, fileName), subject, body);
            return true;
        }
        return false;
    }

    public string GenerateClaimsInvoice(int orderId, string templatePath, string filePath, string filename)
    {
        if (orderId != -1)
        {
            CatalogID = GetOrderCatalog(orderId);
            SentTime = 1;
            //get catalog info
            DataTable catalog = new CatalogManager().GetAllCatalog();
            DataRow[] row = catalog.Select("CatalogId='" + CatalogID + "'");
            string contractPhoneInfo = row[0]["AddressToName"].ToString() + ": " + row[0]["ShipperPhone"].ToString();
            string catalogName = row[0]["catalogName"].ToString();

            string fileName = filename;
            //sendResultLable.InnerText = "";
            Suryani.Commerce.Core.Order_Mgmt.Order order = new Suryani.Commerce.Core.Order_Mgmt.Order_Manager().GetOrder(orderId);
            string trackingNumber = string.Empty;
            bool isNotPaid = CheckPOOrderPaid(order);
            if (order != null && order.OrderItems != null && order.OrderItems.Rows.Count > 0)
            {
                Document document = null;
                FileStream invoicePdfStream = null;
                PdfCopy copy = null;
                PdfReader template1 = null;
                PdfReader template2_1 = null;
                PdfReader template2_2 = null;
                PdfStamper stamper = null;
                AcroFields fields = null;
                try
                {
                    document = new Document();
                    invoicePdfStream = new FileStream(string.Format("{0}\\{1}", filePath, fileName), FileMode.Create);
                    copy = new PdfCopy(document, invoicePdfStream);
                    copy.SetFullCompression();
                    copy.CloseStream = true;
                    document.Open();
                    //judge orderitems first,if the num of orderItems less than 16,we use template1
                    //or we use template 2_1(29 rows) and template 2_2(15 rows), and how many template 2_1 will used result with this num.
                    if (order.OrderItems.Rows.Count <= 16)
                    {
                        template1 = GetTemplateByCatalogId(templatePath, 1);
                        MemoryStream invoiceStream = new MemoryStream();
                        stamper = new PdfStamper(template1, invoiceStream);
                        stamper.SetFullCompression();
                        fields = stamper.AcroFields;
                        if (order.OrderShippings != null && order.OrderShippings.Length > 0)
                        {
                            FillBillToAndShipTo(order, fields, contractPhoneInfo, "", SentTime);
                            //Order List
                            int rowIndex = 0;
                            foreach (DataRow orderItem in order.OrderItems.Rows)
                            {
                                FillOneOrderItem(fields, rowIndex, orderItem);
                                rowIndex++;
                            }
                            FillTotal(order, fields,catalogName,"");
                        }
                        stamper.FormFlattening = true;
                        stamper.Close();
                        template1 = new PdfReader(invoiceStream.ToArray());
                        template1.RemoveUnusedObjects();
                        copy.AddPage(copy.GetImportedPage(template1, 1));
                    }
                    else
                    {
                        template2_1 = GetTemplateByCatalogId(templatePath, 2);
                        template2_2 = GetTemplateByCatalogId(templatePath, 3);
                        int template2_1Num = order.OrderItems.Rows.Count / 29;
                        bool isNeedReserve = false;
                        if (order.OrderItems.Rows.Count % 29 > 15)
                        {
                            template2_1Num += 1;
                            isNeedReserve = true;
                        }
                        if (order.OrderItems.Rows.Count % 29 == 0)
                        {
                            isNeedReserve = true;
                        }
                        int totalItemsOfTemp2_1 = order.OrderItems.Rows.Count;
                        if (isNeedReserve)
                        {
                            totalItemsOfTemp2_1 -= 2;
                        }
                        for (int i = 0; i < template2_1Num; i++)  //how many template2_1 will used
                        {
                            template2_1 = GetTemplateByCatalogId(templatePath, 2);
                            MemoryStream template2_1InvoiceStream = new MemoryStream();
                            stamper = new PdfStamper(template2_1, template2_1InvoiceStream);
                            stamper.SetFullCompression();
                            //begin to fill fields
                            fields = stamper.AcroFields;
                            if (order.OrderShippings != null && order.OrderShippings.Length > 0)
                            {
                                FillBillToAndShipTo(order, fields, contractPhoneInfo, "",SentTime);
                                //Order List
                                int rowIndex = 0;
                                int pageNst = i * 29;
                                for (int j = i * 29; j < (pageNst + 29) && j < totalItemsOfTemp2_1; j++)
                                {
                                    DataRow orderItem = order.OrderItems.Rows[j];
                                    FillOneOrderItem(fields, rowIndex, orderItem);
                                    rowIndex++;
                                }
                                fields.SetField("CurrentPage", (i + 1).ToString());
                                fields.SetField("TotalPage", (template2_1Num + 1).ToString());
                            }
                            stamper.FormFlattening = true;
                            stamper.Close();
                            template2_1 = new PdfReader(template2_1InvoiceStream.ToArray());
                            template2_1.RemoveUnusedObjects();
                            copy.AddPage(copy.GetImportedPage(template2_1, 1));
                        }
                        //one template2_2 will used
                        MemoryStream template2_2InvoiceStream = new MemoryStream();
                        stamper = new PdfStamper(template2_2, template2_2InvoiceStream);
                        stamper.SetFullCompression();
                        fields = stamper.AcroFields;
                        if (order.OrderShippings != null && order.OrderShippings.Length > 0)
                        {
                            FillBillToAndShipTo(order, fields, contractPhoneInfo, "", SentTime);
                            //Order List
                            if (order.OrderItems.Rows.Count % 29 <= 15 && order.OrderItems.Rows.Count % 29 > 0)
                            {
                                int rowIndex = order.OrderItems.Rows.Count % 29 - 1;
                                int lastRowIndex = order.OrderItems.Rows.Count - 1;
                                if (rowIndex >= 0)
                                {
                                    for (int k = rowIndex; k >= 0; k--)
                                    {
                                        DataRow orderItem = order.OrderItems.Rows[lastRowIndex];
                                        FillOneOrderItem(fields, rowIndex, orderItem);
                                        rowIndex--;
                                        lastRowIndex--;
                                    }
                                }
                            }
                            else  //reserve 2 records for InvoiceTemplate2_2
                            {
                                int rowIndex = 0;
                                for (int i = order.OrderItems.Rows.Count - 2; i < order.OrderItems.Rows.Count; i++)
                                {
                                    DataRow orderItem = order.OrderItems.Rows[i];
                                    FillOneOrderItem(fields, rowIndex, orderItem);
                                    rowIndex++;
                                }
                            }
                            fields.SetField("CurrentPage", (template2_1Num + 1).ToString());
                            fields.SetField("TotalPage", (template2_1Num + 1).ToString());
                            FillTotal(order, fields,catalogName,"");
                        }
                        stamper.FormFlattening = true;
                        stamper.Close();
                        template2_2 = new PdfReader(template2_2InvoiceStream.ToArray());
                        template2_2.RemoveUnusedObjects();
                        copy.AddPage(copy.GetImportedPage(template2_2, 1));
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    document.Close();
                    if (invoicePdfStream != null)
                    {
                        invoicePdfStream.Close();
                    }
                    if (template1 != null)
                    {
                        template1.Close();
                    }
                    if (template2_1 != null)
                    {
                        template2_1.Close();
                    }
                    if (template2_2 != null)
                    {
                        template2_2.Close();
                    }
                }
            }
            else
            {
                throw new Exception("No order item to print.");
            }
        }
        return "";
    }

    private int GetOrderCatalog(int orderId)
    {
        Order order = new Order_Manager().GetOrder(orderId);
        if (order != null)
        {
            return order.PlacedCatalogId;
        }
        return 1;
    }
    private int GetPoOrderInvoiceTimes(int orderId)
    {
        int times = 1;
        times = new Order_Manager().GetPoInvoiceTimes(orderId);
        return times;
    }

    /// <summary>
    /// Harry on Dec/22/2010
    /// if catalogID = 1, then diapers template
    /// if catalogID = 2, then soap template
    /// if catalogID = 3, then bb template
    /// if whichTemplate = 1, use template 1
    /// if whichTemplate = 2, use template 2_1
    /// if whichtemplate = 3, use template 2_2
    /// </summary>
    /// <param name="templatePath"></param>
    /// <param name="whichTemplate"></param>
    /// <returns></returns>
    private PdfReader GetTemplateByCatalogId(string templatePath, int whichTemplate)
    {
        PdfReader pdfReader = null;
        string templateName = string.Empty;
        if (CatalogID == 1)
        {
            if (whichTemplate == 1)
            {
                templateName = "InvoiceTemplate1_Diapers.pdf";
            }
            else if (whichTemplate == 2)
            {
                templateName = "InvoiceTemplate2_1_Diapers.pdf";
            }
            else if (whichTemplate == 3)
            {
                templateName = "InvoiceTemplate2_2_Diapers.pdf";
            }
        }
        else if (CatalogID == 2)
        {
            if (whichTemplate == 1)
            {
                templateName = "InvoiceTemplate1_Soap.pdf";
            }
            else if (whichTemplate == 2)
            {
                templateName = "InvoiceTemplate2_1_Soap.pdf";
            }
            else if (whichTemplate == 3)
            {
                templateName = "InvoiceTemplate2_2_Soap.pdf";
            }
        }
        else if (CatalogID == 3)
        {
            if (whichTemplate == 1)
            {
                templateName = "InvoiceTemplate1_BeautyBar.pdf";
            }
            else if (whichTemplate == 2)
            {
                templateName = "InvoiceTemplate2_1_BeautyBar.pdf";
            }
            else if (whichTemplate == 3)
            {
                templateName = "InvoiceTemplate2_2_BeautyBar.pdf";
            }
        }
        else if (CatalogID == 4)
        {
            if (whichTemplate == 1)
            {
                templateName = "InvoiceTemplate1_Wag.pdf";
            }
            else if (whichTemplate == 2)
            {
                templateName = "InvoiceTemplate2_1_Wag.pdf";
            }
            else if (whichTemplate == 3)
            {
                templateName = "InvoiceTemplate2_2_Wag.pdf";
            }
        }
        else if (CatalogID == 5)
        {
            if (whichTemplate == 1)
            {
                templateName = "InvoiceTemplate1_Yoyo.pdf";
            }
            else if (whichTemplate == 2)
            {
                templateName = "InvoiceTemplate2_1_Yoyo.pdf";
            }
            else if (whichTemplate == 3)
            {
                templateName = "InvoiceTemplate2_2_Yoyo.pdf";
            }
        }
        else if(CatalogID==6)
        {
            if(whichTemplate==1)
            {
                templateName = "InvoiceTemplate1_Casa.pdf";
            }
            else if(whichTemplate==2)
            {
                templateName = "InvoiceTemplate2_1_Casa.pdf";
            }
            else if(whichTemplate==3)
            {
                templateName = "InvoiceTemplate2_2_Casa.pdf";
            }
        }
        pdfReader = new PdfReader(string.Format("{0}\\" + templateName, templatePath));
        return pdfReader;
    }

    private DataTable GetInvoiceTemplate(int catalogID)
    {
        DataTable customerTemplate = null;
        if (catalogID == 1)
        {
            customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(DIAPERS_CUSTOMER_TEMPLATE_NAME);
        }
        else if (catalogID == 2)
        {
            customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(SOAP_CUSTOMER_TEMPLATE_NAME);
        }
        else if (catalogID == 3)
        {
            customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(BEAUTYBAR_CUSTOMER_TEMPLATE_NAME);
        }
        else if (catalogID == 4)
        {
            customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(WAG_CUSTOMER_TEMPLATE_NAME);
        }
        else if (catalogID == 5)
        {
            customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(YOYO_CUSTOMER_TEMPLATE_NAME);
        }
        else if (catalogID == 6)
        {
            customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(CASA_CUSTOMER_TEMPLATE_NAME);
        }
        return customerTemplate;
    }
}

 

你可能感兴趣的:(pdf)