Beispiel #1
0
 private void Form_Print_FormClosed(object sender, FormClosedEventArgs e)
 {
     try
     {
         if (Directory.Exists(Config.TempleAddress))
         {
             Directory.Delete(Config.TempleAddress, true);
         }
         System.Environment.Exit(0);
     }
     catch (Exception ex)
     {
         XMessageBox.Error("删除临时文件失败:" + ex.Message);
     }
 }
Beispiel #2
0
        /// <summary>
        /// 产生注册脚本
        /// </summary>
        /// <returns></returns>
        private static bool GenerateRegisterFile()
        {
            try
            {
                var name    = ConfigurationManager.AppSettings["ProtocolName"];
                var appPath = ConfigurationManager.AppSettings["AppPath"];
                var baseDir = AppDomain.CurrentDomain.BaseDirectory;
                //判断协议是否已注册
                if (Registry.ClassesRoot.GetSubKeyNames().FirstOrDefault(n => n.Equals(name)) == null || string.IsNullOrEmpty(appPath) || !appPath.Equals(baseDir))
                {
                    var filePath = Path.Combine(baseDir, "注册应用.reg");
                    var appName  = Application.ExecutablePath;
                    using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
                    {
                        using (var st = new StreamWriter(stream, Encoding.GetEncoding("gb2312")))
                        {
                            StringBuilder content = new StringBuilder();
                            content.AppendLine("Windows Registry Editor Version 5.00");
                            content.AppendLine($"[HKEY_CLASSES_ROOT\\{name}]");
                            content.AppendLine($"@= \"{name}\"");
                            content.AppendLine($"\"URL Protocol\" = \"{appName.Replace("\\", "\\\\")}\"");
                            content.AppendLine($"[HKEY_CLASSES_ROOT\\{name}\\shell]");
                            content.AppendLine($"[HKEY_CLASSES_ROOT\\{name}\\shell\\open]");
                            content.AppendLine($"[HKEY_CLASSES_ROOT\\{name}\\shell\\open\\command]");
                            content.AppendLine($"@=\"\\\"{appName.Replace("\\", "\\\\")}\\\" \\\" %1\\\"\"");
                            st.Write(content.ToString());
                        }
                    }
                    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    config.AppSettings.Settings["AppPath"].Value = baseDir;
                    config.Save(ConfigurationSaveMode.Modified);

                    //System.Diagnostics.Process.Start(filePath);
                    if (File.Exists(filePath))
                    {
                        Process.Start("regedit", string.Format(" /s {0}", @"""" + filePath + @""""));
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                XMessageBox.Error(ex.Message);
                return(false);
            }
        }
Beispiel #3
0
        /// <summary>
        /// 初始化打印数据
        /// </summary>
        private void InitData()
        {
            //获取打印数据
            string address = Config.FullAddress.Replace("{batchNumber}", Config.BatchNumber);

            var data = GetPrintData(address);

            JObject obj = (JObject)JsonConvert.DeserializeObject(data);

            if (obj == null || obj["result"].ToString() == "False")
            {
                XMessageBox.Error("获取数据失败,请检查网络链接是否正常和模板参数是否设置正确。");
                return;
            }

            PrintData = JsonConvert.DeserializeObject <PrintDataModel>(obj["data"].ToString());

            using (var stream = new StreamWriter(Config.TemplateLocation(PrintData.PrintTemplate.FileName), false))
            {
                stream.Write(PrintData.FileContent);
            }

            if (PrintData != null && PrintData.Data != null && PrintData.Total > 0)
            {
                UpdateDataGridViewData(PrintData.Data);
                UpdateStatusBar($"加载数据:{PrintData.Data.Count}/{PrintData.Total}");
                int pageCount = PrintData.Total / 20;
                if (pageCount * 5 < PrintData.Total)
                {
                    pageCount += 1;
                }
                //从第二页开始获取数据
                for (int i = 2; i <= pageCount; i++)
                {
                    data = GetPrintData(address, i);
                    obj  = (JObject)JsonConvert.DeserializeObject(data);
                    var pData = JsonConvert.DeserializeObject <PrintDataModel>(obj["data"].ToString());
                    if (pData != null)
                    {
                        PrintData.Data.AddRange(pData.Data);
                        UpdateDataGridViewData(pData.Data);
                        UpdateStatusBar($"加载数据:{PrintData.Data.Count}/{PrintData.Total}");
                    }
                }
            }
        }
Beispiel #4
0
        private void InitData(int index)
        {
            PageSettings ps = Config.GetPageSettings();

            MyReportViewer.SetPageSettings(ps);
            MyReportViewer.LocalReport.ReportPath = Config.TemplateLocation(PrintData.PrintTemplate.FileName);

            Dictionary <string, object> item = new Dictionary <string, object>();

            if (PrintData != null && PrintData.Data.Count > 0)
            {
                item = PrintData.Data[index];
            }
            else
            {
                XMessageBox.Warning("未加载到数据");
                return;
            }

            MyReportViewer.LocalReport.DataSources.Clear();
            MyReportViewer.LocalReport.DataSources.Add(new ReportDataSource(PrintData.PrintTemplate.DataSetName, item.ToDataTable()));
            var printParams = PrintData.PrintTemplate.PrintParams;

            if (printParams.Count > 0)
            {
                int j = 0;
                foreach (var parameter in MyReportViewer.LocalReport.GetParameters())
                {
                    var    db_param = PrintData.PrintTemplate.PrintParams.Find(p => p.PrintParamName == parameter.Name);
                    string fileName = $"{PrintData.PrintTemplate.PrintTemplateID}_{db_param.Value}{index}{j++}";

                    switch (db_param.ParamType)
                    {
                    case ParamType.BarCode:
                        //创建条形码文件
                        fileName += "1D";
                        string value = CanCreateCode(db_param, item, out bool isCreate);

                        if (isCreate == false)
                        {
                            XMessageBox.Error($"值({value})不能生成条形码");
                        }

                        PrintReport.CreateBarCode(value, fileName, Config.TempleAddress);
                        break;

                    case ParamType.QRCode:
                        //创建二维码
                        fileName += "2D";
                        value     = CanCreateCode(db_param, item, out isCreate);

                        if (isCreate == false)
                        {
                            XMessageBox.Error($"值({value})不能生成条形码");
                        }
                        PrintReport.CreateQRCode(value, fileName, Config.TempleAddress);
                        break;

                    case ParamType.Other:

                        MyReportViewer.LocalReport.SetParameters(new ReportParameter
                                                                     (parameter.Name, Convert.ToString(item[db_param.Value])));
                        continue;

                    case ParamType.SQL:
                        value = "0";
                        if (item.ContainsKey(db_param.Value))
                        {
                            value = Convert.ToString(item[db_param.Value]);
                        }
                        MyReportViewer.LocalReport.SetParameters(new ReportParameter
                                                                     (parameter.Name, value));
                        continue;
                    }
                    var file = Path.Combine(Config.TempleAddress, fileName + ".bmp");
                    MyReportViewer.LocalReport.SetParameters(new ReportParameter(parameter.Name, "file://" + file));
                }
            }
            MyReportViewer.SetDisplayMode(DisplayMode.PrintLayout);
            MyReportViewer.ZoomMode    = ZoomMode.Percent;
            MyReportViewer.ZoomPercent = 100;
        }
Beispiel #5
0
        /// <summary>
        /// ReportViewer渲染完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReportView_RenderingComplete(object sender, Microsoft.Reporting.WinForms.RenderingCompleteEventArgs e)
        {
            if (e.Exception != null)
            {
                var exp = e.Exception;
                while (exp.InnerException != null)
                {
                    exp = exp.InnerException;
                }
                XMessageBox.Error(string.Format("无法打印:{0}", exp.Message));
                return;
            }

            ReportViewer rv = sender as ReportViewer;

            //rv.SetPageSettings(Config.GetPageSettings());
            #region 如果能直接打印了

            if (!PrintData.PrintTemplate.IsAppend || CanPrint != null && CanPrint.Value)
            {
                if (e.Exception == null && rv.LocalReport.DataSources.Count > 0)
                {
                    try
                    {
                        Export(rv.LocalReport);
                        printDocument1.DefaultPageSettings = Config.GetPageSettings();
                        printDocument1.PrinterSettings     = Config.GetPrintSettings();
                        printDocument1.Print();
                        StreamDispose();
                    }
                    catch (Exception exp)
                    {
                        XMessageBox.Warning(string.Format("无法打印:{0}", exp.Message));
                        //XMessageBox.Warning(string.Format("无法打印:{0}", exp.Message));
                    }
                }

                return;
            }

            #endregion

            #region 往页后面追加行
            if (PrintData.PrintTemplate.IsAppend)
            {
                var totalPages = rv.GetTotalPages();

                if (LastPageCount == null)
                {
                    LastPageCount = totalPages;
                }
                var dt = rv.LocalReport.DataSources[0].Value as DataTable;
                if (LastPageCount == totalPages)
                {
                    dt.Rows.Add(dt.NewRow());
                }
                else
                {
                    dt.Rows.RemoveAt(dt.Rows.Count - 1);
                    CanPrint = true;
                }
                rv.RefreshReport();
                return;
            }


            #endregion
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //RegisterApp();

            if (!GenerateRegisterFile())
            {
                return;
            }

            if (args.Length == 0)
            {
                args    = new string[1];
                args[0] = "";
                //args[0] = "CSCOOLDE://PrintSetting;2";//打印设置
                //args[0] = "cscoolde://Print;http://localhost:64782/;20210118182736190896;6";//打印
                args[0] = "cscoolde://PrintPreview;http://localhost:64782/;20210118182736190896;6";
                //
                //XMessageBox.Error("未找到参数");
            }

            if (string.IsNullOrWhiteSpace(args[0]) || !args[0].Contains(";"))
            {
                XMessageBox.Error($"参数不对:{args[0]}");
                return;
            }

            //MessageBox.Show($"{args[0]},长度{args[0].Length}");
            var pars = args[0].Trim().Split(';');

            //多模板打印
            if (pars.Length > 2 && pars[2].Contains('&'))
            {
                string[] batchNumbers = pars[2].Split('&');
                foreach (var bn in batchNumbers)
                {
                    if (string.IsNullOrEmpty(bn))
                    {
                        continue;
                    }
                    string           str       = bn.Replace(',', ';');
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.FileName    = Application.ExecutablePath; //启动的应用程序名称
                    startInfo.Arguments   = $"{pars[0]};{pars[1]};{str}";
                    startInfo.WindowStyle = ProcessWindowStyle.Normal;
                    Process.Start(startInfo);
                }
                return;
            }
            Form form;

            switch (pars[0].ToLower())
            {
            //打印设置
            case @"cscoolde://printsetting":
                form = new Form_PrintSetting(pars[1].TrimEnd('/'));
                break;

            //打印
            case @"cscoolde://print":
                form = new Form_Main(pars[1], pars[2], pars[3].TrimEnd('/'), false);
                break;

            //打印预览
            case "cscoolde://printpreview":
                form = new Form_Main(pars[1], pars[2], pars[3].TrimEnd('/'), true);
                break;

            default:
                XMessageBox.Error($"Type:({pars[0]})");
                return;
            }
            if (form != null)
            {
                Application.Run(form);
            }
        }
Beispiel #7
0
        private void btn_save_Click(object sender, EventArgs e)
        {
            try
            {
                #region 参数校验

                if (this.cmbPrinter.SelectedItem == null)
                {
                    XMessageBox.Warning("请选择打印机");
                    return;
                }
                if (this.cmbPaper.SelectedItem == null)
                {
                    XMessageBox.Warning("请选择打印纸张");
                    return;
                }

                if (!double.TryParse(this.tbPaperWidth.Text, out double nw) || !double.TryParse(this.tbPaperHeight.Text, out double nh) || nw <= 0 || nh <= 0)
                {
                    XMessageBox.Warning("请输入正确的纸张高度和宽度,宽度和高度必须大于零");
                    return;
                }

                if (!double.TryParse(this.tbMarginBottom.Text, out double mb) || !double.TryParse(this.tbMarginRight.Text, out double mr) || !double.TryParse(this.tbMarginLeft.Text, out double ml) || !double.TryParse(this.tbMarginTop.Text, out double mt) || mt < 0 || mb < 0 || ml < 0 || mr < 0)
                {
                    XMessageBox.Warning("请输入正确的页边距,上下左右边距必须大于等于零");
                    return;
                }

                if (nh - mt - mb <= 0 || Math.Abs(nh - mt - mb) / (double)nh < 0.2)
                {
                    XMessageBox.Warning("上下边距太大,可打印区域太小,请重新设置上下边距");
                    return;
                }

                if (nw - mr - ml <= 0 || Math.Abs(nw - mr - ml) / (double)nw < 0.2)
                {
                    XMessageBox.Warning("左右边距太大,可打印区域太小,请重新设置左右边距");
                    return;
                }

                #endregion

                PrinterSettings ps = cmbPrinter.SelectedItem as PrinterSettings;
                var             pz = cmbPaper.SelectedItem as PaperSize;
                ps.DefaultPageSettings.PaperSize = pz;
                if (pz.PaperName.Equals("自定义纸张"))
                {
                    pz.Width  = (int)Config.Mm2Inch(Convert.ToDouble(tbPaperWidth.Text));
                    pz.Height = (int)Config.Mm2Inch(Convert.ToDouble(tbPaperHeight.Text));
                }
                ps.DefaultPageSettings.Margins = new Margins
                {
                    Top    = (int)Config.Mm2Inch(Convert.ToDouble(tbMarginTop.Text)),
                    Bottom = (int)Config.Mm2Inch(Convert.ToDouble(tbMarginBottom.Text)),
                    Left   = (int)Config.Mm2Inch(Convert.ToDouble(tbMarginLeft.Text)),
                    Right  = (int)Config.Mm2Inch(Convert.ToDouble(tbMarginRight.Text))
                };
                ps.DefaultPageSettings.Landscape = this.rbLanscape.Checked;

                RawPrintSetting rps = new RawPrintSetting();
                rps.LandScape   = this.rbLanscape.Checked;
                rps.PageMargins = ps.DefaultPageSettings.Margins;
                rps.PaperName   = ps.DefaultPageSettings.PaperSize.PaperName;
                rps.PaperSize   = pz;
                rps.PrinterName = ps.PrinterName;



                XMessageBox.Info(Config.SaveSetting(rps));
            }
            catch (Exception exp)
            {
                XMessageBox.Error(string.Format("保存打印设置失败:{0}", exp.Message));
            }
        }