public void firstLayerSpeedEqualsAcceptableValue(PrinterSettings settings, PrinterSettingsLayer layer, string sourceFile)
		{
			string firstLayerSpeedString;
			if (!layer.TryGetValue(SettingsKey.first_layer_speed, out firstLayerSpeedString))
			{
				return;
			}

			double firstLayerSpeed;
			if (firstLayerSpeedString.Contains("%"))
			{
				string infillSpeedString = settings.GetValue("infill_speed");
				double infillSpeed = double.Parse(infillSpeedString);

				firstLayerSpeedString = firstLayerSpeedString.Replace("%", "");

				double FirstLayerSpeedPercent = double.Parse(firstLayerSpeedString);

				firstLayerSpeed = FirstLayerSpeedPercent * infillSpeed / 100.0;
			}
			else
			{
				firstLayerSpeed = double.Parse(firstLayerSpeedString);
			}

			Assert.Greater(firstLayerSpeed, 5, "Unexpected firstLayerSpeedEqualsAcceptableValue value: " + sourceFile);
		}
		internal static PrintLevelingData Create(PrinterSettings printerProfile, string jsonData, string depricatedPositionsCsv3ByXYZ)
		{
			if (!string.IsNullOrEmpty(jsonData))
			{
				var deserialized = JsonConvert.DeserializeObject<PrintLevelingData>(jsonData);
				deserialized.printerProfile = printerProfile;

				return deserialized;
			}
			else if (!string.IsNullOrEmpty(depricatedPositionsCsv3ByXYZ))
			{
				var item = new PrintLevelingData(ActiveSliceSettings.Instance);
				item.printerProfile = printerProfile;
				item.ParseDepricatedPrintLevelingMeasuredPositions(depricatedPositionsCsv3ByXYZ);

				return item;
			}
			else
			{
				return new PrintLevelingData(ActiveSliceSettings.Instance)
				{
					printerProfile = printerProfile
				};
			}
		}
示例#3
0
文件: test.cs 项目: mono/gert
	static int Main ()
	{
		PrinterSettings settings = new PrinterSettings ();
		if (settings == null) {
		}
		return 0;
	}
示例#4
0
	public static void Main (string[] args)
	{
		PrinterSettings.StringCollection col = System.Drawing.Printing.PrinterSettings.InstalledPrinters;
		
		for (int i = 0; i < col.Count; i++) {
			
			Console.WriteLine ("--- {0}", col[i]);
			PrinterSettings ps = new PrinterSettings ();
			ps.PrinterName = col[i];
			//Console.WriteLine ("    Duplex: {0}", ps.Duplex);
			Console.WriteLine ("    FromPage: {0}", ps.FromPage);
			Console.WriteLine ("    ToPage: {0}", ps.ToPage);
			Console.WriteLine ("    MaximumCopies: {0}", ps.MaximumCopies);
			Console.WriteLine ("    IsDefaultPrinter: {0}", ps.IsDefaultPrinter);
			Console.WriteLine ("    SupportsColor: {0}", ps.SupportsColor);
			Console.WriteLine ("    MaximumPage {0}", ps.MaximumPage);
			Console.WriteLine ("    MinimumPage {0}", ps.MinimumPage);
			Console.WriteLine ("    LandscapeAngle {0}", ps.LandscapeAngle);
			/*				
			for (int p = 0; p < ps.PrinterResolutions.Count; p++) {
				Console.WriteLine ("        PrinterResolutions {0}", ps.PrinterResolutions [p]);
			}*/		
			
			for (int p = 0; p < ps.PaperSizes.Count; p++) {
				Console.WriteLine ("        PaperSize Name [{0}] Kind [{1}] Width {2} Height {3}", 
					ps.PaperSizes [p].PaperName, ps.PaperSizes [p].Kind,
					ps.PaperSizes [p].Width, ps.PaperSizes [p].Height);
			}
		}
	}
 public static string GetDefaultPrinterName()
 {
     PrinterSettings settings = new PrinterSettings();
     foreach (string printer in PrinterSettings.InstalledPrinters)
     {
         settings.PrinterName = printer;
         if (settings.IsDefaultPrinter)
             return printer;
     }
     return string.Empty;
 }
示例#6
0
    static void Main(string[] args)
    {
        Console.WriteLine("----- debugger start\n");

        var printer = new PrinterSettings();
        Console.WriteLine(printer.IsDefaultPrinter);
        Console.WriteLine(printer.IsValid);
        Console.WriteLine(printer.PrinterName);

        Console.WriteLine("\n----- debugger finish");
    }
示例#7
0
        private string DefaultPrinterName()
        {
            string functionReturnValue = null;
            var oPS = new PrinterSettings();

            try
            {
                functionReturnValue = oPS.PrinterName;
            }
            catch (System.Exception ex)
            {
                functionReturnValue = "";
            }
            finally
            {
                oPS = null;
            }
            return functionReturnValue;
        }
		public static void ImportPrinter(Printer printer, ProfileManager profileData, string profilePath)
		{
			var printerInfo = new PrinterInfo()
			{
				Name = printer.Name,
				ID = printer.Id.ToString(),
				Make = printer.Make ?? "",
				Model = printer.Model ?? "",
			};
			profileData.Profiles.Add(printerInfo);

			var printerSettings = new PrinterSettings()
			{
				OemLayer = LoadOemLayer(printer)
			};

			printerSettings.OemLayer[SettingsKey.make] = printerInfo.Make;
			printerSettings.OemLayer[SettingsKey.model] = printer.Model;

			LoadQualitySettings(printerSettings, printer);
			LoadMaterialSettings(printerSettings, printer);

			printerSettings.ID = printer.Id.ToString();

			printerSettings.UserLayer[SettingsKey.printer_name] = printer.Name ?? "";
			printerSettings.UserLayer[SettingsKey.baud_rate] = printer.BaudRate ?? "";
			printerSettings.UserLayer[SettingsKey.auto_connect] = printer.AutoConnect ? "1" : "0";
			printerSettings.UserLayer[SettingsKey.default_material_presets] = printer.MaterialCollectionIds ?? "";
			printerSettings.UserLayer[SettingsKey.windows_driver] = printer.DriverType ?? "";
			printerSettings.UserLayer[SettingsKey.device_token] = printer.DeviceToken ?? "";
			printerSettings.UserLayer[SettingsKey.device_type] = printer.DeviceType ?? "";

			if (string.IsNullOrEmpty(ProfileManager.Instance.LastProfileID))
			{
				ProfileManager.Instance.SetLastProfile(printer.Id.ToString());
			}

			printerSettings.UserLayer[SettingsKey.active_theme_name] = UserSettings.Instance.get(UserSettingsKey.ActiveThemeName);

			// Import macros from the database
			var allMacros =  Datastore.Instance.dbSQLite.Query<CustomCommands>("SELECT * FROM CustomCommands WHERE PrinterId = " + printer.Id);
			printerSettings.Macros = allMacros.Select(macro => new GCodeMacro()
			{
				GCode = macro.Value.Trim(),
				Name = macro.Name,
				LastModified = macro.DateLastModified
			}).ToList();

			string query = string.Format("SELECT * FROM PrinterSetting WHERE Name = 'PublishBedImage' and PrinterId = {0};", printer.Id);
			var publishBedImage = Datastore.Instance.dbSQLite.Query<PrinterSetting>(query).FirstOrDefault();

			printerSettings.UserLayer[SettingsKey.publish_bed_image] = publishBedImage?.Value == "true" ? "1" : "0";

			// Print leveling
			var printLevelingData = PrintLevelingData.Create(
				printerSettings, 
				printer.PrintLevelingJsonData, 
				printer.PrintLevelingProbePositions);

			printerSettings.UserLayer[SettingsKey.print_leveling_data] = JsonConvert.SerializeObject(printLevelingData);
			printerSettings.UserLayer[SettingsKey.print_leveling_enabled] = printer.DoPrintLeveling ? "true" : "false";

			printerSettings.UserLayer["manual_movement_speeds"] = printer.ManualMovementSpeeds;

			// make sure we clear the one time settings
			printerSettings.OemLayer[SettingsKey.spiral_vase] = "";
			printerSettings.OemLayer[SettingsKey.bottom_clip_amount] = "";
			printerSettings.OemLayer[SettingsKey.layer_to_pause] = "";

			// TODO: Where can we find CalibrationFiiles in the current model?
			//layeredProfile.SetActiveValue(""calibration_files"", ???);

			printerSettings.ID = printer.Id.ToString();

			printerSettings.DocumentVersion = PrinterSettings.LatestVersion;

			printerSettings.Helpers.SetComPort(printer.ComPort);

			printerSettings.Save();
		}
示例#9
0
        private void CreateProductDataWidgets(PrinterSettings printerSettings, ProductSkuData product)
        {
            var row = new FlowLayoutWidget()
            {
                HAnchor = HAnchor.Stretch,
                Margin  = new BorderDouble(top: theme.DefaultContainerPadding)
            };

            productDataContainer.AddChild(row);

            var image = new ImageBuffer(150, 10);

            row.AddChild(new ImageWidget(image)
            {
                Margin  = new BorderDouble(right: theme.DefaultContainerPadding),
                VAnchor = VAnchor.Top
            });

            WebCache.RetrieveImageAsync(image, product.FeaturedImage.ImageUrl, scaleToImageX: true);

            var descriptionBackground = new GuiWidget()
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit | VAnchor.Top,
                Padding = theme.DefaultContainerPadding
            };

            var description = new MarkdownWidget(theme)
            {
                MinimumSize = new VectorMath.Vector2(350, 0),
                HAnchor     = HAnchor.Stretch,
                VAnchor     = VAnchor.Fit,
                Markdown    = product.ProductDescription.Trim()
            };

            descriptionBackground.AddChild(description);
            descriptionBackground.BeforeDraw += (s, e) =>
            {
                var rect = new RoundedRect(descriptionBackground.LocalBounds, 3);
                e.Graphics2D.Render(rect, theme.SlightShade);
            };

            row.AddChild(descriptionBackground);

            var padding = theme.DefaultContainerPadding;

            var addonsColumn = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                Padding = new BorderDouble(padding, padding, padding, 0),
                HAnchor = HAnchor.Stretch
            };

            var addonsSection = new SectionWidget("Upgrades and Accessories", addonsColumn, theme);

            productDataContainer.AddChild(addonsSection);
            theme.ApplyBoxStyle(addonsSection);
            addonsSection.Margin = addonsSection.Margin.Clone(left: 0);

            foreach (var item in product.ProductListing.AddOns)
            {
                var icon = new ImageBuffer(80, 0);
                WebCache.RetrieveImageAsync(icon, item.FeaturedImage.ImageUrl, scaleToImageX: true);

                var addOnRow = new AddOnRow(item.AddOnTitle, theme, null, icon)
                {
                    HAnchor = HAnchor.Stretch,
                    Cursor  = Cursors.Hand
                };

                foreach (var child in addOnRow.Children)
                {
                    child.Selectable = false;
                }

                addOnRow.Click += (s, e) =>
                {
                    ApplicationController.Instance.LaunchBrowser($"https://www.matterhackers.com/store/l/{item.AddOnListingReference}/sk/{item.AddOnSkuReference}");
                };

                addonsColumn.AddChild(addOnRow);
            }

            if (false)
            {
                var settingsPanel = new GuiWidget()
                {
                    HAnchor         = HAnchor.Stretch,
                    VAnchor         = VAnchor.Stretch,
                    MinimumSize     = new VectorMath.Vector2(20, 20),
                    DebugShowBounds = true
                };

                settingsPanel.Load += (s, e) =>
                {
                    var printer = new PrinterConfig(printerSettings);

                    var settingsContext = new SettingsContext(
                        printer,
                        null,
                        NamedSettingsLayers.All);

                    settingsPanel.AddChild(
                        new ConfigurePrinterWidget(settingsContext, printer, theme)
                    {
                        HAnchor = HAnchor.Stretch,
                        VAnchor = VAnchor.Stretch,
                    });
                };

                this.AddChild(new SectionWidget("Settings", settingsPanel, theme, expanded: false, setContentVAnchor: false)
                {
                    VAnchor = VAnchor.Stretch
                });
            }
        }
示例#10
0
        static void Main(string[] args)
        {
            {
                string xml        = @"
<store>
    <name>store1</name>
    <books>
        <book>
            <name>book1</name>
            <desc>good book</desc>
            <date>2014</date>
        </book>
        <book>
            <name>book2</name>
            <desc>better book</desc>
            <date>2015</date>
        </book>
        <book>
            <name>book3</name>
            <desc>best book</desc>
            <date>2016</date>
        </book>
    </books>
</store>
";
                var    serializer = new XmlSerializer(typeof(store));
                using (var textReader = new StringReader(xml))
                {
                    {
                        XmlReaderSettings settings = new XmlReaderSettings();
                        using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
                        {
                            var store = (store)serializer.Deserialize(xmlReader);
                        }
                    }
                }



                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(xml);
            }

            {
                List <CusotmerInfo> customers = new List <CusotmerInfo>();
                customers.Add(new CusotmerInfo()
                {
                    FirstName = "first1", LastName = "last1", Code = "f1"
                });
                customers.Add(new CusotmerInfo()
                {
                    FirstName = "first2", LastName = "last2", Code = "f2"
                });
                customers.Add(new CusotmerInfo()
                {
                    FirstName = "first3", LastName = "last3", Code = "f3"
                });
                customers.Add(new CusotmerInfo()
                {
                    FirstName = "first4", LastName = "last4", Code = "f4"
                });

                foreach (var cust in customers.ToList())
                {
                    string code = cust.Code;

                    customers.Add(new CusotmerInfo()
                    {
                        FirstName = "first5", LastName = "last5", Code = "f5"
                    });
                }


                return;
            }


            {
                List <string> s1 = new List <string>()
                {
                    "a", "b", "c"
                };
                List <string> s2 = s1;
                List <string> s3 = new List <string>(s1);

                s2[1] = "bbbbb";
                s3[1] = "zzzzz";

                return;
            }


            {
                var section = ConfigurationManager.GetSection("server") as NameValueCollection;
                var value   = section["url"];

                Console.WriteLine(string.Format("url={0}", value));
                Console.Read();
            }
            return;

            {
                foreach (int list in Lists())
                {
                    int i = list;
                    int j = i;
                }
            }

            {
                string s              = "Dave56678";
                string base64string   = Base64.Base64.Base64Encode(s);
                string mybase64string = Base64.Base64.MyBase64Encode(s);

                string text   = "Dave56678";
                byte[] bytes  = System.Text.Encoding.ASCII.GetBytes(text);
                string base64 = System.Convert.ToBase64String(bytes);

                byte[] bytes2 = System.Convert.FromBase64String(base64);

                return;
            }

            {
                List <string> lines = new List <string>();
                lines.Add("safassa saf safa f1");
                lines.Add("safassa saf safa f2");
                lines.Add("safassa saf safa f3");
                lines.Add("safassa saf safa f4");
                lines.Add("safassa saf safa f5");
                lines.Add("safassa saf safa f6");

                string result = string.Join("\r\n", lines);

                return;
            }

            {
                Class1.Instance.GetStr();
                Class1.Instance.GetStr();
                Class1.Instance.GetStr();
            }

            return;


            {
                try
                {
                    string apiToken = "000qhx6S4jDT0Eo0ZNbpE1WnGpJi-89A1yUfJYD-R5";
                    string uri      = "https://dev-598383.oktapreview.com";

                    var oktaClient = new OktaClient(apiToken, new Uri(uri));

                    var groupsClient = oktaClient.GetGroupsClient();
                    var groups       = groupsClient.GetList();



                    var usersClient = oktaClient.GetUsersClient();

                    var user = usersClient.Get("*****@*****.**");

                    var groupsUsersClient = oktaClient.GetUserGroupsClient(user);



                    ////user.GetProperty("mycustom_attr");
                    //user.SetProperty("mycustom_attr", "1234");
                    //user = usersClient.Update(user);



                    //var filter = new FilterBuilder()
                    //                .Where(Filters.User.Status)
                    //                .EqualTo(UserStatus.Active)
                    //                .And()
                    //                .Where(Filters.User.LastUpdated)
                    //                .GreaterThanOrEqual(new DateTime(2016, 5, 3));

                    //foreach (User user in usersClient.GetFilteredEnumerator(filter))
                    //{
                    //    var profile = user.Profile;
                    //}


                    //foreach(var user in usersClient)
                    //{
                    //    var profile = user.Profile; // Do something with each user
                    //}

                    //var users = usersClient.GetList();

                    //var user = new User("*****@*****.**", "*****@*****.**", "New", "User");

                    //// Create and activate the user
                    //user = usersClient.Add(user);

                    //// Retrieve the user
                    //user = usersClient.Get("*****@*****.**");

                    //// Update the user's first name
                    //user.Profile.FirstName = "Old";
                    //user = usersClient.Update(user);
                }
                catch (Exception ex)
                {
                    if (ex is OktaException)
                    {
                        var oktaEx = (OktaException)ex;
                    }
                }

                return;
                //var usersClient = new UsersClient(apiToken, subDomain);
            }



            {
                var folder1 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData);


                return;
            }


            {
                string sessionToken = "9f317e9e-8aad-4eed-a6a6-49d492276162";
                string userName     = "******";

                bool isTokenValid = false;

                HttpClient client     = new HttpClient();
                string     requestUri = string.Format("{0}/{1}", "http://localhost/craservice.mosaic2.8.2000", "api/auth/ValidateToken");

                HttpRequestMessage request = new HttpRequestMessage();
                request.Method     = HttpMethod.Get;
                request.RequestUri = new Uri(requestUri);
                request.Headers.Add("X-RM-API-TOKEN", sessionToken);

                HttpResponseMessage response = client.SendAsync(request).Result;
                string responseStr           = response.Content.ReadAsStringAsync().Result;
                responseStr = @"{""IsTokenValid"":true,""AppSecUserName"":""ravi"",""StaffCode"":""ravi"",""LastActiveTime"":""2016-04-14T15:27:31.804698Z""}";
                responseStr = @"{""IsTokenValid"":true,""AppSecUserName"":""ravi"",""StaffCode"":""ravi"",""LastActiveTime"":""2015-08-31T07:05:58-07:00""}";
                responseStr = @"{""IsTokenValid"":true,""AppSecUserName"":""ravi"",""StaffCode"":""ravi"",""LastActiveTime"":""2015-08-31T03:10:00Z""}";
                var tokenResponse = JsonConvert.DeserializeObject <ValidateCraTokenResponse>(responseStr);

                if (tokenResponse != null)
                {
                    if (tokenResponse.IsTokenValid &&
                        (string.Compare(tokenResponse.AppSecUserName, userName, true) == 0 ||
                         string.Compare(tokenResponse.StaffCode, userName, true) == 0))
                    {
                        isTokenValid = true;
                    }
                }

                return;
            }


            {
                for (int j = 1; j < 50; j++)
                {
                    ProcessStartInfo i = new ProcessStartInfo();
                    i.UseShellExecute = true;
                    i.WindowStyle     = ProcessWindowStyle.Normal;
                    i.CreateNoWindow  = false;
                    i.FileName        = @"C:\Program Files (x86)\Raymark\XIP\Raymark.XIP.PrinterApp.exe";
                    i.Arguments       = @"/s V-AQUARIUS\SQL2012 /d Merch_DEV_2_7 /u RaymApp /p raym /store 3 /transnum 2 /cais 473 /transtype ""SALE"" /app ""XPERT"" /preview N /nbcopies 1 /printer_name ""Microsoft XPS Document Writer""";

                    Process pp = Process.Start(i);
                }

                return;
            }

            {
                string from = "Thu Oct 08 2015 00:00:00 GMT1100 (AUS Eastern Daylight Time)";
                string to   = "Fri Jan 08 2016 00:00:00 GMT1100 (AUS Eastern Daylight Time)";

                //string from = "Wed Oct 07 2015 00:00:00 GMT-0400 (Eastern Daylight Time)";
                //string to = "Thu Jan 07 2016 00:00:00 GMT-0500 (Eastern Standard Time)";


                DateTime fromDate = DateTime.Now;
                DateTime toDate   = DateTime.Now;

                fromDate = DateTime.Parse(from);


                if (from != null)
                {
                    string trim = from.Substring(0, from.IndexOf(" ("));
                    fromDate = DateTime.ParseExact(trim, "ddd MMM dd yyyy HH:mm:ss 'GMT'zzz", CultureInfo.InvariantCulture);
                }

                if (to != null)
                {
                    string trim = to.Substring(0, to.IndexOf(" ("));
                    toDate = DateTime.ParseExact(trim, "ddd MMM dd yyyy hh:mm:ss 'GMT'zzz", CultureInfo.InvariantCulture);
                    toDate = toDate.AddHours(24);
                }
            }

            {
                // this is what we are sending
                string post_data = ""; // "foo=bar&baz=oof";

                // this is where we will send it
                string uri = "https://pos.cherrera.com/PosService.rest-training/posservice.svc/get-service-info";

                // create a request
                HttpWebRequest request = (HttpWebRequest)
                                         WebRequest.Create(uri); request.KeepAlive = false;
                request.ProtocolVersion = HttpVersion.Version10;
                request.Method          = "POST";

                // turn our request string into a byte stream
                byte[] postBytes = Encoding.ASCII.GetBytes(post_data);

                // this is important - make sure you specify type this way
                //request.ContentType = "application/x-www-form-urlencoded";
                request.ContentType   = "application/json";
                request.ContentLength = postBytes.Length;
                Stream requestStream = request.GetRequestStream();

                // now send it
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Close();

                // grab te response and print it out to the console along with the status code
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
                Console.WriteLine(response.StatusCode);

                return;
            }


            {
                MakeHTTPSPostCall("https://pos.cherrera.com/PosService.rest-training/posservice.svc/get-service-info", "");

                return;
            }


            {
                decimal?d1 = 1.0M;
                decimal?d2 = 2.0M;

                decimal d3 = d1 + d2 ?? 0M;
            }

            {
                DateTime now = DateTime.Now;

                DateTime newDate  = now.AddYears(1901 - now.Year);
                DateTime newDate2 = newDate.AddYears(1901);
            }


            {
                List <Product> products = new List <Product>()
                {
                    new Product()
                    {
                        Quantity = 1.0M
                    },
                    new Product()
                    {
                        Quantity = 2.0M
                    },
                    new Product()
                    {
                        Quantity = 3.0M
                    },
                    new Product()
                };

                decimal?sum = products.Sum(e => e.Quantity);
            }

            {
                const string file = "cmd.exe";

                var sspw = new SecureString();

                foreach (var c in "cwj109@gmail")
                {
                    sspw.AppendChar(c);
                }

                var proc = new Process();

                proc.StartInfo.UseShellExecute = false;

                proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(file);

                proc.StartInfo.FileName = Path.GetFileName(file);

                proc.StartInfo.Domain          = "raymarkx.com";
                proc.StartInfo.Arguments       = "";
                proc.StartInfo.UserName        = "******";
                proc.StartInfo.Password        = sspw;
                proc.StartInfo.LoadUserProfile = false;
                proc.Start();
            }


            {
                bool   isHosted = true;
                string rootDir  = @"\\server\image";

                if (isHosted)
                {
                    const string fileIdentifier  = @":\";
                    string       httpPath        = string.Empty;
                    string       imageServerHttp = @"http://hostname/";
                    imageServerHttp = (imageServerHttp == null ? "http:/localhost/" : imageServerHttp);

                    int startPos = rootDir.IndexOf(fileIdentifier) + fileIdentifier.Length;
                    if (startPos < rootDir.Length)
                    {
                        httpPath = imageServerHttp + rootDir.Substring(startPos).Replace("\\", "/");
                    }

                    if (httpPath.Substring(httpPath.Length - 1, 1) != "//")
                    {
                        httpPath += "//";
                    }
                    rootDir = httpPath;
                }

                //Do some adjustment of this parameter if this parameter's value is not end with '/'
                if (string.IsNullOrEmpty(rootDir))
                {
                    throw new Exception("Parameter {0} is not set correctly.");
                }
                else
                {
                    //if (sessionContext.IsHosted == false && rootDir.Substring(rootDir.Length - 1, 1) != "\\")
                    if (isHosted == false && rootDir.Substring(rootDir.Length - 1, 1) != "\\")
                    {
                        rootDir += "\\";
                    }
                }
            }



            {
                string path = @"\\aleph";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }


            {
                DateTimeFormatInfo dateTimeInfo = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;

                DateTimeFormatInfo dateTimeInfo1 = DateTimeFormatInfo.CurrentInfo;

                string ampm  = DateTime.Now.ToString("tt");
                string time1 = DateTime.Now.ToString("hh:mm", DateTimeFormatInfo.InvariantInfo);
                string time2 = DateTime.Now.ToString("hh:mm:ss tt", DateTimeFormatInfo.InvariantInfo);
            }
            return;

            {
                CultureInfo cul = new CultureInfo("zh-CN");
                //CultureInfo cul = new CultureInfo("en-US");

                System.Threading.Thread.CurrentThread.CurrentCulture = cul;

                string time1 = DateTime.Now.ToString("hh:mm", DateTimeFormatInfo.InvariantInfo);
                string time2 = DateTime.Now.ToString("hh:mm:ss tt", DateTimeFormatInfo.InvariantInfo);
            }
            return;

            {
                decimal?quantity = null;

                decimal a = Math.Abs(quantity ?? 10M);

                int int1 = 10;
                int1 = Convert.ToInt32(quantity);

                if (quantity == 0)
                {
                    throw new Exception("");
                }

                decimal?qty1 = quantity;

                decimal qty = quantity.Value;
            }


            {
                string colorDescription = "color Description";
                string storeName        = "store Name";
                string storeCode        = "store Code";

                StringBuilder builder = new StringBuilder();

                builder.AppendFormat(@"{{""ColorDescription"":""{0}"",""StoreCode"":""{1}"",""StoreName"":""{2}""",
                                     colorDescription, storeCode, storeName);
            }
            return;

            {
                //////////////////////////////////////////////
                //string email = @"*****@*****.**";
                //string email = @"*****@*****.**";
                string      email       = @"*****@*****.**";
                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress(email);
                mailMessage.To.Add(email);


                mailMessage.Subject    = "Raymark PMW Notification: Task # has been pushed to you";
                mailMessage.IsBodyHtml = true;

                //string MailBody = @" test body";


                //MailBody = MailBody.Replace("%RECIPIENTNAME%", staffToName);
                //MailBody = MailBody.Replace("%TASKNUMBER%", taskNum.ToString());
                //MailBody = MailBody.Replace("%SENDER%", staffFromName);
                //MailBody = MailBody.Replace("%DESCRIPTION%", tasksShortDescription);
                ////  MailBody = MailBody.Replace("%TASKNUMBER%", dtTask.Rows[0]["IssuePriority"].ToString());
                //MailBody = MailBody.Replace("%DURATION%", assignedHours);
                //MailBody = MailBody.Replace("%DATE%", tasksFromDate);
                //MailBody = MailBody.Replace("%WO%", woId);
                //MailBody = MailBody.Replace("%CUSTOMERNAME%", customerId);


                mailMessage.Body = "<h1>test body</h1>";

                SmtpClient Sc = new SmtpClient("colorado");

                //Sc.Credentials = new NetworkCredential(@"raymarkx.com\infos", "d4mph0u553");


                Sc.Send(mailMessage);
            }
            return;


            {
                string input = "normal1";

                ProcessWindowStyle?printMethod = null;
                ProcessWindowStyle printMethod1;
                if (Enum.TryParse <ProcessWindowStyle>(input, out printMethod1))
                {
                    printMethod = printMethod1;
                }

                testfunc("1", printMethod);
            }
            return;

            {
                PrintDocument printDoc = new PrintDocument();

                // Add list of installed printers found to the combo box.
                // The pkInstalledPrinters string will be used to provide the display string.
                int    i;
                string pkInstalledPrinters;

                PrinterSettings set = new PrinterSettings();

                string name = set.PrinterName;

                for (i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
                {
                    pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
                    //comboInstalledPrinters.Items.Add(pkInstalledPrinters);
                    if (printDoc.PrinterSettings.IsDefaultPrinter)
                    {
                        string t = printDoc.PrinterSettings.PrinterName;
                    }
                }
            }
            return;



            {
                ProcessStartInfo info1 = new ProcessStartInfo();
                info1.Verb           = "print";
                info1.FileName       = @"C:\Temp\lov.pdf";
                info1.CreateNoWindow = true;
                info1.WindowStyle    = ProcessWindowStyle.Hidden;
                info1.Arguments      = " /T DEV";

                Process p = new Process();
                p.StartInfo = info1;
                p.Start();

                //p.WaitForInputIdle();
                //System.Threading.Thread.Sleep(3000);
                //if (false == p.CloseMainWindow())
                //	p.Kill();
            }
            return;



            {
                ProcessStartInfo i = new ProcessStartInfo();
                i.UseShellExecute = true;
                i.WindowStyle     = ProcessWindowStyle.Normal;
                i.CreateNoWindow  = false;
                i.FileName        = @"D:\Projects\Wen.Try2012\WenTest\WindowsFormsApplication1\bin\Debug\WindowsFormsApplication1.exe";
                //i.FileName = @"Notepad.exe";
                i.Arguments = "";

                i.UseShellExecute = false;
                i.Domain          = "raymarkx.com";
                i.UserName        = "******";
                //i.Password = "******";
                SecureString ssPwd    = new SecureString();
                string       password = "******";
                for (int x = 0; x < password.Length; x++)
                {
                    ssPwd.AppendChar(password[x]);
                }

                ssPwd.MakeReadOnly();
                i.Password = ssPwd;

                Process pp = Process.Start(i);
            }
            return;


            //////////////////////////////////////////////////

            {
                List <Address> addressList = new List <Address>();

                int pageSize  = 2;
                int pageIndex = 0;

                int startIndex = pageSize * pageIndex;
                int endIndex   = pageSize * (pageIndex + 1) - 1;


                addressList.Add(new Address()
                {
                    Line1 = "1"
                });
                addressList.Add(new Address()
                {
                    Line1 = "2"
                });
                addressList.Add(new Address()
                {
                    Line1 = "3"
                });
                addressList.Add(new Address()
                {
                    Line1 = "4"
                });
                addressList.Add(new Address()
                {
                    Line1 = "5"
                });
                addressList.Add(new Address()
                {
                    Line1 = "6"
                });

                List <Address> newList = addressList.Where((e, index) => index >= startIndex && index <= endIndex).ToList();

                int[] numbers         = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
                var   firstBigNumbers = numbers.TakeWhile((n, index) => n >= index);



                CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("CA");


                String pkInstalledPrinters;
                for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
                {
                    pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
                    Console.WriteLine(pkInstalledPrinters);
                }


                char cha = char.Parse("\t");

                string str = @"s\ty";
                foreach (char c in str)
                {
                    char ch = c;
                }

                CultureInfo info = CultureInfo.CurrentCulture;

                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");


                DateTime date123 = new DateTime();


                string str1 = "zzz";
                string str2 = null;
                int    res  = string.Compare(str1, "a", StringComparison.Ordinal);


                if (str1.Equals("1"))
                {
                    str1 = "11";
                }
                else
                {
                    str2 = "22";
                }



                XmlDocument doc = new XmlDocument();
                XmlElement  transactionsElement = doc.CreateElement("Transactions");
                doc.AppendChild(transactionsElement);

                for (int i = 0; i < 3; i++)
                {
                    XmlElement transactionElement = doc.CreateElement("Transaction");
                    transactionsElement.AppendChild(transactionElement);

                    XmlNode storeNode = doc.CreateElement("StoreId");
                    storeNode.AppendChild(doc.CreateTextNode("7"));
                    transactionElement.AppendChild(storeNode);


                    XmlNode caisNode = doc.CreateElement("Cais");
                    caisNode.AppendChild(doc.CreateTextNode("252"));
                    transactionElement.AppendChild(caisNode);

                    XmlNode transNumNode = doc.CreateElement("TransNum");
                    transNumNode.AppendChild(doc.CreateTextNode("14"));
                    transactionElement.AppendChild(transNumNode);
                }


                DataTable customerTransactionTable = new DataTable("CustomerTransaction");
                customerTransactionTable.Columns.Add(new DataColumn("CustomerCode", typeof(string)));
                customerTransactionTable.Columns.Add(new DataColumn("TransactionNumber", typeof(string)));

                // Loop to populate data table
                for (int i = 1; i < 5; i++) // Table name: Last60Transactions
                {
                    string clientNumber      = string.Format("clientNumber{0}", i);
                    string transactionNumber = string.Format("transactionNumber{0}", i);

                    DataRow newRow = customerTransactionTable.NewRow();
                    newRow["CustomerCode"]      = clientNumber;
                    newRow["TransactionNumber"] = transactionNumber;

                    customerTransactionTable.Rows.Add(newRow);
                }

                customerTransactionTable.AcceptChanges();


                // Convert DataTable to XML string
                string customerTransactionXml;
                using (StringWriter sw = new StringWriter())
                {
                    customerTransactionTable.WriteXml(sw);
                    customerTransactionXml = sw.ToString();
                }



                string   date     = "20140222 154535";
                DateTime datetime = DateTime.ParseExact(date, "yyyyMMdd HHmmss", null);

                Enum1 e1 = Enum1.Item2;

                Enum2 e2 = (Enum2)e1;



                int?number;
                number = null;
                bool y = number.HasValue;

                number = new Nullable <int>();


                bool test = Convert.ToBoolean(DBNull.Value);


                List <int> randomList = new List <int>();

                for (int j = 0; j < 1000000; j++)
                {
                    //Console.WriteLine(DateTime.Now.Millisecond);
                    //////Console.WriteLine(DateTime.Now.ToString("hh:mm:ss:fffffff"));
                    //Console.WriteLine(DateTime.Now.Ticks);

                    //randomList.Add(DateTime.Now.Millisecond);


                    byte[] seed = Guid.NewGuid().ToByteArray();
                    for (int i = 0; i < 3; i++)
                    {
                        seed[i] ^= seed[i + 4];
                        seed[i] ^= seed[i + 8];
                        seed[i] ^= seed[i + 12];
                    }

                    int seedInt = BitConverter.ToInt32(seed, 0);
                    //Console.WriteLine(seedInt);
                    Random rnd = new Random(seedInt);
                    randomList.Add(rnd.Next(9999999));


                    //Console.WriteLine(rnd.Next(9999999));
                }

                var duplicates = randomList.GroupBy(a => a).SelectMany(ab => ab.Skip(1).Take(1)).ToList();

                List <CusotmerInfo> custList = new List <CusotmerInfo>();

                custList.Add(new CusotmerInfo()
                {
                    Code      = "a",
                    FirstName = "F1",
                    LastName  = "L1",
                    Address1  = new Address()
                    {
                        IsDefault = false,
                        Line1     = "Line11",
                        ZipCode   = "Zip1"
                    }
                });

                custList.Add(new CusotmerInfo()
                {
                    Code      = "a",
                    FirstName = "F2",
                    LastName  = "L2",
                    Address1  = new Address()
                    {
                        IsDefault = true,
                        Line1     = "Line12",
                        ZipCode   = "Zip2"
                    }
                });

                custList.Add(new CusotmerInfo()
                {
                    Code      = "b",
                    FirstName = "F3",
                    LastName  = "L3",
                    Address1  = new Address()
                    {
                        IsDefault = false,
                        Line1     = "Line13",
                        ZipCode   = "Zip3"
                    }
                });

                //var result = from cust in custList
                //			 group cust by cust.Code into g
                //			 select new CusotmerInfo()
                //			 {
                //				 Code = g.Key,
                //				 Address1 = g.FirstOrDefault(e => e.Address1.IsDefault) == null ? g.FirstOrDefault().Address1 : g.FirstOrDefault(e => e.Address1.IsDefault).Address1
                //			 };

                var result = from cust in custList
                             group cust by cust.Code into g
                             select g.FirstOrDefault(e => e.Address1.IsDefault) == null?g.FirstOrDefault() : g.FirstOrDefault(e => e.Address1.IsDefault);


                List <CusotmerInfo> re = result.ToList();



                //List<Address> addressList = new List<Address>();
                //addressList.Add(new Address() { AddressLine1 = "a1", Sequence = 2 });
                //addressList.Add(new Address() { AddressLine1 = "a2", Sequence = 3 });
                //addressList.Add(new Address() { AddressLine1 = "a3", Sequence = 1 });
                //addressList.Add(new Address() { AddressLine1 = "a4", Sequence = 4 });

                //int minSequence = addressList.Min(address => address.Sequence);

                //addressList.Sort(delegate(Address a1, Address a2) { return a1.Sequence - a2.Sequence; });
            }
            return;
        }
		private static void LoadMaterialSettings(PrinterSettings layeredProfile, Printer printer)
		{
			var materialAssignments = printer.MaterialCollectionIds?.Split(',');
			if(materialAssignments == null)
			{
				return;
			}

			var collections = Datastore.Instance.dbSQLite.Table<SliceSettingsCollection>().Where(v => v.PrinterId == printer.Id && v.Tag == "material");
			foreach (var collection in collections)
			{
				layeredProfile.MaterialLayers.Add(new PrinterSettingsLayer(LoadSettings(collection))
				{
					LayerID = Guid.NewGuid().ToString(),
					Name = collection.Name
				});
			}
		}
		internal static async Task SwitchToProfile(string printerID)
		{
			ProfileManager.Instance.SetLastProfile(printerID);
			Instance = (await ProfileManager.LoadProfileAsync(printerID)) ?? ProfileManager.LoadEmptyProfile();
		}
示例#13
0
        public void PrintPreview(string Printer, string PaperType, string Tray, uint FromPage, uint ToPage, int Language)
        {
            PrinterSettings p;
            bool            bGood = false;

            p = new PrinterSettings();
            if (PrinterSettings.InstalledPrinters.Count > 0)
            {
                foreach (string s in PrinterSettings.InstalledPrinters)
                {
                    if (s.Equals(Printer, StringComparison.OrdinalIgnoreCase))
                    {
                        p.PrinterName = s;
                        bGood         = true;
                    }
                }
                if (!bGood)
                {
                    p.PrinterName = PrinterSettings.InstalledPrinters[0];
                    bGood         = true;
                }
            }
            if (bGood == false)
            {
                MessageBox.Show("No installed printers were found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            PreparePrint(Printer, PaperType);

            this.FromPage = FromPage;
            this.ToPage   = ToPage;
            this.NextPage = FromPage;
            this.Language = Language;

            PrintDocument printDocument = new PrintDocument();

            printDocument.PrintPage      += new PrintPageEventHandler(this.pd_PrintPage);
            printDocument.PrinterSettings = p;

            PaperSize gevondenSize = null;

            foreach (PaperSize ps in printDocument.PrinterSettings.PaperSizes)
            {
                if (ps.PaperName.Equals(PaperType, StringComparison.OrdinalIgnoreCase))
                {
                    gevondenSize = ps;
                    break;
                }
            }
            if (gevondenSize == null)
            {
                System.Drawing.Printing.PrinterSettings.PaperSizeCollection col;
                col = printDocument.PrinterSettings.PaperSizes;

                Tools.Size theSize = PaperDef.GetLabelSize();

                PaperSize sz = new PaperSize(PaperType, (int)(PaperDef.GetPhysicalLabelSize().Width.InInch() * 100), (int)(PaperDef.GetPhysicalLabelSize().Height.InInch() * 100));
                //PaperSize sz = new PaperSize(PaperType, (int)(PaperDef.GetPhysicalLabelSize().Width.InInch() * 96), (int)(PaperDef.GetPhysicalLabelSize().Height.InInch() * 96));
                //TODO: DPI values

                printDocument.PrinterSettings.DefaultPageSettings.PaperSize = sz;
            }
            else
            {
                printDocument.PrinterSettings.DefaultPageSettings.PaperSize = gevondenSize;
            }
            if ((FromPage > 0) || (ToPage != uint.MaxValue))
            {
                printDocument.PrinterSettings.PrintRange = PrintRange.SomePages;
                printDocument.PrinterSettings.FromPage   = (int)FromPage;
                printDocument.PrinterSettings.ToPage     = (int)ToPage;
            }
            else
            {
                printDocument.PrinterSettings.PrintRange = PrintRange.AllPages;
            }

            printDocument.PrinterSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
            printDocument.DocumentName = "Preview document";
            printDocument.DefaultPageSettings.PaperSource.SourceName = Tray;

            PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();

            printPreviewDialog.Document = printDocument;

            printPreviewDialog.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            printPreviewDialog.UseAntiAlias  = true; //remove later if proves to be to slow.
            ((ToolStrip)printPreviewDialog.Controls[1]).Items[0].Enabled = false;

            printPreviewDialog.ShowDialog();
            StaticVarslabel.Values.Clear(); //Clear static variables after printjob
            printPreviewDialog.Dispose();
        }
        public static void Preview(this Report report, FRPrintPreviewControl preview, PrinterSettings settings = null)
        {
            var doc = report.PrepareDoc(settings);

            if (doc == null)
            {
                return;
            }

            preview.Document = doc;
        }
		public void layerHeightLessThanNozzleDiameter(PrinterSettings printerSettings, PrinterSettingsLayer layer, string sourceFile)
		{
			string layerHeight;
			if (!layer.TryGetValue(SettingsKey.layer_height, out layerHeight))
			{
				return;
			}

			float convertedLayerHeight = float.Parse(layerHeight);

			string nozzleDiameter = printerSettings.GetValue(SettingsKey.nozzle_diameter);
			float convertedNozzleDiameterValue = float.Parse(nozzleDiameter);

			Assert.LessOrEqual(convertedLayerHeight, convertedNozzleDiameterValue, "Unexpected layerHeightLessThanNozzleDiameter value: " + sourceFile);
		}
示例#16
0
 public PrintLevelingData(PrinterSettings printerProfile)
 {
     this.printerProfile = printerProfile;
 }
        /**
         * printDocument -
         *
         * displays a print dialog in order to print the current document
         */
        public void printDocument()
        {
            // check for a null document
            if (document == null)
            {
                MessageBox.Show("A PDF must be open in order to print.", "Datalogics DotNETViewer");
                return;
            }

            // continuous page printing not supported
            if (PageDisplayMode == PageViewMode.continuousPage)
            {
                MessageBox.Show("Unable to Print in Continuous Page Mode", "Print Error", MessageBoxButtons.OK);
                return;
            }

            try
            {
                double docGreatestWidthInPrinterRezUnits = 0.0;
                double docGreatestWidthInInches          = 0.0;
                double docGreatestWidthInPDFUserUnits    = 0.0;

                double docHeightInInches          = 0.0;
                double docHeightInPrinterRezUnits = 0.0;
                double docHeightInPDFUserUnits    = 0.0;

                Graphics graphics;
                uint     resolutionX;
                uint     resolutionY;

                // DLADD wrl 6/24/08 -- Use DotNET shrinkToFit flag to handle scaling
                bool shrinkToFit = false;

                PrintDocument printDocument = new PrintDocument();

                // create the settings to use while printing
                PrinterSettings printerSettings = printDocument.PrinterSettings;
                printerSettings.MinimumPage = 1;
                printerSettings.MaximumPage = document.NumPages;
                printerSettings.PrintRange  = PrintRange.AllPages;
                printerSettings.FromPage    = 1;
                printerSettings.ToPage      = document.NumPages;

                // create a print dialog
                DotNETPrintDialog dpd = new DotNETPrintDialog();
                dpd.Document       = printDocument;
                dpd.AllowSelection = false;
                dpd.AllowSomePages = true;

                if (PageDisplayMode == PageViewMode.singlePage)
                {
                    dpd.AllowShrinkToFit = true;
                    dpd.ShrinkToFit      = true;
                }

                // display the print dialog if the user does not
                // click "OK" throw a new exception to cancel printing
                if (dpd.ShowDialog() != DialogResult.OK)
                {
                    throw new CancelPrinting();
                }

                shrinkToFit = dpd.ShrinkToFit;

                graphics    = printerSettings.CreateMeasurementGraphics();
                resolutionX = (uint)graphics.DpiX;
                resolutionY = (uint)graphics.DpiY;

                // grab some additional parameters if printing to a file
                if (printerSettings.PrintToFile)
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.DefaultExt = ".plt";
                    saveFileDialog.FileName   = "plot.plt";

                    if (saveFileDialog.ShowDialog() != DialogResult.OK)
                    {
                        throw new CancelPrinting();
                    }
                    else
                    {
                        printerSettings.PrintFileName = saveFileDialog.FileName;
                    }
                }

                // find the dimensions we need for printing
                docGreatestWidthInPDFUserUnits = 0;
                for (int i = 0; i < document.NumPages; ++i)
                {
                    using (Page page = document.GetPage(i)) docGreatestWidthInPDFUserUnits = Math.Max(docGreatestWidthInPDFUserUnits, page.CropBox.Width);
                }
                docHeightInPDFUserUnits = 0;
                for (int i = printerSettings.FromPage - 1; i <= printerSettings.ToPage - 1; ++i)
                {
                    using (Page page = document.GetPage(i)) docHeightInPDFUserUnits += page.CropBox.Height;
                }

                docGreatestWidthInInches = docGreatestWidthInPDFUserUnits / (double)GlobalConsts.pdfDPI;
                docHeightInInches        = docHeightInPDFUserUnits / (double)GlobalConsts.pdfDPI;

                docGreatestWidthInPrinterRezUnits = docGreatestWidthInInches * (double)resolutionX;
                docHeightInPrinterRezUnits        = docHeightInInches * (double)resolutionY;

                if (PageDisplayMode == PageViewMode.singlePage)
                {
#if HAS_DATALOGICS_PRINTING
                    Printer S_printer = new Printer(printerSettings.PrinterName);

                    if (S_printer.HardwareID == "isysij18")
                    {
                        // special workaround for iSys iTerra IJ1800
                        // use our special print controller to print via unmanaged code
                        PrintController pc = new DLPrinterPrintController(S_printer, printDocument.PrinterSettings, document.fileName);
                        printDocument.PrintController = new PrintControllerWithStatusDialog(pc);
                    }
                    else
                    {
                        S_printer.Dispose();
                    }
#endif

                    // User can control printing of OCGs
                    DrawParams drawParams = new DrawParams();

                    for (int j = 0; j < layersManager.ocgStates.Count; j++)
                    {
                        layersManager.ocgStates[j] = layersManager.layersInDocument[j].printLayer.Checked;
                    }

                    layersManager.docLayerContext.SetOCGStates(layersManager.docLayers, layersManager.ocgStates);
                    drawParams.OptionalContentContext = layersManager.docLayerContext;

                    // create the print controller
                    DotNETPrintController ppc = new DotNETPrintController(document, printDocument, drawParams, true, shrinkToFit);

                    // start the printing
                    ppc.Print();
                }
            }
            catch (CancelPrinting)
            {
                // Ignore, user cancelled printing
            }
        }
示例#18
0
        private void AddDisplay(PrinterSettings printerSettings,
                                ThemeConfig theme,
                                bool showClearButton,
                                string setting,
                                int toolIndex,
                                TextWidget widget)
        {
            GuiWidget clearZOffsetButton = null;

            void Printer_SettingChanged(object s, StringEventArgs e)
            {
                if (e?.Data == setting)
                {
                    double zOffset = printerSettings.GetValue <double>(setting);
                    bool   hasOverriddenZOffset = zOffset != 0;

                    if (clearZOffsetButton != null)
                    {
                        clearZOffsetButton.Visible = hasOverriddenZOffset;
                    }

                    widget.Text = zOffset.ToString("0.##");
                    DescribeExtruder(widget, toolIndex);
                }
            }

            var zOffsetStreamContainer = new FlowLayoutWidget(FlowDirection.LeftToRight)
            {
                Margin  = new BorderDouble(3, 0),
                Padding = new BorderDouble(3),
                HAnchor = HAnchor.Fit | HAnchor.Right,
                VAnchor = VAnchor.Absolute,
                Height  = 20 * GuiWidget.DeviceScale
            };

            this.AddChild(zOffsetStreamContainer);

            var zoffset = printerSettings.GetValue <double>(setting);

            zOffsetStreamContainer.AddChild(widget);

            if (showClearButton)
            {
                clearZOffsetButton             = theme.CreateSmallResetButton();
                clearZOffsetButton.Name        = "Clear ZOffset button";
                clearZOffsetButton.ToolTipText = "Clear ZOffset".Localize();
                clearZOffsetButton.Visible     = zoffset != 0;
                clearZOffsetButton.Click      += (sender, e) =>
                {
                    printerSettings.SetValue(setting, "0");
                };
                zOffsetStreamContainer.AddChild(clearZOffsetButton);
            }

            printerSettings.SettingChanged += Printer_SettingChanged;

            this.Closed += (s, e) =>
            {
                printerSettings.SettingChanged -= Printer_SettingChanged;
            };
        }
        public void PageSetupDialog_PrinterSettings_SetWithDocument_GetReturnsExpected(PrinterSettings value)
        {
            var dialog = new PageSetupDialog
            {
                Document        = new PrintDocument(),
                PrinterSettings = value
            };

            Assert.Same(value, dialog.PrinterSettings);
            Assert.Null(dialog.Document);

            // Set same.
            dialog.PrinterSettings = value;
            Assert.Same(value, dialog.PrinterSettings);
            Assert.Null(dialog.Document);
        }
示例#20
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Get our path to Acrobat
            PdfFilePrinter.AdobeReaderPath = strAcrobat.Replace("\\", "\\\\");

            // Present a Printer settings dialog to the user so the can select the printer
            // to use.
            PrinterSettings settings = new PrinterSettings();

            settings.Collate = false;
            PrintDialog printerDialog = new PrintDialog();

            printerDialog.AllowSomePages              = false;
            printerDialog.ShowHelp                    = false;
            printerDialog.PrinterSettings             = settings;
            printerDialog.AllowPrintToFile            = true;
            printerDialog.PrinterSettings.PrintToFile = true;
            DialogResult result = printerDialog.ShowDialog();

            //If the user doesn't cancel, do something
            if (result == DialogResult.OK)
            {
                //Loop through the DataGrid
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    //If the row is checked, let's work with it.
                    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                    if (Convert.ToBoolean(chk.Value) == true)
                    {
                        Int32 iOrderId = Convert.ToInt32(row.Cells[1].Value.ToString());

                        using (SqlConnection conn = new SqlConnection(strConn))
                        {
                            conn.Open();
                            DataSet ds = new DataSet();

                            //Get info about the Order
                            SqlCommand sqlComm = new SqlCommand("Get_Order_By_Id", conn);
                            sqlComm.Parameters.AddWithValue("@Order_Id", iOrderId);
                            sqlComm.CommandType = CommandType.StoredProcedure;

                            SqlDataAdapter da = new SqlDataAdapter();
                            da.SelectCommand = sqlComm;

                            da.Fill(ds);
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                DataSet dsInvoiceNum = new DataSet();

                                //Returns in invoice number
                                SqlCommand sqlCommInv = new SqlCommand("Generate_Invoice", conn);
                                sqlCommInv.Parameters.AddWithValue("@Order_Id", iOrderId);
                                sqlCommInv.CommandType = CommandType.StoredProcedure;

                                SqlDataAdapter daInv = new SqlDataAdapter();
                                daInv.SelectCommand = sqlCommInv;

                                daInv.Fill(dsInvoiceNum);

                                int iInvoiceNum = Convert.ToInt32(dsInvoiceNum.Tables[0].Rows[0][0]);

                                DataRow dr = ds.Tables[0].Rows[0];

                                //Create the PDF
                                PdfDocument document = new PdfDocument();
                                document.Info.Author   = "MLAW Engineers";
                                document.Info.Keywords = "";

                                PdfPage page = document.AddPage();
                                page.Size = PdfSharp.PageSize.A4;

                                // Obtain an XGraphics object to render to
                                XGraphics gfx = XGraphics.FromPdfPage(page);

                                // Create a font
                                double fontHeight = 12;
                                XFont  font       = new XFont("Times New Roman", fontHeight, XFontStyle.BoldItalic);

                                // Get the centre of the page
                                double y           = 20;
                                int    lineCount   = 0;
                                double linePadding = 10;

                                // Create a rectangle to draw the text in and draw in it
                                XRect rect = new XRect(0, y, page.Width, fontHeight);

                                //This is all PDF formatting/printing/layout
                                lineCount++;
                                y += fontHeight;

                                String imageLoc = "mlaw_logo.png";
                                DrawImage(gfx, imageLoc, 28, 20, 111, 28);

                                PointF pt      = new PointF(144, 48);
                                XFont  fontEng = new XFont("Arial", 15, XFontStyle.Regular);
                                gfx.DrawString("ENGINEERS", fontEng, XBrushes.Navy, pt);

                                XPen pen = new XPen(XColors.Black, 2);
                                gfx.DrawLine(pen, 20, 50, 580, 50);

                                pt = new PointF(24, 61);
                                XFont fontServLine = new XFont("Arial Narrow", 9, XFontStyle.Regular);
                                gfx.DrawString("FOUNDATION | FRAMING | INSPECTIONS | ENERGY | GEOSTRUCTURAL", fontServLine, XBrushes.Black, pt);

                                pt = new PointF(520, 60);
                                XFont fontPE = new XFont("Arial", 8, XFontStyle.Regular);
                                gfx.DrawString("TX PE #002685", fontPE, XBrushes.Black, pt);


                                XFont fontNormal = new XFont("Arial", 10, XFontStyle.Regular);
                                pt = new PointF(40, 180);
                                gfx.DrawString(dr["Client_Full_Name"].ToString(), fontNormal, XBrushes.Black, pt);
                                pt = new PointF(40, 191);
                                gfx.DrawString(dr["Billing_Address_1"].ToString(), fontNormal, XBrushes.Black, pt);
                                pt = new PointF(40, 202);
                                gfx.DrawString(dr["Billing_City"].ToString() + ", " + dr["Billing_State"].ToString() + " " + dr["Billing_Postal_Code"].ToString(), fontNormal, XBrushes.Black, pt);
                                pt = new PointF(340, 180);

                                DateTime dtNow = DateTime.Now;


                                gfx.DrawString(dtNow.ToString("MMMM dd, yyyy"), fontNormal, XBrushes.Black, pt);
                                pt = new PointF(340, 191);
                                gfx.DrawString("Invoice Number: " + iInvoiceNum.ToString(), fontNormal, XBrushes.Black, pt);
                                pt = new PointF(340, 202);

                                /* Removed per Janet
                                 * gfx.DrawString("CC: 001240", fontNormal, XBrushes.Black, pt);
                                 * pt = new PointF(340, 223);
                                 * gfx.DrawString("Comments:", fontNormal, XBrushes.Black, pt);
                                 * pt = new PointF(340, 234);
                                 * gfx.DrawString(dr["Comments"].ToString(), fontNormal, XBrushes.Black, pt);
                                 * */

                                XFont fontBold = new XFont("Arial", 10, XFontStyle.Bold);
                                pt = new PointF(40, 250);
                                gfx.DrawString("Address: " + dr["Address"].ToString(), fontBold, XBrushes.Black, pt);
                                pt = new PointF(91, 261);
                                gfx.DrawString("Lot: " + dr["Lot"].ToString(), fontBold, XBrushes.Black, pt);
                                pt = new PointF(170, 261);
                                gfx.DrawString("Block: " + dr["Block"].ToString(), fontBold, XBrushes.Black, pt);
                                pt = new PointF(91, 272);
                                gfx.DrawString("Subdivision: " + dr["Subdivision_Name"].ToString(), fontBold, XBrushes.Black, pt);


                                pt = new PointF(40, 300);
                                gfx.DrawString("Engineers Project No: " + dr["MLAW_Number"].ToString(), fontNormal, XBrushes.Black, pt);
                                pt = new PointF(40, 311);

                                /*Removed Per Janet
                                 * gfx.DrawString("Date Received: " + dr["Received_Date_String"].ToString(), fontNormal, XBrushes.Black, pt);
                                 * pt = new PointF(40, 322);
                                 * gfx.DrawString("Date Delivered: ", fontNormal, XBrushes.Black, pt);
                                 */

                                //Figure out what to bill the customer

                                Decimal dAmount   = 0;
                                Decimal dDiscount = 0;
                                Decimal dTotal    = 0;
                                Decimal number;

                                if (Decimal.TryParse(dr["Amount"].ToString(), out number))
                                {
                                    dAmount = number;
                                }

                                if (Decimal.TryParse(dr["Discount"].ToString(), out number))
                                {
                                    dDiscount = number;
                                }

                                dTotal = dAmount - dDiscount;

                                PointF pt1 = new PointF(40, 400);
                                PointF pt2 = new PointF(540, 400);
                                gfx.DrawLine(XPens.Black, pt1, pt2);

                                pt = new PointF(40, 430);
                                gfx.DrawString("Foundation Design Services: ", fontNormal, XBrushes.Black, pt);

                                pt = new PointF(40, 460);
                                gfx.DrawString("Base Charge: ..........................................................................................................................", fontNormal, XBrushes.Black, pt);

                                pt = new PointF(500, 460);
                                gfx.DrawString(dAmount.ToString("C2"), fontNormal, XBrushes.Black, pt);

                                if (dDiscount > 0)
                                {
                                    pt = new PointF(500, 480);
                                    gfx.DrawString(dDiscount.ToString("C2"), fontNormal, XBrushes.Black, pt);
                                }
                                pt = new PointF(140, 480);
                                String strSqFt = "X";

                                /* Removed per Janet
                                 * if (dSlabSqFt > 0 || iLevel1 > 0)
                                 * {
                                 *  strSqFt = Convert.ToInt32(dSlabSqFt).ToString();
                                 * }
                                 *
                                 *
                                 * gfx.DrawString("(         Sq Ft:  " + strSqFt + "             )", fontNormal, XBrushes.Black, pt);
                                 *
                                 *
                                 * pt = new PointF(140, 500);
                                 * gfx.DrawString("Copies of Document Included", fontNormal, XBrushes.Black, pt);
                                 */

                                pt1 = new PointF(40, 540);
                                pt2 = new PointF(540, 540);
                                gfx.DrawLine(XPens.Black, pt1, pt2);

                                pt = new PointF(300, 600);
                                gfx.DrawString("Total Charge:", fontNormal, XBrushes.Black, pt);

                                pt = new PointF(500, 600);
                                gfx.DrawString(dTotal.ToString("C2"), fontNormal, XBrushes.Black, pt);

                                /* Remove per Janet
                                 * pt = new PointF(300, 530);
                                 * gfx.DrawString("Approved:     ____________________________", fontNormal, XBrushes.Black, pt);
                                 */

                                pt = new PointF(60, 830);
                                XFont fontSmall = new XFont("Arial", 6, XFontStyle.Regular);
                                gfx.DrawString("2804 LONGHORN BLVD.", fontSmall, XBrushes.Black, pt);

                                pt = new PointF(182, 830);
                                gfx.DrawString("AUSTIN, TX 78758", fontSmall, XBrushes.Black, pt);

                                pt = new PointF(287, 830);
                                gfx.DrawString("512.835.7000", fontSmall, XBrushes.Black, pt);

                                pt = new PointF(380, 830);
                                gfx.DrawString("FAX 512.835.4975", fontSmall, XBrushes.Black, pt);

                                pt = new PointF(480, 830);
                                gfx.DrawString("TOLL FREE 877.855.3041", fontSmall, XBrushes.Black, pt);

                                //The invoice is Save in an Invoices directory

                                /****** MUST CREATE THIS DIRECTORY AHEAD OF TIME - REFACTOR TO AUTO-CREATE IF NOT THERE *****/
                                String strFileName = "Invoices/Invoice_" + dr["MLAW_Number"].ToString() + ".pdf";
                                document.Save(strFileName);

                                try
                                {
                                    FileInfo f        = new FileInfo(strFileName);
                                    string   fullname = f.FullName;
                                    Process  process  = new Process();

                                    // pdf file to print
                                    process.StartInfo.FileName = fullname;

                                    //print to specified printer
                                    process.StartInfo.Verb           = "Print";
                                    process.StartInfo.CreateNoWindow = true;

                                    process.StartInfo.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden;
                                    process.StartInfo.UseShellExecute = true;


                                    //Printer name
                                    process.StartInfo.Arguments = settings.PrinterName;
                                    process.Start();
                                    process.WaitForExit(3000);

                                    //Start Acrobat and print it out
                                    Process[] procs = Process.GetProcessesByName("Acrobat");

                                    foreach (Process proc in procs)
                                    {
                                        if (!process.HasExited)
                                        {
                                            proc.Kill();
                                            proc.WaitForExit();
                                        }
                                    }

                                    process.Close();
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("Error: " + ex.Message);
                                }
                            }
                        }
                    }
                }
            }
            loadData();
        }
示例#21
0
        private void PrepararImpressao()
        {
            this.Log().Debug("Preparando a impressão.");

            var e = new DANFSeEventArgs(Layout);

            OnGetReport.Raise(this, e);
            if (e.FilePath.IsEmpty() || !File.Exists(e.FilePath))
            {
                //ToDo: Adicionar os layouts de acordo com o provedor
                var assembly = Assembly.GetExecutingAssembly();

                Stream ms;
                switch (Layout)
                {
                case LayoutImpressao.ABRASF2:
                    ms = assembly.GetManifestResourceStream("ACBr.Net.NFSe.DANFSe.FastReport.OpenSource.Report.DANFSe.frx");
                    break;

                case LayoutImpressao.DSF:
                    ms = assembly.GetManifestResourceStream("ACBr.Net.NFSe.DANFSe.FastReport.OpenSource.Report.DANFSe.frx");
                    break;

                case LayoutImpressao.Ginfes:
                    ms = assembly.GetManifestResourceStream("ACBr.Net.NFSe.DANFSe.FastReport.OpenSource.Report.DANFSe.frx");
                    break;

                case LayoutImpressao.ABRASF:
                    ms = assembly.GetManifestResourceStream("ACBr.Net.NFSe.DANFSe.FastReport.OpenSource.Report.DANFSe.frx");
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                this.Log().Debug("Carregando layout impressão.");

                internalReport.Load(ms);
            }
            else
            {
                this.Log().Debug("Carregando layout impressão costumizado.");

                internalReport.Load(e.FilePath);
            }

            this.Log().Debug("Passando configurações para o relatório.");

#if NETFULL
            internalReport.SetParameterValue("Logo", Logo.ToByteArray());
            internalReport.SetParameterValue("LogoPrefeitura", LogoPrefeitura.ToByteArray());
#else
            internalReport.SetParameterValue("Logo", Logo);
            internalReport.SetParameterValue("LogoPrefeitura", LogoPrefeitura);
#endif
            internalReport.SetParameterValue("MunicipioPrestador", Parent.Configuracoes.WebServices.Municipio);
            internalReport.SetParameterValue("Ambiente", (int)Parent.Configuracoes.WebServices.Ambiente);
            internalReport.SetParameterValue("SoftwareHouse", SoftwareHouse);
            internalReport.SetParameterValue("Site", Site);

            settings = new PrinterSettings {
                Copies = (short)Math.Max(NumeroCopias, 1)
            };

            if (!Impressora.IsEmpty())
            {
                settings.PrinterName = Impressora;
            }

            this.Log().Debug("Impressão preparada.");
        }
        private static PrintDocument PrepareDoc(this Report report, PrinterSettings settings = null)
        {
            if (report.PreparedPages.Count < 1)
            {
                report.Prepare();
                if (report.PreparedPages.Count < 1)
                {
                    return(null);
                }
            }

            MemoryStream ms   = null;
            var          page = 0;
            var          exp  = new ImageExport {
                ImageFormat = ImageExportFormat.Png, Resolution = 600
            };

            var doc = new PrintDocument {
                DocumentName = report.Name
            };

            if (settings != null)
            {
                doc.PrinterSettings = settings;
            }

            // Ajustando o tamanho da pagina
            doc.QueryPageSettings += (sender, args) =>
            {
                var rPage = report.PreparedPages.GetPage(page);
                args.PageSettings.Landscape = rPage.Landscape;
                args.PageSettings.Margins   = new Margins((int)(scaleFactor * rPage.LeftMargin * Units.HundrethsOfInch),
                                                          (int)(scaleFactor * rPage.RightMargin * Units.HundrethsOfInch),
                                                          (int)(scaleFactor * rPage.TopMargin * Units.HundrethsOfInch),
                                                          (int)(scaleFactor * rPage.BottomMargin * Units.HundrethsOfInch));

                args.PageSettings.PaperSize = new PaperSize("Custom", (int)(ExportUtils.GetPageWidth(rPage) * scaleFactor * Units.HundrethsOfInch),
                                                            (int)(ExportUtils.GetPageHeight(rPage) * scaleFactor * Units.HundrethsOfInch));
            };

            doc.BeginPrint += (sender, args) => ms?.Dispose();

            doc.PrintPage += (sender, args) =>
            {
                ms              = new MemoryStream();
                exp.PageRange   = PageRange.PageNumbers;
                exp.PageNumbers = $"{page + 1}";
                exp.Export(report, ms);

                args.Graphics.DrawImage(Image.FromStream(ms), args.PageBounds);
                page++;

                args.HasMorePages = page < report.PreparedPages.Count;
            };

            doc.EndPrint += (sender, args) => page = 0;

            doc.Disposed += (sender, args) =>
            {
                ms?.Dispose();
                exp?.Dispose();
            };

            return(doc);
        }
		public void firstLayerHeightLessThanNozzleDiameter(PrinterSettings printerSettings, PrinterSettingsLayer layer, string sourceFile)
		{
			string firstLayerHeight;
			
			if (!layer.TryGetValue(SettingsKey.first_layer_height, out firstLayerHeight))
			{
				return;
			}

			float convertedFirstLayerHeightValue;

			if (firstLayerHeight.Contains("%"))
			{
				string reFormatLayerHeight = firstLayerHeight.Replace("%", " ");
				convertedFirstLayerHeightValue = float.Parse(reFormatLayerHeight) / 100;
			}
			else
			{
				convertedFirstLayerHeightValue = float.Parse(firstLayerHeight);
			}

			string nozzleDiameter = printerSettings.GetValue(SettingsKey.nozzle_diameter);

			Assert.LessOrEqual(convertedFirstLayerHeightValue, float.Parse(nozzleDiameter), "Unexpected firstLayerHeightLessThanNozzleDiameter value: " + sourceFile);
		}
示例#24
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        ///
        /// </summary>
        /// <param name="e"></param>
        /// ------------------------------------------------------------------------------------
        private void Init(PrintPageEventArgs e)
        {
#if false
            long x1 = System.DateTime.Now.Ticks;
#endif
            // Set these now because the Graphics object will be locked below.
            m_rcDst = m_rcSrc = new Rect(0, 0, (int)e.Graphics.DpiX, (int)e.Graphics.DpiY);

            int dpix;
            if (MiscUtils.IsUnix)
            {
                dpix = 72;
            }
            else
            {
                dpix = (int)e.Graphics.DpiX;
            }

            m_dxpAvailWidth = PixelsFrom100ths(e.MarginBounds.Width, dpix);

            // Create and initialize a print context.
            m_vwPrintContext = VwPrintContextWin32Class.Create();

            // TODO: When we provide a way for the user to specify the nFirstPageNo (i.e. the
            // first argument to SetPagePrintInfo), then change the arguments to
            // SetPagePrintInfo.
            m_vwPrintContext.SetPagePrintInfo(1, 1, 65535, 1, false);
            SetMargins(e);

            IVwGraphics vwGraphics = VwGraphicsWin32Class.Create();
            IntPtr      hdc        = IntPtr.Zero;
            try
            {
                // Get the printer's hdc and use it to initialize other stuff.
                hdc = e.Graphics.GetHdc();
                ((IVwGraphicsWin32)vwGraphics).Initialize(hdc);
                m_vwPrintContext.SetGraphics(vwGraphics);

                // Make a rootbox for printing and initialize it.
                m_rootb = VwRootBoxClass.Create();
                m_rootb.RenderEngineFactory = SingletonsContainer.Get <RenderEngineFactory>();
                m_rootb.TsStrFactory        = TsStringUtils.TsStrFactory;
                m_rootb.SetSite(this);
                m_rootb.DataAccess = m_sda;
                m_rootb.SetRootObject(m_hvo, m_vc, m_frags, m_styleSheet);
                m_rootb.InitializePrinting(m_vwPrintContext);
                m_totalNumberOfPages = m_rootb.GetTotalPrintPages(m_vwPrintContext);
                m_psettings          = e.PageSettings.PrinterSettings;
                SetPrintRange();
            }
            catch (Exception ex)
            {
                m_rootb = null;

                throw new ContinuableErrorException("An error has occurred during the setup required for printing.", ex);
            }
            finally
            {
                if (hdc != IntPtr.Zero)
                {
                    vwGraphics.ReleaseDC();
                    e.Graphics.ReleaseHdc(hdc);
                }
            }
#if false
            long x2 = System.DateTime.Now.Ticks;
            Debug.WriteLine("PrintRootSite.Init() took " + DeltaTime(x1, x2) + " seconds.");
#endif
        }
示例#25
0
        /// <summary>
        /// 执行打印
        /// </summary>
        /// <param name="print"></param>
        /// <param name="path"></param>
        /// <param name="horizontal"></param>
        private static void Print(PrintDocument print, string path, int Copies = 1, Duplex horizontal = Duplex.Simplex, string range = null)
        {
            print.DocumentName = Path.GetFileName(path);
            PrinterSettings settings = print.PrinterSettings;

            settings.Copies = (short)Copies;
            if (settings.CanDuplex)
            {
                settings.Duplex = horizontal;
            }
            else
            {
                settings.Duplex = Duplex.Simplex;
            }
            if (!Utils.IsStrNull(range))
            {
                if (range.Contains("-"))
                {
                    string[] array     = range.Split('-');
                    int[]    pageArray = new int[array.Length];
                    for (int a = 0; a < array.Length; a++)
                    {
                        if (Utils.IsInt(array[a]))
                        {
                            pageArray[a] = int.Parse(array[a]);
                        }
                        else
                        {
                            MessageBox.Show("你的输入有不是数字");
                            return;
                        }
                    }

                    settings.FromPage = pageArray[0];
                    settings.ToPage   = pageArray[1];
                    print.PrinterSettings.PrintRange = PrintRange.SomePages;
                    print.Print();
                }
                if (range.Contains("、"))
                {
                    string[] array     = range.Split('、');
                    int[]    pageArray = new int[array.Length];
                    for (int a = 0; a < array.Length; a++)
                    {
                        if (Utils.IsInt(array[a]))
                        {
                            pageArray[a] = int.Parse(array[a]);
                        }
                        else
                        {
                            MessageBox.Show("你的输入有不是数字");
                            return;
                        }
                    }
                    foreach (int pageInt in pageArray)
                    {
                        settings.FromPage = pageInt;
                        settings.ToPage   = pageInt + 1;
                        print.PrinterSettings.PrintRange = PrintRange.SomePages;
                        print.Print();
                    }
                }
            }
            else
            {
                print.Print();
            }
        }
示例#26
0
        private void CreateFormControls()
        {
            form.SuspendLayout();

            GroupBox group_box_prn = new GroupBox();

            group_box_prn.Location = new Point(10, 8);
            group_box_prn.Text     = "Printer";
            group_box_prn.Size     = new Size(420, 145);

            GroupBox group_box_range = new GroupBox();

            group_box_range.Location = new Point(10, 155);
            group_box_range.Text     = "Print range";
            group_box_range.Size     = new Size(240, 100);

            GroupBox group_box_copies = new GroupBox();

            group_box_copies.Location = new Point(265, 155);
            group_box_copies.Text     = "Copies";
            group_box_copies.Size     = new Size(165, 100);

            // Accept button
            accept_button           = new Button();
            form.AcceptButton       = accept_button;
            accept_button.Anchor    = ((AnchorStyles)((AnchorStyles.Bottom | AnchorStyles.Right)));
            accept_button.FlatStyle = FlatStyle.System;
            accept_button.Location  = new Point(265, 270);
            accept_button.Text      = "OK";
            accept_button.FlatStyle = FlatStyle.System;
            accept_button.Click    += new EventHandler(OnClickOkButton);

            // Cancel button
            cancel_button           = new Button();
            form.CancelButton       = cancel_button;
            cancel_button.Anchor    = ((AnchorStyles)((AnchorStyles.Bottom | AnchorStyles.Right)));
            cancel_button.FlatStyle = FlatStyle.System;
            cancel_button.Location  = new Point(350, 270);
            cancel_button.Text      = "Cancel";
            cancel_button.FlatStyle = FlatStyle.System;
            cancel_button.Click    += new EventHandler(OnClickCancelButton);

            // Static controls
            Label label = new Label();

            label.AutoSize = true;
            label.Text     = "&Name:";
            label.Location = new Point(20, 33);
            group_box_prn.Controls.Add(label);

            label          = new Label();
            label.Text     = "Status:";
            label.AutoSize = true;
            label.Location = new Point(20, 60);
            group_box_prn.Controls.Add(label);

            label_status          = new Label();
            label_status.AutoSize = true;
            label_status.Location = new Point(80, 60);
            group_box_prn.Controls.Add(label_status);

            label          = new Label();
            label.Text     = "Type:";
            label.AutoSize = true;
            label.Location = new Point(20, 80);
            group_box_prn.Controls.Add(label);

            label_type          = new Label();
            label_type.AutoSize = true;
            label_type.Location = new Point(80, 80);
            group_box_prn.Controls.Add(label_type);

            label          = new Label();
            label.Text     = "Where:";
            label.AutoSize = true;
            label.Location = new Point(20, 100);
            group_box_prn.Controls.Add(label);

            label_where          = new Label();
            label_where.AutoSize = true;
            label_where.Location = new Point(80, 100);
            group_box_prn.Controls.Add(label_where);

            label          = new Label();
            label.Text     = "Comment:";
            label.AutoSize = true;
            label.Location = new Point(20, 120);
            group_box_prn.Controls.Add(label);

            label_comment          = new Label();
            label_comment.AutoSize = true;
            label_comment.Location = new Point(80, 120);
            group_box_prn.Controls.Add(label_comment);

            radio_all          = new RadioButton();
            radio_all.TabIndex = 21;
            radio_all.Location = new Point(20, 20);
            radio_all.Text     = "&All";
            radio_all.Checked  = true;
            group_box_range.Controls.Add(radio_all);

            radio_pages                 = new RadioButton();
            radio_pages.TabIndex        = 22;
            radio_pages.Location        = new Point(20, 46);
            radio_pages.Text            = "Pa&ges";
            radio_pages.Width           = 60;
            radio_pages.CheckedChanged += new EventHandler(OnPagesCheckedChanged);
            group_box_range.Controls.Add(radio_pages);

            radio_sel          = new RadioButton();
            radio_sel.TabIndex = 23;
            radio_sel.Location = new Point(20, 72);
            radio_sel.Text     = "&Selection";
            group_box_range.Controls.Add(radio_sel);

            labelFrom          = new Label();
            labelFrom.Text     = "&from:";
            labelFrom.TabIndex = 24;
            labelFrom.AutoSize = true;
            labelFrom.Location = new Point(80, 50);
            group_box_range.Controls.Add(labelFrom);

            txtFrom              = new TextBox();
            txtFrom.TabIndex     = 25;
            txtFrom.Location     = new Point(120, 50);
            txtFrom.Width        = 40;
            txtFrom.TextChanged += new EventHandler(OnPagesTextChanged);
            group_box_range.Controls.Add(txtFrom);

            labelTo          = new Label();
            labelTo.Text     = "&to:";
            labelTo.TabIndex = 26;
            labelTo.AutoSize = true;
            labelTo.Location = new Point(170, 50);
            group_box_range.Controls.Add(labelTo);

            txtTo              = new TextBox();
            txtTo.TabIndex     = 27;
            txtTo.Location     = new Point(190, 50);
            txtTo.Width        = 40;
            txtTo.TextChanged += new EventHandler(OnPagesTextChanged);
            group_box_range.Controls.Add(txtTo);

            chkbox_print          = new CheckBox();
            chkbox_print.Location = new Point(305, 115);
            chkbox_print.Text     = "Print to fil&e";


            updown_copies          = new NumericUpDown();
            updown_copies.TabIndex = 31;
            updown_copies.Location = new Point(105, 18);
            updown_copies.Minimum  = 1;
            group_box_copies.Controls.Add(updown_copies);
            updown_copies.ValueChanged += new System.EventHandler(OnUpDownValueChanged);
            updown_copies.Size          = new System.Drawing.Size(40, 20);

            label          = new Label();
            label.Text     = "Number of &copies:";
            label.AutoSize = true;
            label.Location = new Point(10, 20);
            group_box_copies.Controls.Add(label);

            chkbox_collate                 = new CheckBox();
            chkbox_collate.TabIndex        = 32;
            chkbox_collate.Location        = new Point(105, 55);
            chkbox_collate.Text            = "C&ollate";
            chkbox_collate.Width           = 58;
            chkbox_collate.CheckedChanged += new EventHandler(chkbox_collate_CheckedChanged);

            group_box_copies.Controls.Add(chkbox_collate);

            collate          = new CollatePreview();
            collate.Location = new Point(6, 50);
            collate.Size     = new Size(100, 45);
            group_box_copies.Controls.Add(collate);



            // Printer combo
            printer_combo = new ComboBox();
            printer_combo.DropDownStyle         = ComboBoxStyle.DropDownList;
            printer_combo.Location              = new Point(80, 32);
            printer_combo.Width                 = 220;
            printer_combo.SelectedIndexChanged += new EventHandler(OnPrinterSelectedIndexChanged);

            default_printer_settings = new PrinterSettings();
            for (int i = 0; i < installed_printers.Count; i++)
            {
                printer_combo.Items.Add(installed_printers[i]);
                if (installed_printers[i] == default_printer_settings.PrinterName)
                {
                    printer_combo.SelectedItem = installed_printers[i];
                }
            }
            printer_combo.TabIndex = 11;
            chkbox_print.TabIndex  = 12;
            group_box_prn.Controls.Add(printer_combo);
            group_box_prn.Controls.Add(chkbox_print);

            form.Size                 = new Size(450, 327); // 384
            form.FormBorderStyle      = FormBorderStyle.FixedDialog;
            form.MaximizeBox          = false;
            group_box_prn.TabIndex    = 10;
            group_box_range.TabIndex  = 20;
            group_box_copies.TabIndex = 30;
            accept_button.TabIndex    = 40;
            cancel_button.TabIndex    = 50;
            form.Controls.Add(group_box_prn);
            form.Controls.Add(group_box_range);
            form.Controls.Add(group_box_copies);
            form.Controls.Add(accept_button);
            form.Controls.Add(cancel_button);
            form.ResumeLayout(false);
        }
示例#27
0
        internal PageSetupData()
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(WinOEPrintingSubKey);

            if (null != key)
            {
                try
                {
                    object registryValue = null;

                    registryValue = key.GetValue(RegistryHeaderAlignment);
                    if (null != registryValue && registryValue is int)
                    {
                        this.headerAlignment = (HorizontalAlignment)registryValue;
                    }

                    registryValue = key.GetValue(RegistryFooterAlignment);
                    if (null != registryValue && registryValue is int)
                    {
                        this.footerAlignment = (HorizontalAlignment)registryValue;
                    }

                    registryValue = key.GetValue(RegistryHeaderMarging);
                    if (null != registryValue && registryValue is int)
                    {
                        this.headerMargin = (int)registryValue;
                    }

                    registryValue = key.GetValue(RegistryFooterMarging);
                    if (null != registryValue && registryValue is int)
                    {
                        this.footerMargin = (int)registryValue;
                    }

                    registryValue = key.GetValue(RegistryHeaderTemplate);
                    if (null != registryValue && registryValue is string)
                    {
                        this.headerTemplate = (string)registryValue;
                    }

                    registryValue = key.GetValue(RegistryFooterTemplate);
                    if (null != registryValue && registryValue is string)
                    {
                        this.footerTemplate = (string)registryValue;
                    }

                    registryValue = key.GetValue(RegistryHeaderCustom);
                    if (null != registryValue && registryValue is int)
                    {
                        this.headerCustom = Convert.ToBoolean((int)registryValue);
                    }

                    registryValue = key.GetValue(RegistryFooterCustom);
                    if (null != registryValue && registryValue is int)
                    {
                        this.footerCustom = Convert.ToBoolean((int)registryValue);
                    }

                    registryValue = key.GetValue(RegistryCenterHorizontally);
                    if (null != registryValue && registryValue is int)
                    {
                        this.centerHorizontally = Convert.ToBoolean((int)registryValue);
                    }

                    registryValue = key.GetValue(RegistryCenterVertically);
                    if (null != registryValue && registryValue is int)
                    {
                        this.centerVertically = Convert.ToBoolean((int)registryValue);
                    }
                }
                finally
                {
                    key.Close();
                }
            }

            PrinterSettings printerSettings = new PrinterSettings();

            this.landscape = printerSettings.DefaultPageSettings.Landscape;
            this.margins   = printerSettings.DefaultPageSettings.Margins;
        }
示例#28
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));
            }
        }
示例#29
0
        public void Print(string DocumentName, string Printer, string Tray, string PaperType, uint FromPage, uint ToPage, int Language)
        {
            PrinterSettings p = new PrinterSettings();

            p.PrinterName = Printer;
            try
            {
                PreparePrint(Printer, PaperType);
            }
            catch (ApplicationException e) {
                GlobalDataStore.Logger.Error("Error: " + e.Message);
            }

            this.FromPage = FromPage;
            this.ToPage   = ToPage;
            this.NextPage = FromPage;
            this.Language = Language;

            PrintDocument printDocument = new PrintDocument();

            printDocument.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
            //printDocument.PrinterSettings.PrinterName = Printer;
            printDocument.PrinterSettings = p;

            PaperSize gevondenSize = null;

            foreach (PaperSize ps in printDocument.PrinterSettings.PaperSizes)
            {
                if (ps.PaperName.Equals(PaperType, StringComparison.OrdinalIgnoreCase))
                {
                    gevondenSize = ps;
                    break;
                }
            }
            if (gevondenSize == null)
            {
                System.Drawing.Printing.PrinterSettings.PaperSizeCollection col;
                col = printDocument.PrinterSettings.PaperSizes;

                Tools.Size theSize = PaperDef.GetLabelSize();

                PaperSize sz = new PaperSize(PaperType, (int)(PaperDef.GetPhysicalLabelSize().Width.InInch() * 100), (int)(PaperDef.GetPhysicalLabelSize().Height.InInch() * 100));

                printDocument.PrinterSettings.DefaultPageSettings.PaperSize = sz;
            }
            else
            {
                printDocument.PrinterSettings.DefaultPageSettings.PaperSize = gevondenSize;
            }


            if ((FromPage > 0) || (ToPage != uint.MaxValue))
            {
                printDocument.PrinterSettings.PrintRange = PrintRange.SomePages;
                printDocument.PrinterSettings.FromPage   = (int)FromPage;
                printDocument.PrinterSettings.ToPage     = (int)ToPage;
            }
            else
            {
                printDocument.PrinterSettings.PrintRange = PrintRange.AllPages;
            }

            printDocument.DocumentName = DocumentName;

            try
            {
                printDocument.DefaultPageSettings.PaperSource.SourceName = Tray;
            }
            catch (InvalidPrinterException)
            {
                GlobalDataStore.Logger.Error("Printer " + printDocument.DefaultPageSettings.PrinterSettings.PrinterName + " does not exist.");
            }
            catch (Exception ex)
            {
                GlobalDataStore.Logger.Error(ex.Message);
            }
            printDocument.PrintController = new StandardPrintController();

            if (printDocument.PrinterSettings.PrinterName.Contains("Microsoft XPS Document Writer"))
            {
                try
                {
                    printDocument.PrinterSettings.PrintToFile   = true;
                    printDocument.PrinterSettings.PrintFileName = PreviewFileName + "tmp";
                    theBoundsCached = false;
                    printDocument.Print();
                    printDocument.Dispose();
                    FileInfo fi = new FileInfo(PreviewFileName + "tmp");
                    try
                    {
                        if (File.Exists(PreviewFileName))
                        {
                            File.Delete(PreviewFileName);
                        }
                    }
                    catch (Exception)
                    {
                        GlobalDataStore.Logger.Error(string.Format("Cannot remove file {0}", PreviewFileName));
                    }

                    try
                    {
                        fi.MoveTo(PreviewFileName);
                    }
                    catch
                    {
                        int  i     = 0;
                        bool ready = false;
                        while ((!ready) && (i < 10))
                        {
                            i++;
                            //Windows 8.1 locks files longer. Try another move after a wait
                            System.Threading.Thread.Sleep(100);
                            try
                            {
                                fi.MoveTo(PreviewFileName);
                                ready = true;
                            }
                            catch (Exception)
                            {
                                //GlobalDataStore.Logger.Error("Cannot rename file from " + PreviewFileName + "tmp " + "to " + PreviewFileName + ". ");
                            }
                        }
                        if (!ready)
                        {
                            GlobalDataStore.Logger.Error("Cannot rename file from " + PreviewFileName + "tmp " + "to " + PreviewFileName + ".");
                        }
                    }
                }
                catch (ArgumentNullException)
                {
                    GlobalDataStore.Logger.Error("Cannot print to an XPS writer without a filename!");
                }
                catch (Exception e)
                {
                    GlobalDataStore.Logger.Error("An unexpected error occured: " + e.Message);
                }
            }
            else
            {
                try
                {
                    printDocument.Print();
                }
                catch (InvalidPrinterException pe)
                {
                    GlobalDataStore.Logger.Error("Printing error. Selected printerdriver removed from your system?");
                    GlobalDataStore.Logger.Error(pe.Message);
                }
            }
            StaticVarslabel.Values.Clear();//Clear all static variables after printjob
            printDocument.Dispose();
        }
        /// <include file='doc\PageSetupDialog.uex' path='docs/doc[@for="PageSetupDialog.RunDialog"]/*' />
        /// <devdoc>
        /// </devdoc>
        /// <internalonly/>
        protected override bool RunDialog(IntPtr hwndOwner)
        {
            IntSecurity.SafePrinting.Demand();

            NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc);
            if (pageSettings == null)
            {
                throw new ArgumentException(SR.GetString(SR.PSDcantShowWithoutPage));
            }

            NativeMethods.PAGESETUPDLG data = new NativeMethods.PAGESETUPDLG();
            data.lStructSize       = Marshal.SizeOf(data);
            data.Flags             = GetFlags();
            data.hwndOwner         = hwndOwner;
            data.lpfnPageSetupHook = hookProcPtr;

            PrinterUnit toUnit = PrinterUnit.ThousandthsOfAnInch;

            // Refer VSWhidbey: 331160. Below was a breaking change from RTM and EVERETT even though this was a correct FIX.
            // EnableMetric is a new Whidbey property which we allow the users to choose between the AutoConversion or not.
            if (EnableMetric)
            {
                //take the Units of Measurement while determining the PrinterUnits...
                //bug (121347)...
                StringBuilder sb     = new StringBuilder(2);
                int           result = UnsafeNativeMethods.GetLocaleInfo(NativeMethods.LOCALE_USER_DEFAULT, NativeMethods.LOCALE_IMEASURE, sb, sb.Capacity);

                if (result > 0 && Int32.Parse(sb.ToString(), CultureInfo.InvariantCulture) == 0)
                {
                    toUnit = PrinterUnit.HundredthsOfAMillimeter;
                }
            }

            if (MinMargins != null)
            {
                Margins margins = PrinterUnitConvert.Convert(MinMargins, PrinterUnit.Display, toUnit);
                data.minMarginLeft   = margins.Left;
                data.minMarginTop    = margins.Top;
                data.minMarginRight  = margins.Right;
                data.minMarginBottom = margins.Bottom;
            }

            if (pageSettings.Margins != null)
            {
                Margins margins = PrinterUnitConvert.Convert(pageSettings.Margins, PrinterUnit.Display, toUnit);
                data.marginLeft   = margins.Left;
                data.marginTop    = margins.Top;
                data.marginRight  = margins.Right;
                data.marginBottom = margins.Bottom;
            }

            // Ensure that the margins are >= minMargins.
            // This is a requirement of the PAGESETUPDLG structure.
            //
            data.marginLeft   = Math.Max(data.marginLeft, data.minMarginLeft);
            data.marginTop    = Math.Max(data.marginTop, data.minMarginTop);
            data.marginRight  = Math.Max(data.marginRight, data.minMarginRight);
            data.marginBottom = Math.Max(data.marginBottom, data.minMarginBottom);

            PrinterSettings printer = (printerSettings == null) ? pageSettings.PrinterSettings : printerSettings;

            // GetHDevmode demands AllPrintingAndUnmanagedCode Permission : Since we are calling that function we should Assert the permision,
            IntSecurity.AllPrintingAndUnmanagedCode.Assert();
            try {
                data.hDevMode  = printer.GetHdevmode(pageSettings);
                data.hDevNames = printer.GetHdevnames();
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            try {
                bool status = UnsafeNativeMethods.PageSetupDlg(data);
                if (!status)
                {
                    // Debug.WriteLine(Windows.CommonDialogErrorToString(Windows.CommDlgExtendedError()));
                    return(false);
                }

                UpdateSettings(data, pageSettings, printerSettings); // yes, printerSettings, not printer
                return(true);
            }
            finally {
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode));
                UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames));
            }
        }
	public PageSettings(PrinterSettings printerSettings) {}
    public void SetLayoutType(LayoutModes eViewMode)
    {
        PrintDocument pd = new PrintDocument();
        PrinterSettings ps = new PrinterSettings();
        
        //int* y = (int*)500;

        switch (eViewMode)
        {
            case LayoutModes.WYSIWYG:
                //SendMessage(this.Handle, EM_SETTARGETDEVICE, ps.GetHdevmode(), new IntPtr(y));
                break;
            case LayoutModes.WordWrap:
                SendMessage(new HandleRef(this, this.Handle), EM_SETTARGETDEVICE, 0, 0);
                break;
            case LayoutModes.Default:
                SendMessage(new HandleRef(this, this.Handle), EM_SETTARGETDEVICE, 0, 1);
                break;
        }
    }
		public static void LoadQualitySettings(PrinterSettings layeredProfile, Printer printer)
		{
			var collections = Datastore.Instance.dbSQLite.Table<SliceSettingsCollection>().Where(v => v.PrinterId == printer.Id && v.Tag == "quality");
			foreach (var collection in collections)
			{
				layeredProfile.QualityLayers.Add(new PrinterSettingsLayer(LoadSettings(collection))
				{
					LayerID = Guid.NewGuid().ToString(),
					Name = collection.Name
				});
			}
		}
		public static bool ParseShowString(string unsplitSettings, PrinterSettings printerSettings, List<PrinterSettingsLayer> layerCascade)
		{
			if (!string.IsNullOrEmpty(unsplitSettings))
			{
				string[] splitSettings = unsplitSettings.Split('&');

				foreach (var inLookupSettings in splitSettings)
				{
					var lookupSettings = inLookupSettings;
					if (!string.IsNullOrEmpty(lookupSettings))
					{
						string showValue = "0";
						if (lookupSettings.StartsWith("!"))
						{
							showValue = "1";
							lookupSettings = lookupSettings.Substring(1);
						}

						string sliceSettingValue = printerSettings.GetValue(lookupSettings, layerCascade);
						if (sliceSettingValue == showValue)
						{
							return false;
						}
					}
				}
			}

			return true;
		}
示例#35
0
        /// <summary>
        /// Print RDLC File
        /// </summary>
        /// <returns></returns>
        public bool Print()
        {
            this.pageIndex = 0;

            this.pageStreams.Clear();


            ReportPageSettings rps = this.localReport.GetDefaultPageSettings();

            float pageWidth    = 0f;
            float pageHeight   = 0f;
            float marginTop    = rps.Margins.Top / 100f;
            float marginLeft   = rps.Margins.Left / 100f;
            float marginRight  = rps.Margins.Right / 100f;
            float marginBottom = rps.Margins.Bottom / 100f;

            bool landscape = false;

            if (rps.PaperSize.Width > rps.PaperSize.Height)
            {
                pageWidth  = rps.PaperSize.Width / 100f;
                pageHeight = rps.PaperSize.Height / 100f;

                landscape = false;
            }
            else
            {
                pageWidth  = rps.PaperSize.Height / 100f;
                pageHeight = rps.PaperSize.Width / 100f;

                landscape = true;
            }
            string ImageDeviceInfo = string.Format(@"<DeviceInfo>
                                                        <OutputFormat>EMF</OutputFormat>
                                                        <PageWidth>{0}in</PageWidth>
                                                        <PageHeight>{1}in</PageHeight>
                                                        <MarginTop>{2}in</MarginTop>
                                                        <MarginLeft>{3}in</MarginLeft>
                                                        <MarginRight>{4}in</MarginRight>
                                                        <MarginBottom>{5}in</MarginBottom>
                                                     </DeviceInfo>",
                                                   pageWidth, pageHeight, marginTop, marginLeft, marginRight, marginBottom);

            Warning[] warnings = null;
            try
            {
                this.localReport.Render("Image", ImageDeviceInfo, CreatePrintPageStream, out warnings);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (warnings != null && warnings.Length > 0)
            {
                string warnMsg = string.Empty;

                foreach (Warning warning in warnings)
                {
                    warnMsg += string.Format("WarningCode: {0} WarningMessage: {1}\r\n", warning.Code, warning.Message);
                }

                throw new Exception(warnMsg);
            }

            if (this.pageStreams == null || this.pageStreams.Count == 0)
            {
                return(false);
            }

            try
            {
                PageSetupDialog psd      = new PageSetupDialog();
                PrinterSettings printset = new PrinterSettings();

                XmlDocument doc = new XmlDocument();
                //doc.Load(System.Configuration.ConfigurationManager.AppSettings["printset"].ToString());
                string xmlFile = AppDomain.CurrentDomain.BaseDirectory + "BugsBox.Pharmacy.AppClient.printSet.xml";
                doc.Load(xmlFile);
                string s = System.Environment.CurrentDirectory;

                XmlNodeList nodelist = doc.SelectNodes("/printsets/pageset");


                int          wt      = Convert.ToInt16(nodelist[0].Attributes["width"].Value);
                int          ht      = Convert.ToInt16(nodelist[1].Attributes["height"].Value);
                PaperSize    pse     = new PaperSize("Custom", wt, ht);
                PageSettings pageset = new PageSettings();


                int     Bottom = Convert.ToInt16(nodelist[2].Attributes["top"].Value);
                int     Top    = Convert.ToInt16(nodelist[3].Attributes["left"].Value);
                int     Left   = Convert.ToInt16(nodelist[4].Attributes["right"].Value);
                int     Right  = Convert.ToInt16(nodelist[5].Attributes["bottom"].Value);
                Margins margin = new Margins(Left, Right, Top, Bottom);
                pageset.Margins = margin;

                pageset.PaperSize = pse;

                printset.DefaultPageSettings.PaperSize = pse;
                psd.PrinterSettings                = printset;
                psd.PageSettings                   = pageset;
                psd.PageSettings.PaperSize         = pse;
                this.printDocument.PrinterSettings = psd.PrinterSettings;
                //int printAreaWidth = Convert.ToInt16(psd.PageSettings.PrintableArea.Width);
                //int printAreaHeight = Convert.ToInt16(psd.PageSettings.PrintableArea.Height);



                //if(psd.ShowDialog()==DialogResult.Cancel)return false;

                //if (printAreaHeight != Convert.ToInt16(psd.PrinterSettings.DefaultPageSettings.PrintableArea.Height) || printAreaWidth != Convert.ToInt16(psd.PrinterSettings.DefaultPageSettings.PrintableArea.Width))
                //{


                //    nodelist[0].Attributes[0].Value = (this.printDocument.DefaultPageSettings.PrintableArea.Width + this.printDocument.DefaultPageSettings.HardMarginX * 2).ToString("F0");
                //    nodelist[1].Attributes[0].Value = (this.printDocument.DefaultPageSettings.PrintableArea.Height +this.printDocument.DefaultPageSettings.HardMarginY*2).ToString("F0");
                //    nodelist[2].Attributes[0].Value = (this.printDocument.DefaultPageSettings.Margins.Top).ToString();
                //    nodelist[3].Attributes[0].Value = (this.printDocument.DefaultPageSettings.Margins.Left).ToString();
                //    nodelist[4].Attributes[0].Value = (this.printDocument.DefaultPageSettings.Margins.Right).ToString();
                //    nodelist[5].Attributes[0].Value = (this.printDocument.DefaultPageSettings.Margins.Bottom).ToString();

                //    doc.Save(System.Configuration.ConfigurationManager.AppSettings["printset"].ToString());

                //}

                //this.printDocument.Print();
                this.printPreview.Document = this.printDocument;
                this.printPreview.ShowDialog();
                //使用image输出到文件后,可能会改变应用程序默认路径,所以。。。。。。。。
                if (System.Environment.CurrentDirectory != s)
                {
                    System.Environment.CurrentDirectory = s;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("打印配置文件丢失,请检查!\n" + ex.Message);
            }
            return(true);
        }
示例#36
0
        public async Task <bool> Print(PrinterSettings printerSettings, List <ScannedImage> images, List <ScannedImage> selectedImages)
        {
            List <ScannedImage> imagesToPrint;

            switch (printerSettings.PrintRange)
            {
            case PrintRange.AllPages:
                imagesToPrint = images;
                break;

            case PrintRange.Selection:
                imagesToPrint = selectedImages;
                break;

            case PrintRange.SomePages:
                int start  = printerSettings.FromPage - 1;
                int length = printerSettings.ToPage - start;
                imagesToPrint = images.Skip(start).Take(length).ToList();
                break;

            default:
                imagesToPrint = new List <ScannedImage>();
                break;
            }
            if (imagesToPrint.Count == 0)
            {
                return(false);
            }

            var snapshots = imagesToPrint.Select(x => x.Preserve()).ToList();

            return(await Task.Factory.StartNew(() =>
            {
                try
                {
                    var printDocument = new PrintDocument();
                    int i = 0;
                    printDocument.PrintPage += (sender, e) =>
                    {
                        var image = Task.Factory.StartNew(() => scannedImageRenderer.Render(imagesToPrint[i])).Unwrap().Result;
                        try
                        {
                            var pb = e.PageBounds;
                            if (Math.Sign(image.Width - image.Height) != Math.Sign(pb.Width - pb.Height))
                            {
                                // Flip portrait/landscape to match output
                                image = new RotationTransform(90).Perform(image);
                            }

                            // Fit the image into the output rect while maintaining its aspect ratio
                            var rect = image.Width / pb.Width < image.Height / pb.Height
                                ? new Rectangle(pb.Left, pb.Top, image.Width *pb.Height / image.Height, pb.Height)
                                : new Rectangle(pb.Left, pb.Top, pb.Width, image.Height *pb.Width / image.Width);

                            e.Graphics.DrawImage(image, rect);
                        }
                        finally
                        {
                            image.Dispose();
                        }

                        e.HasMorePages = (++i < imagesToPrint.Count);
                    };
                    printDocument.PrinterSettings = printerSettings;
                    printDocument.Print();

                    Log.Event(EventType.Print, new Event
                    {
                        Name = MiscResources.Print,
                        Pages = snapshots.Count,
                        DeviceName = printDocument.PrinterSettings.PrinterName
                    });

                    return true;
                }
                finally
                {
                    snapshots.ForEach(s => s.Dispose());
                }
            }, TaskCreationOptions.LongRunning));
        }
	// Constructors
	public InvalidPrinterException(PrinterSettings settings) {}
		public static PrinterSettings LoadEmptyProfile()
		{
			var emptyProfile = new PrinterSettings() { ID = "EmptyProfile" };
			emptyProfile.UserLayer[SettingsKey.printer_name] = "Printers...".Localize();

			return emptyProfile;
		}
示例#39
0
        // Update the dialog with information from the settings.
        void UpdateDialog()
        {
            PageSettings    pageSettings    = settings.PageSettings;
            PrinterSettings printerSettings = pageSettings.PrinterSettings;

            // Courses
            if (settings.CourseIds != null)
            {
                courseSelector.SelectedCourses = settings.CourseIds;
            }
            if (settings.AllCourses)
            {
                courseSelector.AllCoursesSelected = true;
            }
            courseSelector.VariationChoicesPerCourse = settings.VariationChoicesPerCourse;

            // Output section.
            printerName.Text = printerSettings.PrinterName;
            if (printerSettings.IsValid)
            {
                paperSize.Text   = Util.GetPaperSizeText(pageSettings.PaperSize);
                orientation.Text = (pageSettings.Landscape) ? MiscText.Landscape : MiscText.Portrait;
                margins.Text     = Util.GetMarginsText(pageSettings.Margins);
            }
            else
            {
                paperSize.Text = orientation.Text = margins.Text = "";
            }

            // Copies section.
            if (settings.CountKind == PrintingCountKind.DescriptionCount)
            {
                copiesCombo.SelectedIndex  = 2;
                descriptionsUpDown.Enabled = true;
                descriptionsLabel.Enabled  = true;
                descriptionsUpDown.Value   = settings.Count;
            }
            else
            {
                descriptionsUpDown.Enabled = false;
                descriptionsLabel.Enabled  = false;
                if (settings.CountKind == PrintingCountKind.OneDescription)
                {
                    copiesCombo.SelectedIndex = 0;
                }
                else
                {
                    copiesCombo.SelectedIndex = 1;
                }
            }

            // Appearance section
            boxSizeUpDown.Value = (decimal)settings.BoxSize;
            if (settings.UseCourseDefault)
            {
                descriptionKindCombo.SelectedIndex = 0;
            }
            else if (settings.DescKind == DescriptionKind.Symbols)
            {
                descriptionKindCombo.SelectedIndex = 1;
            }
            else if (settings.DescKind == DescriptionKind.Text)
            {
                descriptionKindCombo.SelectedIndex = 2;
            }
            else if (settings.DescKind == DescriptionKind.SymbolsAndText)
            {
                descriptionKindCombo.SelectedIndex = 3;
            }
        }
示例#40
0
        private void Imprimir(Stream stream)
        {
            try
            {
                this.Log().Debug("Iniciando impressão.");

                using (internalReport = new Report())
                {
                    PrepararImpressao();

                    this.Log().Debug("Passando dados para impressão.");

                    internalReport.RegisterData(Parent.NotasServico.ToArray(), "NotaServico");
                    internalReport.Prepare();

                    switch (Filtro)
                    {
                    case FiltroDFeReport.Nenhum:
                        if (MostrarPreview)
                        {
                            internalReport.Show();
                        }
                        else if (MostrarSetup)
                        {
                            internalReport.PrintWithDialog();
                        }
                        else
                        {
                            internalReport.Print(settings);
                        }
                        break;

                    case FiltroDFeReport.PDF:
                        this.Log().Debug("Exportando para PDF.");

                        var evtPdf = new DANFSeExportEventArgs();
                        evtPdf.Filtro = Filtro;
                        evtPdf.Export = new PDFSimpleExport()
                        {
                            ImageDpi        = 600,
                            ShowProgress    = MostrarSetup,
                            OpenAfterExport = MostrarPreview
                        };

                        OnExport.Raise(this, evtPdf);
                        if (stream.IsNull())
                        {
                            internalReport.Export(evtPdf.Export, NomeArquivo);
                        }
                        else
                        {
                            internalReport.Export(evtPdf.Export, stream);
                        }

                        this.Log().Debug("Exportação concluida.");
                        break;

                    case FiltroDFeReport.HTML:
                        this.Log().Debug("Exportando para HTML.");

                        var evtHtml = new DANFSeExportEventArgs();
                        evtHtml.Filtro = Filtro;
                        evtHtml.Export = new HTMLExport()
                        {
                            Format        = HTMLExportFormat.HTML,
                            EmbedPictures = true,
                            Preview       = MostrarPreview,
                            ShowProgress  = MostrarSetup
                        };

                        OnExport.Raise(this, evtHtml);
                        if (stream.IsNull())
                        {
                            internalReport.Export(evtHtml.Export, NomeArquivo);
                        }
                        else
                        {
                            internalReport.Export(evtHtml.Export, stream);
                        }

                        this.Log().Debug("Exportação concluida.");
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    this.Log().Debug("Impressão Concluida.");
                }
            }
            finally
            {
                internalReport = null;
                settings       = null;
            }
        }
示例#41
0
        public void Print(FileInfo file, PrinterSettings printerSettings, PageSettings pageSettings)
        {
            var bmp = Bitmap.FromFile(file.FullName);

            void ppp(object sender, PrintPageEventArgs e)
            {
                var newWidth    = bmp.Width * 100 / bmp.HorizontalResolution;
                var newHeight   = bmp.Height * 100 / bmp.VerticalResolution;
                var widthFactor = (pageSettings.Landscape)
                    ? newWidth / e.PageSettings.PrintableArea.Height
                    : newWidth / e.PageSettings.PrintableArea.Width;
                var HeightFactor = (pageSettings.Landscape)
                    ? newHeight / e.PageSettings.PrintableArea.Width
                    : newHeight / e.PageSettings.PrintableArea.Height;
                var widthMargin  = 0;
                var heightMargin = 0;

                if (widthFactor > 1 || HeightFactor > 1)
                {
                    if (widthFactor > HeightFactor)
                    {
                        newWidth  /= widthFactor;
                        newHeight /= widthFactor;
                    }
                    else
                    {
                        newWidth  /= HeightFactor;
                        newHeight /= HeightFactor;
                    }
                }
                if (pageSettings.Landscape)
                {
                    heightMargin = (int)((e.PageSettings.PrintableArea.Height - newHeight) / 2) / 2;
                }
                else
                {
                    widthMargin = (int)((e.PageSettings.PrintableArea.Width - newWidth) / 2) / 2;
                }
                var h = e.PageSettings.PrintableArea.Height;
                var m = (e.PageSettings.PrintableArea.Height - h) / 2;

                e.Graphics.DrawImage(bmp,
                                     (e.PageSettings.HardMarginX + widthMargin),
                                     (e.PageSettings.HardMarginY + heightMargin),
                                     newWidth,
                                     newHeight);
            }

            var printDoc = new PrintDocument
            {
                DefaultPageSettings = pageSettings
            };

            if (!file.Exists)
            {
                return;
            }
            printDoc.PrinterSettings = printerSettings;
            printDoc.PrintPage      += ppp;
            printDoc.Print();
            bmp.Dispose();
        }
        private void PrintJob(IEnumerable <object> items)
        {
            if (items != null)
            {
                StringWriter writer = new StringWriter();
                foreach (TypesetFileList item in items)
                {
                    Task.Run(async() =>
                    {
                        string uri = "http://xdkyu02.cafe24.com/fileDownload.do?fileId=" + item.fileId.ToString();

                        Console.WriteLine(_jwt);
                        Console.WriteLine(uri);

                        using (var client = new HttpClient())
                        {
                            client.DefaultRequestHeaders.Add("x-access-token", _jwt);

                            var response = await client.GetAsync(uri);
                            Console.WriteLine(response);
                            if (response.IsSuccessStatusCode)
                            {
                                var jsonresult = response.Content.ReadAsStringAsync().Result;
                                Console.WriteLine(jsonresult);
                                //deserialized 된 Json
                                var jsonParse = JsonConvert.DeserializeObject <DownloadResponse>(jsonresult);
                                var fileUrl   = jsonParse.data.fileUrl;
                                using (var webclient = new WebClient())
                                {
                                    Console.WriteLine(item.fileType);
                                    webclient.DownloadFile(fileUrl, "C:\\temp\\" + item.fileId + item.fileType);


                                    bool succ = false;
                                    if (item.fileType == "pdf")
                                    {
                                        succ = Pdf.PrintPDFs("C:\\temp\\" + item.fileId + ".pdf");
                                    }
                                    else
                                    {
                                        IPrinter printer         = new Printer();
                                        PrinterSettings settings = new PrinterSettings();
                                        var PrinterName          = settings.PrinterName;
                                        Console.WriteLine(PrinterName);
                                        printer.PrintRawFile(PrinterName, "C:\\temp\\", item.fileId + "." + item.fileType);
                                        succ = true;
                                    }
                                    if (succ)
                                    {
                                        PdfReader pdfReader = new PdfReader("C:\\temp\\" + item.fileId + ".pdf");
                                        int numberOfPages   = pdfReader.NumberOfPages;

                                        string uri2 = "http://xdkyu02.cafe24.com/insertPrintLog.do";

                                        string json = new JavaScriptSerializer().Serialize(new
                                        {
                                            printCount = numberOfPages,
                                            ClientId   = 1,
                                            userId     = _user.userId,
                                            fileId     = item.fileId
                                        });

                                        await Task.Run(async() =>
                                        {
                                            using (var client2 = new HttpClient())
                                            {
                                                client.DefaultRequestHeaders.Add("x-access-token", _jwt);
                                                var response2 = await client.PostAsync(
                                                    uri2,
                                                    new StringContent(json, Encoding.UTF8, "application/json"));
                                                if (response.IsSuccessStatusCode)
                                                {
                                                    var jsonresult2 = response.Content.ReadAsStringAsync().Result;


                                                    return(true);
                                                    //else return false;
                                                }
                                                else
                                                {
                                                    return(false);
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                            else
                            {
                            }
                        }
                    });
                }
                string[] files = Directory.GetFiles(@"c:\temp");
                foreach (string file in files.Where(
                             file => file.ToUpper().Contains(".PDF")))
                {
                }
            }
        }
		internal static bool ImportFromExisting(string settingsFilePath)
		{
			if (string.IsNullOrEmpty(settingsFilePath) || !File.Exists(settingsFilePath))
			{
				return false;
			}

			string fileName = Path.GetFileNameWithoutExtension(settingsFilePath);
			var existingPrinterNames = Instance.ActiveProfiles.Select(p => p.Name);

			var printerInfo = new PrinterInfo
			{
				Name = agg_basics.GetNonCollidingName(existingPrinterNames, fileName),
				ID = Guid.NewGuid().ToString(),
				Make = "Other",
				Model = "Other",
			};

			bool importSuccessful = false;

			string importType = Path.GetExtension(settingsFilePath).ToLower();
			switch (importType)
			{
				case ProfileManager.ProfileExtension:
					// Add the Settings as a profile before performing any actions on it to ensure file paths resolve
					{
						Instance.Profiles.Add(printerInfo);

						var printerSettings = PrinterSettings.LoadFile(settingsFilePath);
						printerSettings.ID = printerInfo.ID;
						printerSettings.ClearValue(SettingsKey.device_token);
						printerInfo.DeviceToken = "";

						// TODO: Resolve name conflicts
						printerSettings.Helpers.SetName(printerInfo.Name);

						if (printerSettings.OemLayer.ContainsKey(SettingsKey.make))
						{
							printerInfo.Make = printerSettings.OemLayer[SettingsKey.make];
						}

						if (printerSettings.OemLayer.ContainsKey(SettingsKey.model))
						{
							printerInfo.Model = printerSettings.OemLayer[SettingsKey.model] ?? "Other";
						}

						printerSettings.Save();
						importSuccessful = true;
					}
					break;

				case ".ini":
					//Scope variables
					{
						var settingsToImport = PrinterSettingsLayer.LoadFromIni(settingsFilePath);
						var printerSettings = new PrinterSettings()
						{
							ID = printerInfo.ID,
						};

						bool containsValidSetting = false;

						printerSettings.OemLayer = new PrinterSettingsLayer();

						printerSettings.OemLayer[SettingsKey.make] = "Other";
						printerSettings.OemLayer[SettingsKey.model] = "Other";

						foreach (var item in settingsToImport)
						{
							if (printerSettings.Contains(item.Key))
							{
								containsValidSetting = true;
								string currentValue = printerSettings.GetValue(item.Key).Trim();
								// Compare the value to import to the layer cascade value and only set if different
								if (currentValue != item.Value)
								{
									printerSettings.OemLayer[item.Key] = item.Value;
								}
							}
						}

						if(containsValidSetting)
						{
							printerSettings.UserLayer[SettingsKey.printer_name] = printerInfo.Name;

							printerSettings.ClearValue(SettingsKey.device_token);
							printerInfo.DeviceToken = "";

							printerInfo.Make = printerSettings.OemLayer[SettingsKey.make] ?? "Other";
							printerInfo.Model = printerSettings.OemLayer[SettingsKey.model] ?? "Other";

							Instance.Profiles.Add(printerInfo);

							printerSettings.Helpers.SetName(printerInfo.Name);

							printerSettings.Save();
							importSuccessful = true;
						}
					}
					break;
			}
			return importSuccessful;
		}
		public PrintLevelingData(PrinterSettings printerProfile)
		{
			this.printerProfile = printerProfile;
		}
		public void firstLayerExtrusionWidthAcceptableValue(PrinterSettings printerSettings, PrinterSettingsLayer layer, string sourceFile)
		{
			string firstLayerExtrusionWidth;
			if (!layer.TryGetValue(SettingsKey.first_layer_extrusion_width, out firstLayerExtrusionWidth))
			{
				return;
			}

			float convertedFirstLayerExtrusionWidth;

			string nozzleDiameter = printerSettings.GetValue(SettingsKey.nozzle_diameter);
			float acceptableValue = float.Parse(nozzleDiameter) * 4;

			if (firstLayerExtrusionWidth.Contains("%"))
			{
				string reformatFirstLayerExtrusionWidth = firstLayerExtrusionWidth.Replace("%", " ");
				convertedFirstLayerExtrusionWidth = float.Parse(reformatFirstLayerExtrusionWidth) / 100;
			}
			else
			{
				convertedFirstLayerExtrusionWidth = float.Parse(firstLayerExtrusionWidth);
			}

			Assert.LessOrEqual(convertedFirstLayerExtrusionWidth, acceptableValue, "Unexpected firstLayerExtrusionWidthAcceptableValue value: " + sourceFile);
		}
		public SettingsHelpers(PrinterSettings printerSettings)
		{
			this.printerSettings = printerSettings;
		}
示例#47
0
 public PageSettings(PrinterSettings printerSettings)
 {
     throw null;
 }
示例#48
0
        private void cboPrinter_SelectedIndexChanged(object sender, EventArgs e)
        {
            PrinterSettings settings = new PrinterSettings();

            myPrinters.SetDefaultPrinter(this.cboPrinter.Text);
        }
示例#49
0
 public override IFrostedSerialPort Create(string serialPortName, PrinterSettings settings)
 {
     return(new TcpipSerialPort(settings, serialPortName));
 }
示例#50
0
 public override bool SerialPortIsAvailable(string serialPortName, PrinterSettings settings)
 {
     return(int.TryParse(settings.GetValue(SettingsKey.ip_port), out _) &&
            IPAddress.TryParse(settings.GetValue(SettingsKey.ip_address), out _));
 }
		static ActiveSliceSettings()
		{
			// Load last profile or fall back to empty
			Instance = ProfileManager.Instance?.LoadLastProfileWithoutRecovery() ?? ProfileManager.LoadEmptyProfile();
		}
 /// <summary>
 /// Prints file
 /// </summary>
 /// <param name="fileName">file name</param>
 /// <param name="printerSettings">printer settings</param>
 private void Print(string fileName, string documentName, PrinterSettings printerSettings, PostScriptMetaData data)
 {
     SetStatus("Printing");
     PrintHelper.Print(fileName, documentName, printerSettings, data);
     Close();
 }
		public static void RefreshActiveInstance(PrinterSettings updatedProfile)
		{
			bool themeChanged = activeInstance.GetValue(SettingsKey.active_theme_name) != updatedProfile.GetValue(SettingsKey.active_theme_name);

			activeInstance = updatedProfile;

			SliceSettingsWidget.SettingChanged.CallEvents(null, new StringEventArgs(SettingsKey.printer_name));

			if (themeChanged)
			{
				UiThread.RunOnIdle(() => SwitchToPrinterTheme(true));
			}
			else
			{
				UiThread.RunOnIdle(ApplicationController.Instance.ReloadAdvancedControlsPanel);
			}
		}
示例#54
0
        protected void btnPrintExcelClick(object sender, EventArgs e)
        {
            if (this.FileUpload1.HasFile)
            {
                string ext = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName).ToLower();
                if (ext == ".xls" || ext == ".xlsx")
                {
                    #region Print

                    Stream readFile = this.FileUpload1.PostedFile.InputStream;
                    try
                    {
                        ExcelToPdfConverter converter = null;
                        if (ext == ".xls")
                        {
                            converter = new ExcelToPdfConverter(readFile);
                        }
                        else if (ext == ".xlsx")
                        {
                            converter = new ExcelToPdfConverter(readFile);
                        }
                        converter.ChartToImageConverter = new ChartToImageConverter();
                        //Set the image quality
                        converter.ChartToImageConverter.ScalingMode = ScalingMode.Best;

                        //Create new printerSettings instance.
                        PrinterSettings printerSettings = new PrinterSettings();
                        printerSettings.FromPage = 1;
                        printerSettings.Collate  = true;
                        printerSettings.Copies   = 2;
                        printerSettings.Duplex   = Duplex.Simplex;
                        if (this.printWithConverterAndPrinterBtn.Checked)
                        {
                            //Print excel document with specified printer settings and converter settings.
                            converter.Print(printerSettings, GetConverterSettings());
                        }
                        else if (this.printWithPrinterBtn.Checked)
                        {
                            //Print excel document with specified printer settings.
                            converter.Print(printerSettings);
                        }
                        else if (this.printWithConverterBtn.Checked)
                        {
                            //Print excel document with specified and converter settings.
                            converter.Print(GetConverterSettings());
                        }
                        else if (this.defaultPrintBtn.Checked)
                        {
                            //print excel document with default printer settings.
                            converter.Print();
                        }
                    }
                    catch (Exception)
                    {
                        this.label1.Text = "The input document could not be processed, Could you please email the document to [email protected] for troubleshooting";
                    }

                    # endregion
                }
                else
                {
                    this.label1.Text = "Please choose xls or xlsx file to print";
                }
            }
            else
            {
                this.label1.Text = "Browse a Excel document and then click the button to print the document";
            }
        }