zoukankan      html  css  js  c++  java
  • C#打印格式

    一:C#代码直接打印pdf文件(打印质保书pdf文件)

    引用:

    代码注释很详细了。

            private void btn_pdf_Click(object sender, RoutedEventArgs e)
            {
                string filePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Resource\川AX5572 904080D005000.pdf";
                printShow(filePath);
            }
    
            /// <summary>
            /// 打印的代码
            /// </summary>
            /// <param name="url">要打印的PDF路径</param>
            private int printShow(string url)
            {
                int isOK = 0;
                PDFFile file = PDFFile.Open(url);
                PrinterSettings settings = new PrinterSettings();
                System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
                settings.PrinterName = "NPI84FFAF (HP LaserJet MFP M436)"; // 打印机名称
                settings.PrintToFile = false;
    
                //设置纸张大小(可以不设置,取默认设置)3.90 in,  8.65 in
                PaperSize ps = new PaperSize("test", 4, 9);
                ps.RawKind = 9; //如果是自定义纸张,就要大于118,(A4值为9,详细纸张类型与值的对照请看http://msdn.microsoft.com/zh-tw/library/system.drawing.printing.papersize.rawkind(v=vs.85).aspx)
    
                O2S.Components.PDFRender4NET.Printing.PDFPrintSettings pdfPrintSettings = new O2S.Components.PDFRender4NET.Printing.PDFPrintSettings(settings);
                pdfPrintSettings.PaperSize = ps;
                pdfPrintSettings.PageScaling = O2S.Components.PDFRender4NET.Printing.PageScaling.FitToPrinterMarginsProportional;
                pdfPrintSettings.PrinterSettings.Copies = 1;
    
                try
                {
                    file.Print(pdfPrintSettings);
                    isOK = 1;
                }
                catch (Exception)
                {
                    isOK = -1;
                    throw;
                }
                finally
                {
    
                    file.Dispose();
                }
                return isOK;
            }
    

      

    二:先生成excel在调用打印(生成excel主要在于布局)

    按钮事件代码:

            private void btn_zbs_Click(object sender, RoutedEventArgs e)
            {
                // 准备好数据
                List<DynamicModel> dm = new List<DynamicModel>()
                {
                    new DynamicModel(){BatchNumber="319040027",RelMpa = "470",RMpa = "655",A="29.0",Agt = "16.0",RmReL = "1.40",RelRel = "1.18",DirectBendingOne="",ResultOne = "",DirectBendingTwo = "I",
                        ResultTwo = "合格",
                        Metallography = "合格",
                        WeightDeviation="合格",
                        SurfaceQuality="合格",
                        SizeAndAppearance="合格",
                        Packing="合格",
                    },
                    new DynamicModel(){BatchNumber="319040027",RelMpa = "450",RMpa = "650",A="27.0",Agt = "15.4",RmReL = "1.45",RelRel = "1.13",DirectBendingOne="",ResultOne = "",DirectBendingTwo = "I",
                        ResultTwo = "合格",
                        Metallography = "合格",
                        WeightDeviation="合格",
                        SurfaceQuality="合格",
                        SizeAndAppearance="合格",
                        Packing="合格",
                    },
                    new DynamicModel(){BatchNumber="319040027",RelMpa = "435",RMpa = "640",A="28.0",Agt = "15.7",RmReL = "1.47",RelRel = "1.09",DirectBendingOne="",ResultOne = "",DirectBendingTwo = "I",
                        ResultTwo = "合格",
                        Metallography = "合格",
                        WeightDeviation="合格",
                        SurfaceQuality="合格",
                        SizeAndAppearance="合格",
                        Packing="合格",
                    },
                    new DynamicModel(){BatchNumber="319040027",RelMpa = "460",RMpa = "645",A="26.0",Agt = "16.2",RmReL = "1.40",RelRel = "1.15",DirectBendingOne="",ResultOne = "",DirectBendingTwo = "I",
                        ResultTwo = "合格",
                        Metallography = "合格",
                        WeightDeviation="合格",
                        SurfaceQuality="合格",
                        SizeAndAppearance="合格",
                        Packing="合格",
                    },
                    new DynamicModel(){BatchNumber="319040027",RelMpa = "470",RMpa = "655",A="29.0",Agt = "16.0",RmReL = "1.40",RelRel = "1.18",DirectBendingOne="",ResultOne = "",DirectBendingTwo = "I",
                        ResultTwo = "合格",
                        Metallography = "合格",
                        WeightDeviation="合格",
                        SurfaceQuality="合格",
                        SizeAndAppearance="合格",
                        Packing="合格",
                    },
                };
    
                List<ChemistryModel> cm = new List<ChemistryModel>()
                {
                    new ChemistryModel(){BatchNumber="319040027",Bales="2",Constituent="熔炼",C="0.22",Si= "0.37",Mn = "1.32",P="0.020",S="0,030",Ceq = "0.46"},
                    new ChemistryModel(){BatchNumber="319040027",Bales="2",Constituent="熔炼",C="0.22",Si= "0.37",Mn = "1.32",P="0.020",S="0,030",Ceq = "0.46"},
                    new ChemistryModel(){BatchNumber="319040027",Bales="2",Constituent="熔炼",C="0.22",Si= "0.37",Mn = "1.32",P="0.020",S="0,030",Ceq = "0.46"},
                    new ChemistryModel(){BatchNumber="319040027",Bales="2",Constituent="熔炼",C="0.22",Si= "0.37",Mn = "1.32",P="0.020",S="0,030",Ceq = "0.46"},
                };
    
                WarrantyModel wm = new WarrantyModel()
                {
                    LicenceNumber = "XK05-001-00066",
                    OrderUnit = "。。。。。。限公司",
                    ReceivingUnit = "。。。。有限责任公司",
                    ContractCode = "D9S0379001",
                    VarietyName = "钢筋混凝土用热轧带肋钢筋(盘卷)",
                    Technical = "GB/T1499.2-2018",
                    FixedLength = "",
                    BrandName = "HRB400R",
                    Diameter = "10",
                    AddressChina = " 中   国   攀   枝   花",
                    AddressEnglish = " PAN ZHI HUA CHINA ",
                    KnotNumber = "904080D005000",
                    DeliveryStute = "热扎",
                    CertificateNo = "1904DB00384",
                    ArriveStation = "汽车自提",
                    LicenseNumber = "川A09901",
                    DeliverGoodsData = "2019年4月8日",
                    TabulationTime = "2019年04月08日 15时08分13分",
                    Remark = "
    1、兹证明本产品按供货标准检验各项指标均符合供货标准规定。     
    2、质量证明书原件是验收依据,复印件仅供参考,不作为验收凭证。     
    3、弯芯直径①:C▁d=a、G▁3d、H▁4d、I▁5d、J▁6d、K▁7d、L▁8d、M▁9d。",
                    Explain = "",
                    PersonInCharge = ""
                };
                wm.Dynamic = dm;
                wm.Chemistry = cm;
    
                // 调用打印
                PrintHelper printHelper = new PrintHelper(wm);
                printHelper.DataToExcel();
    
            }
    

      

     PrintHelper.cs文件代码

        /// <summary>
        /// 打印
        /// </summary>
        public class PrintHelper
        {
    
            /// <summary>
            /// 文件生成路径
            /// </summary>
            private string _filePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "file\" +
                                       DateTime.Now.ToString("yyyyMMddhhmmss");//DateTime.Now.ToFileTimeUtc().ToString();
            /// <summary>
            /// 打印质保书数据实体
            /// </summary>
            private WarrantyModel _warranty;
    
            /// <summary>
            /// 
            /// </summary>
            private int _maxRemarkLength = int.MinValue;
    
            public PrintHelper(WarrantyModel warranty)
            {
                _warranty = warranty;
            }
            /// <summary>
            /// 动态生成Excel
            /// </summary>
            public void DataToExcel()
            {
    
                int max = int.MinValue;
                var remarkList = _warranty.Chemistry.Select(m => m.BatchNumber).ToList();
                for (int i = 0, length = remarkList.Count; i < length; i++)
                {
                    var remark = remarkList[i];
                    if (remark != null && remark.Length > max)
                    {
                        max = remarkList[i].Length;
                    }
                }
    
                if (max > 10) _maxRemarkLength = (max / 4 + 1) * 20;
                else _maxRemarkLength = 40;
    
                Application ExcelApp = new Application();
    
                Workbook worksBook = ExcelApp.Workbooks.Add();
                Worksheet workSheet = (Worksheet)worksBook.Worksheets[1];
                if (workSheet == null)
                {
                    System.Diagnostics.Debug.WriteLine("ERROR: worksheet == null");
                    return;
                }
    
                workSheet.Name = "DeliveryOrderBills";
                workSheet.Cells.WrapText = true;
                workSheet.Cells.EntireRow.AutoFit();
    
                RangeMark(workSheet, "A1", "D1", "QG/JS JL(Y)042-2017", 10, 30, 1, 0);
                RangeMark(workSheet, "H1", "K1", "产 品 质 量 保 证 书", 26, 30, 3, 0);
    
                RangeMark(workSheet, "A3", "A3", "许可证号:", 12, 30, 3, 0);
                RangeMark(workSheet, "B3", "D3", _warranty.LicenceNumber, 12, 30, 1, 0);
                RangeMark(workSheet, "O3", "O3", "结齐单号:", 12, 30, 3, 0);
                RangeMark(workSheet, "P3", "Q3", _warranty.KnotNumber, 12, 30, 1, 0);
    
                RangeMark(workSheet, "A4", "A4", "订货单位:", 12, 30, 3, 0);
                RangeMark(workSheet, "B4", "C4", _warranty.OrderUnit, 12, 30, 1, 0);
                RangeMark(workSheet, "I4", "K4", "Quality  Certificate", 12, 30, 3, 0);
                RangeMark(workSheet, "O4", "O4", "交货状态:", 12, 30, 3, 0);
                RangeMark(workSheet, "P4", "Q4", _warranty.DeliveryStute, 12, 30, 1, 0);
    
                RangeMark(workSheet, "A5", "A5", "收获单位:", 12, 30, 3, 0);
                RangeMark(workSheet, "B5", "C5", _warranty.ReceivingUnit, 12, 30, 1, 0);
                RangeMark(workSheet, "H5", "K5", "攀钢集团攀枝花金属制品有限公司", 16, 30, 3, 0);
                RangeMark(workSheet, "O5", "O5", "证明书号:", 12, 30, 3, 0);
                RangeMark(workSheet, "P5", "Q5", _warranty.CertificateNo, 12, 30, 1, 0);
    
                RangeMark(workSheet, "A6", "A6", "合同编号:", 12, 30, 3, 0);
                RangeMark(workSheet, "B6", "C6", _warranty.ContractCode, 12, 30, 1, 0);
                RangeMark(workSheet, "F6", "F6", "定尺长度
    (mm):", 12, 30, 3, 0);
                RangeMark(workSheet, "G6", "G6", _warranty.FixedLength, 12, 30, 3, 0);
                RangeMark(workSheet, "I6", "M6", "Pangang Group Panzhihua Metal Products Co., Ltd.", 12, 20, 3, 0);
                RangeMark(workSheet, "O6", "O6", "到 站:", 12, 30, 3, 0);
                RangeMark(workSheet, "P6", "Q6", _warranty.ArriveStation, 12, 30, 1, 0);
    
                RangeMark(workSheet, "A7", "A7", "品种名称:", 12, 30, 3, 0);
                RangeMark(workSheet, "B7", "D7", _warranty.VarietyName, 12, 30, 1, 0);
                RangeMark(workSheet, "F7", "F7", "牌 号", 12, 30, 3, 0);
                RangeMark(workSheet, "G7", "G7", _warranty.BrandName, 12, 20, 3, 0);
                RangeMark(workSheet, "J7", "J7", "地 址:", 12, 30, 3, 0);
                RangeMark(workSheet, "K7", "M7", _warranty.AddressChina, 12, 30, 3, 0);
                RangeMark(workSheet, "O7", "O7", "车 号:", 12, 30, 3, 0);
                RangeMark(workSheet, "P7", "Q7", _warranty.LicenseNumber, 12, 30, 1, 0);
    
                RangeMark(workSheet, "A8", "A8", "技术条件:", 12, 30, 3, 0);
                RangeMark(workSheet, "B8", "D8", _warranty.Technical, 12, 30, 1, 0);
                RangeMark(workSheet, "F8", "F8", "直径(mm):", 12, 30, 3, 0);
                RangeMark(workSheet, "G8", "G8", _warranty.Diameter, 12, 30, 3, 0);
                RangeMark(workSheet, "J8", "J8", "Address:", 12, 30, 3, 0);
                RangeMark(workSheet, "K8", "M8", _warranty.AddressEnglish, 12, 30, 3, 0);
                RangeMark(workSheet, "O8", "O8", "发货日期:", 12, 30, 3, 0);
                RangeMark(workSheet, "P8", "Q8", _warranty.DeliverGoodsData, 12, 30, 1, 0);
    
                // 化学成分表单(表头部分)
                RangeMark(workSheet, "A9", "A10", "批号");
                RangeMark(workSheet, "B9", "B10", "捆(包)数");
                RangeMark(workSheet, "C9", "C10", "成分项目");
                RangeMark(workSheet, "D9", "O9", "化  学  成  分 chemical composition");
                RangeMark(workSheet, "P9", "P9", "");
                RangeMark(workSheet, "Q9", "Q9", "");
                RangeMark(workSheet, "R9", "R9", "");
    
                RangeMark(workSheet, "D10", "D10", "C");
                RangeMark(workSheet, "E10", "E10", "Si");
                RangeMark(workSheet, "F10", "F10", "Mn");
                RangeMark(workSheet, "G10", "G10", "P");
                RangeMark(workSheet, "H10", "H10", "S");
                RangeMark(workSheet, "I10", "I10", "Ceq");
                RangeMark(workSheet, "J10", "J10", "");
                RangeMark(workSheet, "K10", "K10", "");
                RangeMark(workSheet, "L10", "L10", "");
                RangeMark(workSheet, "M10", "M10", "");
                RangeMark(workSheet, "N10", "N10", "");
                RangeMark(workSheet, "O10", "O10", "");
                RangeMark(workSheet, "P10", "R10", "");
    
                // 化学成分表单(内容部分)
                var rowTwoNum = 0;// 力学性能表单开始行索引
    
                if (_warranty.Chemistry.Any())
                {
                    for (int i = 0; i < _warranty.Chemistry.Count; i++)
                    {
                        // 行数索引
                        var rowOneNum = 11 + i;
                        // 数据实体
                        var item = _warranty.Chemistry[i];
                        RangeMark(workSheet, string.Format("A{0}", rowOneNum), string.Format("A{0}", rowOneNum), item.BatchNumber);
                        RangeMark(workSheet, string.Format("B{0}", rowOneNum), string.Format("B{0}", rowOneNum), item.Bales);
                        RangeMark(workSheet, string.Format("C{0}", rowOneNum), string.Format("C{0}", rowOneNum), item.Constituent);
                        RangeMark(workSheet, string.Format("D{0}", rowOneNum), string.Format("D{0}", rowOneNum), item.C);
                        RangeMark(workSheet, string.Format("E{0}", rowOneNum), string.Format("E{0}", rowOneNum), item.Si);
                        RangeMark(workSheet, string.Format("F{0}", rowOneNum), string.Format("F{0}", rowOneNum), item.Mn);
                        RangeMark(workSheet, string.Format("G{0}", rowOneNum), string.Format("G{0}", rowOneNum), item.P);
                        RangeMark(workSheet, string.Format("H{0}", rowOneNum), string.Format("H{0}", rowOneNum), item.S);
                        RangeMark(workSheet, string.Format("I{0}", rowOneNum), string.Format("I{0}", rowOneNum), item.Ceq);
                        RangeMark(workSheet, string.Format("J{0}", rowOneNum), string.Format("J{0}", rowOneNum), "");
                        RangeMark(workSheet, string.Format("K{0}", rowOneNum), string.Format("K{0}", rowOneNum), "");
                        RangeMark(workSheet, string.Format("L{0}", rowOneNum), string.Format("L{0}", rowOneNum), "");
                        RangeMark(workSheet, string.Format("M{0}", rowOneNum), string.Format("M{0}", rowOneNum), "");
                        RangeMark(workSheet, string.Format("N{0}", rowOneNum), string.Format("N{0}", rowOneNum), "");
                        RangeMark(workSheet, string.Format("O{0}", rowOneNum), string.Format("O{0}", rowOneNum), "");
                        RangeMark(workSheet, string.Format("P{0}", rowOneNum), string.Format("P{0}", rowOneNum), "");
                        RangeMark(workSheet, string.Format("Q{0}", rowOneNum), string.Format("Q{0}", rowOneNum), "");
                        RangeMark(workSheet, string.Format("R{0}", rowOneNum), string.Format("R{0}", rowOneNum), "");
                    }
                    // 空行索引
                    var krowIndex = _warranty.Chemistry.Count + 11;
                    RangeMark(workSheet, string.Format("A{0}", krowIndex), string.Format("R{0}", krowIndex), "", 12, 15);
                    rowTwoNum = krowIndex + 1;
                }
                else
                {
                    RangeMark(workSheet, string.Format("A{0}", 11), string.Format("R{0}", 11), "", 12, 15);
                    rowTwoNum = 12;
                }
                // 力学性能表单(表头部分)
                RangeMark(workSheet, string.Format("A{0}", rowTwoNum), string.Format("A{0}", rowTwoNum + 1), "批号");
                RangeMark(workSheet, string.Format("B{0}", rowTwoNum), string.Format("G{0}", rowTwoNum), "力学性能");
                RangeMark(workSheet, string.Format("H{0}", rowTwoNum), string.Format("I{0}", rowTwoNum), "冷弯 / 180°");
                RangeMark(workSheet, string.Format("J{0}", rowTwoNum), string.Format("K{0}", rowTwoNum), "反向弯曲 ②");
    
                RangeMark(workSheet, string.Format("L{0}", rowTwoNum), string.Format("L{0}", rowTwoNum + 1), "金相组织");
                RangeMark(workSheet, string.Format("M{0}", rowTwoNum), string.Format("M{0}", rowTwoNum + 1), "");
                RangeMark(workSheet, string.Format("N{0}", rowTwoNum), string.Format("N{0}", rowTwoNum + 1), "");
                RangeMark(workSheet, string.Format("O{0}", rowTwoNum), string.Format("O{0}", rowTwoNum + 1), "重量偏差");
                RangeMark(workSheet, string.Format("P{0}", rowTwoNum), string.Format("P{0}", rowTwoNum + 1), "表面质量");
                RangeMark(workSheet, string.Format("Q{0}", rowTwoNum), string.Format("Q{0}", rowTwoNum + 1), "尺寸和
    外形");
                RangeMark(workSheet, string.Format("R{0}", rowTwoNum), string.Format("R{0}", rowTwoNum + 1), "包装");
    
                RangeMark(workSheet, string.Format("B{0}", rowTwoNum + 1), string.Format("B{0}", rowTwoNum + 1), "Rel /Mpa");
                RangeMark(workSheet, string.Format("C{0}", rowTwoNum + 1), string.Format("C{0}", rowTwoNum + 1), "Rm /Mpa");
                RangeMark(workSheet, string.Format("D{0}", rowTwoNum + 1), string.Format("D{0}", rowTwoNum + 1), "A / %");
                RangeMark(workSheet, string.Format("E{0}", rowTwoNum + 1), string.Format("E{0}", rowTwoNum + 1), "Rgt / %");
                RangeMark(workSheet, string.Format("F{0}", rowTwoNum + 1), string.Format("F{0}", rowTwoNum + 1), " R°m / R°eL");
                RangeMark(workSheet, string.Format("G{0}", rowTwoNum + 1), string.Format("G{0}", rowTwoNum + 1), "R°eL/ReL");
                RangeMark(workSheet, string.Format("H{0}", rowTwoNum + 1), string.Format("H{0}", rowTwoNum + 1), "弯芯直径①");
                RangeMark(workSheet, string.Format("I{0}", rowTwoNum + 1), string.Format("I{0}", rowTwoNum + 1), "结果");
                RangeMark(workSheet, string.Format("J{0}", rowTwoNum + 1), string.Format("J{0}", rowTwoNum + 1), "弯芯直径①");
                RangeMark(workSheet, string.Format("K{0}", rowTwoNum + 1), string.Format("K{0}", rowTwoNum + 1), "结果");
    
                // 力学性能表单(内容部分)
                var totalRowIndex = rowTwoNum + 2;// 统计行索引
    
                if (_warranty.Dynamic.Any())
                {
                    for (int i = 0; i < _warranty.Dynamic.Count; i++)
                    {
                        // 内容索引
                        var rowThreeNum = i + rowTwoNum + 2;
                        totalRowIndex = rowThreeNum + 1;
                        // 数据实体
                        var item = _warranty.Dynamic[i];
                        RangeMark(workSheet, string.Format("A{0}", rowThreeNum), string.Format("A{0}", rowThreeNum), item.BatchNumber);
                        RangeMark(workSheet, string.Format("B{0}", rowThreeNum), string.Format("B{0}", rowThreeNum), item.RelMpa);
                        RangeMark(workSheet, string.Format("C{0}", rowThreeNum), string.Format("C{0}", rowThreeNum), item.RMpa);
                        RangeMark(workSheet, string.Format("D{0}", rowThreeNum), string.Format("D{0}", rowThreeNum), item.A);
                        RangeMark(workSheet, string.Format("E{0}", rowThreeNum), string.Format("E{0}", rowThreeNum), item.Agt);
                        RangeMark(workSheet, string.Format("F{0}", rowThreeNum), string.Format("F{0}", rowThreeNum), item.RmReL);
                        RangeMark(workSheet, string.Format("G{0}", rowThreeNum), string.Format("G{0}", rowThreeNum), item.RelRel);
                        RangeMark(workSheet, string.Format("H{0}", rowThreeNum), string.Format("H{0}", rowThreeNum), item.DirectBendingOne);
                        RangeMark(workSheet, string.Format("I{0}", rowThreeNum), string.Format("I{0}", rowThreeNum), item.ResultOne);
                        RangeMark(workSheet, string.Format("J{0}", rowThreeNum), string.Format("J{0}", rowThreeNum), item.DirectBendingTwo);
                        RangeMark(workSheet, string.Format("K{0}", rowThreeNum), string.Format("K{0}", rowThreeNum), item.ResultTwo);
                        RangeMark(workSheet, string.Format("L{0}", rowThreeNum), string.Format("L{0}", rowThreeNum), item.Metallography);
                        RangeMark(workSheet, string.Format("M{0}", rowThreeNum), string.Format("M{0}", rowThreeNum), "");
                        RangeMark(workSheet, string.Format("N{0}", rowThreeNum), string.Format("N{0}", rowThreeNum), "");
                        RangeMark(workSheet, string.Format("O{0}", rowThreeNum), string.Format("O{0}", rowThreeNum), item.WeightDeviation);
                        RangeMark(workSheet, string.Format("P{0}", rowThreeNum), string.Format("P{0}", rowThreeNum), item.SurfaceQuality);
                        RangeMark(workSheet, string.Format("Q{0}", rowThreeNum), string.Format("Q{0}", rowThreeNum), item.SizeAndAppearance);
                        RangeMark(workSheet, string.Format("R{0}", rowThreeNum), string.Format("R{0}", rowThreeNum), item.Packing);
    
                    }
                     
                }
                // 添加统计行 
                RangeMark(workSheet, string.Format("A{0}", totalRowIndex), string.Format("A{0}", totalRowIndex), "");
                RangeMark(workSheet, string.Format("B{0}", totalRowIndex), string.Format("B{0}", totalRowIndex), "总捆(包)数 ");
                RangeMark(workSheet, string.Format("C{0}", totalRowIndex), string.Format("C{0}", totalRowIndex), "计算");
                RangeMark(workSheet, string.Format("D{0}", totalRowIndex), string.Format("D{0}", totalRowIndex), "");
                RangeMark(workSheet, string.Format("E{0}", totalRowIndex), string.Format("E{0}", totalRowIndex), "");
                RangeMark(workSheet, string.Format("F{0}", totalRowIndex), string.Format("F{0}", totalRowIndex), "");
                RangeMark(workSheet, string.Format("G{0}", totalRowIndex), string.Format("G{0}", totalRowIndex), "");
                RangeMark(workSheet, string.Format("H{0}", totalRowIndex), string.Format("I{0}", totalRowIndex), "实际总重量(t)");
                RangeMark(workSheet, string.Format("J{0}", totalRowIndex), string.Format("J{0}", totalRowIndex), "计算");
                RangeMark(workSheet, string.Format("K{0}", totalRowIndex), string.Format("L{0}", totalRowIndex), "");
                RangeMark(workSheet, string.Format("M{0}", totalRowIndex), string.Format("N{0}", totalRowIndex), "");
                RangeMark(workSheet, string.Format("O{0}", totalRowIndex), string.Format("Q{0}", totalRowIndex), "");
                RangeMark(workSheet, string.Format("R{0}", totalRowIndex), string.Format("R{0}", totalRowIndex), "");
    
                
    
                // 合并横着的单元格
                ColumnsSpan(workSheet, "F1", "G1");
                ColumnsSpan(workSheet, "F2", "G2");
                ColumnsSpan(workSheet, "F3", "G3");
                ColumnsSpan(workSheet, "F4", "G4");
                ColumnsSpan(workSheet, "F5", "G5");
    
                ColumnsSpan(workSheet, "L1", "M1");
                ColumnsSpan(workSheet, "L2", "M2");
                ColumnsSpan(workSheet, "L3", "M3");
                ColumnsSpan(workSheet, "L4", "M4");
                ColumnsSpan(workSheet, "L5", "M5");
    
    
                // 合并竖着的单元格 
                RowsSpan(workSheet, "F1", "F5");
                RowsSpan(workSheet, "G1", "G5");
    
                RowsSpan(workSheet, "L1", "L5");
                RowsSpan(workSheet, "M1", "M5");
    
                // 插入图片
                SavePic(workSheet, "G1", Directory.GetCurrentDirectory() + "/pq.jpg");
                SavePic(workSheet, "L1", Directory.GetCurrentDirectory() + "/s.jpg");
    
                //------------------------打印页面相关设置--------------------------------
                workSheet.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperA4;//纸张大小
                workSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;//页面横向
                //workSheet.PageSetup.Zoom = 75; //打印时页面设置,缩放比例百分之几
                workSheet.PageSetup.Zoom = false; //打印时页面设置,必须设置为false,页高,页宽才有效
                workSheet.PageSetup.FitToPagesWide = 1; //设置页面缩放的页宽为1页宽
                workSheet.PageSetup.FitToPagesTall = false; //设置页面缩放的页高自动
                workSheet.PageSetup.CenterFooter = "第 &P 页,共 &N 页";//页面下标
                workSheet.PageSetup.FooterMargin = 5;
                workSheet.PageSetup.PrintGridlines = false; //打印单元格网线
                workSheet.PageSetup.TopMargin = 15; //上边距为2cm(转换为in)
                workSheet.PageSetup.BottomMargin = 20; //下边距为1.5cm
                workSheet.PageSetup.LeftMargin = 30; //左边距为2cm
                workSheet.PageSetup.RightMargin = 30; //右边距为2cm
                workSheet.PageSetup.CenterHorizontally = true; //文字水平居中
                //------------------------打印页面设置结束--------------------------------
                ///http://blog.csdn.net/wanmingtom/article/details/6125599
                ///
                 
    
                // 生成excel文件
                workSheet.SaveAs(_filePath, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, 1, false, Type.Missing, Type.Missing, Type.Missing); //另存表
    
                //// 直接打印放开下面两个注释即可
                //ExcelApp.Visible = false; //是否显示excel文档
                //workSheet.PrintOutEx();
                KillProcess(ExcelApp); //杀掉生成的进程
                GC.Collect(); //垃圾回收机制
                 
            }
    
            private void ColumnsSpan(Worksheet workSheet, string start, string end)
            {
                Microsoft.Office.Interop.Excel.Range EG1 = workSheet.get_Range(start, end);
                EG1.MergeCells = true;
                EG1.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
                EG1.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
    
            }
            private void RowsSpan(Worksheet workSheet, string start, string end)
            {
                Range pqPricRange = workSheet.get_Range(start, end);
                pqPricRange.Application.DisplayAlerts = false;
                //pqPricRange.Merge(Missing.Value);
                pqPricRange.MergeCells = true;
                pqPricRange.Application.DisplayAlerts = true;
                pqPricRange.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
                pqPricRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
            }
    
    
            /// <summary>
            /// 创建单元格
            /// </summary>
            /// <param name="workSheet">Worksheet对象</param>
            /// <param name="startCell">开始格子号</param>
            /// <param name="endCell">终止格子号</param>
            /// <param name="strText">文本</param>
            /// <param name="fontSize">字体大小</param>
            /// <param name="rowHeight">行高</param>
            /// <param name="HorizontalAlignment">横向剧中</param>
            /// <param name="LineStyle">单元格边框</param>
            /// <returns></returns>
            private bool RangeMark(Worksheet workSheet, string startCell, string endCell, string strText, int fontSize = 12, int rowHeight = 30, int HorizontalAlignment = 3, int LineStyle = 1)
            {
                //创建一个区域对象。第一个参数是开始格子号,第二个参数是终止格子号。比如选中A1——D3这个区域。
                Range range = workSheet.get_Range(startCell, endCell);
                if (range == null)
                {
                    System.Diagnostics.Debug.WriteLine("ERROR: range == null");
                    return false;
                }
                range.Merge(0); //合并方法,0的时候直接合并为一个单元格
                range.Font.Size = fontSize; //字体大小
                range.Font.Name = "黑体"; //字体
                //range.EntireRow.AutoFit(); //自动调整行高
                //range.EntireColumn.AutoFit();
                //range.RowHeight = 20; 
                //range.EntireColumn.AutoFit(); //自动调整列宽
                //range.NumberFormatLocal = "@";
                //range.EntireColumn.AutoFit();
                range.NumberFormatLocal = "@";
                range.RowHeight = rowHeight;
                range.ColumnWidth = 15;
                //range.EntireColumn.AutoFit();
                //range.EntireRow.AutoFit();
                range.HorizontalAlignment = HorizontalAlignment; //横向居中
                range.VerticalAlignment = XlVAlign.xlVAlignCenter;
                range.Value = strText; //合并单元格之后,设置其中的文本
                range.Cells.Borders.LineStyle = LineStyle; //设置单元格边框的粗细
                range.WrapText = true; //文本自动换行
                return true;
            }
    
    
            /// <summary>
            /// 杀掉生成的进程
            /// </summary>
            /// <param name="AppObject">进程程对象</param>
            private static void KillProcess(Microsoft.Office.Interop.Excel.Application AppObject)
            {
                int Pid = 0;
                IntPtr Hwnd = new IntPtr(AppObject.Hwnd);
                System.Diagnostics.Process p = null;
                try
                {
                    GetWindowThreadProcessId(Hwnd, out Pid);
                    p = System.Diagnostics.Process.GetProcessById(Pid);
                    if (p != null)
                    {
                        p.Kill();
                        p.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("进程关闭失败!异常信息:" + ex);
                }
            }
    
            /// <summary>
            /// 引用Windows句柄,获取程序PID
            /// </summary>
            /// <param name="Hwnd"></param>
            /// <param name="PID"></param>
            /// <returns></returns>
            [DllImport("User32.dll")]
            public static extern int GetWindowThreadProcessId(IntPtr Hwnd, out int PID);
    
            private void SavePic(Worksheet workSheet, string rangename, string filename)
            {
                Microsoft.Office.Interop.Excel.Range range = workSheet.get_Range(rangename, Type.Missing);
                range.Select();
                range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
                ///////////  
                float PicLeft, PicTop, PicWidth, PicHeight;    //距离左边距离,顶部距离,图片宽度、高度  
                PicTop = Convert.ToSingle(range.Top);
                PicWidth = Convert.ToSingle(range.MergeArea.Width);
                PicHeight = Convert.ToSingle(range.Height);
                PicWidth = Convert.ToSingle(range.Width);
                PicLeft = Convert.ToSingle(range.Left);
                //////////////////  
    
                Microsoft.Office.Interop.Excel.Pictures pict = (Microsoft.Office.Interop.Excel.Pictures)workSheet.Pictures(Type.Missing);
                if (filename.IndexOf(".") > 0)
                {
                    if (System.IO.File.Exists(filename))
                    {
                        pict.Insert(filename, Type.Missing);//显示原图   重叠在一起  
                        //workSheet.Shapes.AddPicture(filename,
                        //    Microsoft.Office.Core.MsoTriState.msoFalse,
                        //    Microsoft.Office.Core.MsoTriState.msoCTrue,
                        //    PicLeft, PicTop, PicWidth, PicHeight);//指定位置显示小图  
                    }
                }
            }
        }
    

      生成的excel预览

    三 在Visual Studio中通过插件编辑rdlc文件进行可视化布局(动态添加行的我暂时没有弄出来,这里只演示固定字段的打印)

     首先引用:

    第一步:安装插件 

    搜索rdlc

     

     第二步:这里下载好之后从新启动vs它会自动安装插件。安装好后创建文件。

     

     第三步:可视化布局操作

     第四步:设置数据绑定,在需要绑定数据的单元格中鼠标右键点击文本框属性。

    名称:与实体属性写法一致  值:[与实体属性写法一致]

     

    设置字体及大小

     第五步:布局及所有字段写好之后就设置数据集(我这里用的是本地实体模型)

    右键添加数据集

    这里选择你要绑定的实体

     

    注意:当界面设计好之后我们重新生成项目总是提示生成失败,而vs也不提示哪里出错了。

    我就猜测是不是这个rdlc文件的问题,我就试着把rdlc文件排除在项目外,再次生成就可以了。

    当然这个不影响我们编辑rdlc文件,你可以继续编辑,只不过在读取的时候,是默认bin目录下,这里每次编辑了就要手动赋值到bin目录中。 

     这里设计好了之后就看代码。

    按钮事件代码:

      private void btn_code_Click(object sender, RoutedEventArgs e)
            {
                // 数据
                var csm = new CodeSheetModel()
                {
                    CodeSheetNumber = "1W52902644",
                    ContractNuber = "D8S0363501",
                    QuasiSign = "",
                    LoadingPoint = "北部站",
                    DeliveryStandard = "GB/T1499.2-2019",
                    DeliveryAddress = "",
                    OrderUnit = "。。。。。有限公司",
                    ReceivingUnit = "。。。。。。。有限公司",
                    SettlementUnit = "。。。。。有限公司",
                    PrivateLineName = "螺纹钢",
                    LicenseNumber = "川B37037",
                    BillLoadNo = "1W62904010501",
                    ShippType = "21",
                    DeliveryClass = "2",
                    ProductDescription = "不说明",
                    VarietyName = "螺纹钢",
                    ShipmentNo = "",
                    BrandNo = "HRB400E1114",
                    FactoryOutData = "2019-04-03 14:10",
                    MeterMode = "计量",
                    PrintDateTime = "2019-04-03 14:10:45"
                };
    
                var p = new CodePrintHelper(); 
                p.Run(csm, (ex) =>
                {
                    MessageBox.Show(ex.Message);
                }, "NPI84FFAF (HP LaserJet MFP M436)");
                 
                MessageBox.Show("完成打印。。。");
            }
    

      CodePrintHelper.cs文件代码:

        /// <summary>
        /// 码单打印
        /// </summary>
        public class CodePrintHelper
        {
    
            /// <summary>
            /// 用来记录当前打印到第几页了
            /// </summary>
            private int m_currentPageIndex = 0;
            private IList<Stream> m_streams;
            /// <summary>
            /// 时间
            /// </summary>
            private DateTime dateTime;
    
            /// <summary>
            /// 打印机集合
            /// </summary>
            private static List<string> printList = null;
    
            /// <summary>
            /// 打印发生异常的回调函数
            /// </summary>
            public Action<Exception> ExecptionCallBack { get; set; }
    
            /// <summary>
            /// 获取打印机集合
            /// </summary>
            public static List<string> PrintList
            {
                get
                {
                    if (printList == null)
                    {
                        printList = new List<string>();
                        LocalPrintServer printServer = new LocalPrintServer();
                        PrintQueueCollection printQueuesOnLocalServer = printServer.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local });
                        foreach (PrintQueue printer in printQueuesOnLocalServer)
                            printList.Add(printer.Name);
                    }
                    return printList;
                }
            }
    
            /// <summary>
            /// 执行打印
            /// </summary>
            /// <param name="CodeSheetModel">打印的数据</param>
            /// <param name="printName">打印机名称,为空则调用默认的打印机</param>
            public bool Run(CodeSheetModel outPlate, Action<Exception> execptionCallBack, string printName = null)
            {
                ExecptionCallBack = execptionCallBack;
    
                // 检查是否指定了打印机
                if (string.IsNullOrWhiteSpace(printName) && PrintList.Count > 0)
                    printName = PrintList[0];
                else if (PrintList.Count <= 0)
                {
                    ExecptionCallBack(new Exception("未找到可用的打印机"));
                    return false;
                }
    
                if (!printList.Contains(printName))
                {
                    ExecptionCallBack(new Exception(string.Format("未找到打印机 {0}", printName)));
                    return false;
                }
    
                dateTime = DateTime.Now;
    
                var report = new LocalReport();
                report.ReportPath = "./Reports/ExitBarReport.rdlc";
                report.DataSources.Add(new ReportDataSource("CodeSheetDataSet", LoadData(outPlate)));
    
                Export(report);
    
                m_currentPageIndex = 0;
                Print(printName);
    
    
                if (m_streams != null)
                {
                    foreach (Stream stream in m_streams)
                        stream.Close();
                    m_streams = null;
                }
                DeleteTempFile();
                return true;
            }
    
            /// <summary>
            /// 填充要打印的数据
            /// </summary>
            /// <param name="op"></param>
            /// <returns></returns>
            public DataTable LoadData(CodeSheetModel op)
            {
                DataTable dt = new DataTable();
    
                dt.Columns.Add("CodeSheetNumber", typeof(string));
                dt.Columns.Add("ContractNuber", typeof(string));
                dt.Columns.Add("QuasiSign", typeof(string));
                dt.Columns.Add("LoadingPoint", typeof(string));
                dt.Columns.Add("DeliveryStandard", typeof(string));
                dt.Columns.Add("DeliveryAddress", typeof(string));
                dt.Columns.Add("OrderUnit", typeof(string));
                dt.Columns.Add("ReceivingUnit", typeof(string));
                dt.Columns.Add("SettlementUnit", typeof(string));
                dt.Columns.Add("PrivateLineName", typeof(string));
                dt.Columns.Add("LicenseNumber", typeof(string));
                dt.Columns.Add("BillLoadNo", typeof(string));
                dt.Columns.Add("ShippType", typeof(string));
                dt.Columns.Add("DeliveryClass", typeof(string));
                dt.Columns.Add("ProductDescription", typeof(string));
                dt.Columns.Add("VarietyName", typeof(string));
                dt.Columns.Add("ShipmentNo", typeof(string));
                dt.Columns.Add("BrandNo", typeof(string));
                dt.Columns.Add("FactoryOutData", typeof(string));
                dt.Columns.Add("MeterMode", typeof(string));
                dt.Columns.Add("PrintDateTime", typeof(string));
                //// 产品
                //dt.Columns.Add("MeltingNumber", typeof(string));
                //dt.Columns.Add("MaterialScience", typeof(string));
                //dt.Columns.Add("MachiningState", typeof(string));
                //dt.Columns.Add("Chang", typeof(string));
                //dt.Columns.Add("NetWight", typeof(string));
                //dt.Columns.Add("BundleNum", typeof(string));
                //dt.Columns.Add("BranchNum", typeof(string));
    
                DataRow dr = dt.NewRow();
                dr["CodeSheetNumber"] = op.CodeSheetNumber;
                dr["ContractNuber"] = op.ContractNuber;
                dr["QuasiSign"] = op.QuasiSign;
                dr["LoadingPoint"] = op.LoadingPoint;
                dr["DeliveryStandard"] = op.DeliveryStandard;
                dr["DeliveryAddress"] = op.DeliveryAddress;
                dr["OrderUnit"] = op.OrderUnit;
                dr["ReceivingUnit"] = op.ReceivingUnit;
                dr["SettlementUnit"] = op.SettlementUnit;
                dr["PrivateLineName"] = op.PrivateLineName;
                dr["LicenseNumber"] = op.LicenseNumber;
                dr["BillLoadNo"] = op.BillLoadNo;
                dr["ShippType"] = op.ShippType;
                dr["DeliveryClass"] = op.DeliveryClass;
                dr["ProductDescription"] = op.ProductDescription;
                dr["VarietyName"] = op.VarietyName;
                dr["ShipmentNo"] = op.ShipmentNo;
                dr["BrandNo"] = op.BrandNo;
                dr["FactoryOutData"] = op.FactoryOutData;
                dr["MeterMode"] = op.MeterMode;
                dr["PrintDateTime"] = op.PrintDateTime;
    
                dt.Rows.Add(dr);
                //// 产品 
                //for (int i = 0; i < productItem.Count; i++)
                //{
                //    var model = productItem[i];
                //    var newRow = dt.NewRow();
                //    dr["MeltingNumber"] = model.MeltingNumber;
                //    dr["MaterialScience"] = model.MaterialScience;
                //    dr["MachiningState"] = model.MachiningState;
                //    dr["Chang"] = model.Chang;
                //    dr["NetWight"] = model.NetWight;
                //    dr["BundleNum"] = model.BundleNum;
                //    dr["BranchNum"] = model.BranchNum;
                //    dt.Rows.Add(newRow);
                //}
    
                return dt;
            }
    
    
            /// <summary>
            /// 导出报表的每一个页面到一个EMF文件 
            /// </summary>
            /// <param name="report"></param>
            private void Export(LocalReport report)
            {
                string deviceInfo =
                    "<DeviceInfo>" +
                    "  <OutputFormat>EMF</OutputFormat>" +
                    "  <PageWidth>19.30cm</PageWidth>" +
                    "  <PageHeight>6.68cm</PageHeight>" +
                    "  <MarginTop>0.13cm</MarginTop>" +
                    "  <MarginLeft>1.53cm</MarginLeft>" +
                    "  <MarginRight>0.13cm</MarginRight>" +
                    "  <MarginBottom>0.13cm</MarginBottom>" +
                    "</DeviceInfo>";
                Warning[] warnings;
                m_streams = new List<Stream>();
                report.Render("Image", deviceInfo, CreateStream, out warnings);
    
    
                foreach (Stream stream in m_streams)
                {
                    stream.Position = 0;
                }
            }
            /// <summary>
            /// 创建流
            /// </summary>
            /// <param name="name"></param>
            /// <param name="fileNameExtension"></param>
            /// <param name="encoding"></param>
            /// <param name="mimeType"></param>
            /// <param name="willSeek"></param>
            /// <returns></returns>
            private Stream CreateStream(string name,
                string fileNameExtension, Encoding encoding,
                string mimeType, bool willSeek)
            {
                //var stream = new FileStream(@"./" + name +
                // "." + fileNameExtension, FileMode.Create);
                //var stream = new FileStream($"./{dateTime.ToString("yyyy_MM_dd_HH_mm_ss")}_{name}.{fileNameExtension}", FileMode.Create);
                if (!Directory.Exists("./PrintFileTemp"))
                {
                    Directory.CreateDirectory("./PrintFileTemp");
                }
                var stream = new FileStream(string.Format("./PrintFileTemp/{0}_{1}.{2}", dateTime.ToString("yyyy_MM_dd_HH_mm_ss"), name, fileNameExtension), FileMode.Create);
    
                if (m_streams.Count < 1)
                    m_streams.Add(stream);
    
                return stream;
            }
    
            /// <summary>
            /// 打印
            /// </summary>
            /// <param name="printerName"></param>
            private void Print(string printerName)
            {
                if (m_streams == null || m_streams.Count == 0)
                    return;
    
                PrintDocument printDoc = new PrintDocument();
                printDoc.PrinterSettings.PrinterName = printerName;
                if (!printDoc.PrinterSettings.IsValid)
                {
                    //ExecptionCallBack(new Exception($"未找到打印机 {printerName}"));
                    ExecptionCallBack(new Exception(string.Format("未找到打印机 {0}", printerName)));
                    return;
                }
    
    
                // 0.001 英寸 = 0.0254 厘米
                //           = 960cm 
    
                //printDoc.DefaultPageSettings.PaperSize = new PaperSize("Custom", 815, 400);
                printDoc.PrinterSettings.Copies = 1;
    
                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
                printDoc.Print();
            }
    
            /// <summary>
            /// 
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="ev"></param>
            private void PrintPage(object sender, PrintPageEventArgs ev)
            {
                Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]);
                ev.Graphics.DrawImage(pageImage, ev.PageBounds);
                ev.HasMorePages = false;
                ev.PageSettings.Landscape = true;
            }
    
            private void DeleteTempFile()
            {
                Dispose();
                foreach (var item in Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory + "PrintFileTemp"))
                {
                    try
                    {
                        File.Delete(item);
                    }
                    catch (Exception)
                    {
    
                    }
    
                }
            }
    
            /// <summary>
            /// 释放现有流资源
            /// </summary>
            public void Dispose()
            {
                if (m_streams != null)
                {
                    foreach (Stream stream in m_streams)
                        stream.Close();
                    m_streams = null;
                }
            }
        }
    

      

     以上就是三种打印方式。

     以上源码下载地址:https://download.csdn.net/download/qingchundaima/11125329

  • 相关阅读:
    Mysql设置字段唯一,值唯一方式
    在tomcat中模块化部署项目
    优化Eclipse
    akka 服务的搭建
    ES6中的let和var区别
    jquery,$,选择器,正则表达式
    jsp页面用java代码取随机数
    为什么要做权限管理
    将字符串编码成数值,求数值最大和问题
    Cookie与Session的区别
  • 原文地址:https://www.cnblogs.com/qiu18359243869/p/10736611.html
Copyright © 2011-2022 走看看