/// <summary> /// 原生支付 模式一 /// </summary> /// <returns></returns> public ActionResult Native() { RequestHandler nativeHandler = new RequestHandler(null); string timeStamp = TenPayV3Util.GetTimestamp(); string nonceStr = TenPayV3Util.GetNoncestr(); //商品Id,用户自行定义 string productId = DateTime.Now.ToString("yyyyMMddHHmmss"); nativeHandler.SetParameter("appid", TenPayV3Info.AppId); nativeHandler.SetParameter("mch_id", TenPayV3Info.MchId); nativeHandler.SetParameter("time_stamp", timeStamp); nativeHandler.SetParameter("nonce_str", nonceStr); nativeHandler.SetParameter("product_id", productId); string sign = nativeHandler.CreateMd5Sign("key", TenPayV3Info.Key); var url = TenPayV3.NativePay(TenPayV3Info.AppId, timeStamp, TenPayV3Info.MchId, nonceStr, productId, sign); BitMatrix bitMatrix; bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 600, 600); var bw = new ZXing.BarcodeWriterPixelData(); var pixelData = bw.Write(bitMatrix); using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) { using (var ms = new MemoryStream()) { var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); return(File(ms, "image/png")); } } }
private void GeneratePng(TagHelperOutput output, string content, BarcodeFormat barcodeformat, int width, int height, int margin, string alt) { var qrWriter = new ZXing.BarcodeWriterPixelData { Format = barcodeformat, Options = new QrCodeEncodingOptions { Height = height, Width = width, Margin = margin } }; var pixelData = qrWriter.Write(content); // creating a bitmap from the raw pixel data; if only black and white colors are used it makes no difference // that the pixel data ist BGRA oriented and the bitmap is initialized with RGB // the System.Drawing.Bitmap class is provided by the CoreCompat.System.Drawing package using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) using (var ms = new MemoryStream()) { // lock the data area for fast access var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } // save to stream as PNG bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); output.TagName = "img"; output.Attributes.Clear(); output.Attributes.Add("width", pixelData.Width); output.Attributes.Add("height", pixelData.Height); output.Attributes.Add("alt", alt); output.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(ms.ToArray()))); } }
/// <summary> /// 显示二维码 /// </summary> /// <param name="productId"></param> /// <returns></returns> public ActionResult ProductPayCode(int productId, int hc) { var products = ProductModel.GetFakeProductList(); var product = products.FirstOrDefault(z => z.Id == productId); if (product == null || product.GetHashCode() != hc) { return(Content("商品信息不存在,或非法进入!2004")); } var url = string.Format("http://sdk.weixin.senparc.com/TenPayV3/JsApi?productId={0}&hc={1}&t={2}", productId, product.GetHashCode(), SystemTime.Now.Ticks); BitMatrix bitMatrix; bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 600, 600); var bw = new ZXing.BarcodeWriterPixelData(); var pixelData = bw.Write(bitMatrix); using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) { using (var ms = new MemoryStream()) { var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } ms.Flush(); //.net core 必须要加 ms.Position = 0; //.net core 必须要加 bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); return(File(ms, "image/png")); } } }
public override void Process(TagHelperContext context, TagHelperOutput output) { var content = context.AllAttributes["content"].Value.ToString(); var width = int.Parse(context.AllAttributes["width"].Value.ToString()); var height = int.Parse(context.AllAttributes["height"].Value.ToString()); var barcodeWriterPixelData = new ZXing.BarcodeWriterPixelData { Format = ZXing.BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = height, Width = width, Margin = 0 } }; var pixelData = barcodeWriterPixelData.Write(content); using (var bitmap = new Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) { using (var memoryStream = new MemoryStream()) { var bitmapData = bitmap.LockBits(new Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png); output.TagName = "img"; output.Attributes.Clear(); output.Attributes.Add("width", width); output.Attributes.Add("height", height); output.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(memoryStream.ToArray()))); //Without Razor //IBarcodeWriter barCodeWriter = new IBarcodeWriter(); //var writerSvg = new ZXing.IBarcodeWriterSvg } } }
public override bool WriteCoinToQRCode(CloudCoin cloudCoin, string OutputFile, string tag) { var width = 250; // width of the Qr Code var height = 250; // height of the Qr Code var margin = 0; var qrCodeWriter = new ZXing.BarcodeWriterPixelData { Format = ZXing.BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = height, Width = width, Margin = margin } }; string coinJson = JsonConvert.SerializeObject(cloudCoin); var pixelData = qrCodeWriter.Write(coinJson); // creating a bitmap from the raw pixel data; if only black and white colors are used it makes no difference // that the pixel data ist BGRA oriented and the bitmap is initialized with RGB using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) using (var ms = new MemoryStream()) { var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } // save to stream as PNG bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); bitmap.Save(OutputFile); } return(true); }
public static string GenerateQR(string str, string serverpath = @"C:\", int width = 80, int height = 80) { //var checkfolder = CheckFolderExists(serverpath); string barcodeString = str; string path = Path.GetTempFileName() + ".jpg"; var writer = new ZXing.BarcodeWriterPixelData { Format = ZXing.BarcodeFormat.QR_CODE, }; var options = new QrCodeEncodingOptions { DisableECI = true, CharacterSet = "UTF-8", Width = width, Height = height, }; writer.Options = options; var pixelData = writer.Write(barcodeString); using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) using (var ms = new MemoryStream()) { var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } // save to stream as PNG //bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); bitmap.Save(path, ImageFormat.Jpeg); } return(path); }
/// <summary> /// 生成二维码图片 /// </summary> /// <param name="contents">要生成二维码包含的信息</param> /// <param name="width">生成的二维码宽度(默认300像素)</param> /// <param name="height">生成的二维码高度(默认300像素)</param> /// <returns>二维码图片</returns> public static byte[] GeneratorQrImage(string contents, int width = 300, int height = 300) { if (string.IsNullOrEmpty(contents)) { return(null); } var writerSvg = new ZXing.BarcodeWriterPixelData { Format = ZXing.BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { ErrorCorrection = ErrorCorrectionLevel.H, CharacterSet = "UTF-8", DisableECI = true, Width = width, Height = height, } }; var pixelData = writerSvg.Write(contents); return(ConvertPixelDataToByteArray(pixelData)); }
private byte[] GenerateBarCodeZXing(string data) { var qrCodeWriter = new ZXing.BarcodeWriterPixelData { Format = ZXing.BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = 250, Width = 250, Margin = 0 } }; var pixelData = qrCodeWriter.Write(data); // creating a bitmap from the raw pixel data; if only black and white colors are used it makes no difference // that the pixel data ist BGRA oriented and the bitmap is initialized with RGB using (var bitmap = new Bitmap(pixelData.Width, pixelData.Height, PixelFormat.Format32bppRgb)) using (var ms = new MemoryStream()) { var bitmapData = bitmap.LockBits(new System.DrawingCore.Rectangle(0, 0, pixelData.Width, pixelData.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } // save to stream as PNG bitmap.Save(ms, ImageFormat.Png); ImageConverter converter = new ImageConverter(); return((byte[])converter.ConvertTo(ms, typeof(byte[]))); //return null; } }
public void generateBoardingpass() { //var writer = new QRCodeWriter(); //var bitmap = writer.encode(Voornaam + Naam + Id, BarcodeFormat.QR_CODE, 300, 300); //bitmap. var width = 250; // width of the Qr Code var height = 250; // height of the Qr Code var margin = 0; var qrCodeWriter = new ZXing.BarcodeWriterPixelData { Format = ZXing.BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = height, Width = width, Margin = margin } }; var pixelData = qrCodeWriter.Write(Id + Naam + Voornaam); // creating a bitmap from the raw pixel data; if only black and white colors are used it makes no difference // that the pixel data ist BGRA oriented and the bitmap is initialized with RGB using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) using (var ms = new MemoryStream()) { var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } // save to stream as PNG bitmap.Save("Boardingpasses/" + Voornaam + Naam + Id + ".png"); } }
public static byte[] CreateQrCode(string content) { var qrWriter = new ZXing.BarcodeWriterPixelData { Format = BarcodeFormat.QR_CODE, Options = new EncodingOptions { Height = 100, Width = 100, Margin = 1 } }; var pixelData = qrWriter.Write(content); // creating a bitmap from the raw pixel data; if only black and white colors are used it makes no difference // that the pixel data ist BGRA oriented and the bitmap is initialized with RGB // the System.Drawing.Bitmap class is provided by the CoreCompat.System.Drawing package using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) using (var ms = new MemoryStream()) { // lock the data area for fast access var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } // save to stream as PNG bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); Console.WriteLine(content); return(ms.ToArray()); } }
public void SetUrl(string url) { var bitmapRenderer = new ZXing.Rendering.WriteableBitmapRenderer(); bitmapRenderer.Background = System.Windows.Media.Colors.White; bitmapRenderer.Foreground = System.Windows.Media.Colors.Black; ZXing.BarcodeWriterPixelData qrWriter = new ZXing.BarcodeWriterPixelData() { Format = BarcodeFormat.QR_CODE, Options = new ZXing.Common.EncodingOptions() { Height = 1024, Width = 1024 } }; var bitmap = bitmapRenderer.Render(qrWriter.Encode(url), BarcodeFormat.QR_CODE, url); QrImage.Source = bitmap; UrlText.Text = "spin.exe --uri " + url; }
public ActionResult Index(string codesStr) { var codes = codesStr.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); var i = 0; foreach (var code in codes) { i++; BitMatrix bitMatrix; bitMatrix = new MultiFormatWriter().encode(code, BarcodeFormat.QR_CODE, 600, 600); var bw = new ZXing.BarcodeWriterPixelData(); var pixelData = bw.Write(bitMatrix); var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb); var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } var fileName = Path.Combine(CO2NET.Config.RootDictionaryPath, "QrCodes", $"{i}.jpg");//需要确保文件夹存在! SenparcTrace.SendCustomLog("二维码生成", fileName); var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite); { bitmap.Save(fileStream, System.Drawing.Imaging.ImageFormat.Png); } } return(Content("done.")); }
public override void Process(TagHelperContext context, TagHelperOutput output) { var content = context.AllAttributes["content"]?.Value.ToString(); var alt = context.AllAttributes["alt"]?.Value.ToString(); var width = Convert.ToInt32(context.AllAttributes["width"] == null ? "500" : context.AllAttributes["width"].Value.ToString()); var height = Convert.ToInt32(context.AllAttributes["height"] == null ? "500" : context.AllAttributes["height"].Value.ToString()); var margin = Convert.ToInt32(context.AllAttributes["margin"] == null ? "5" : context.AllAttributes["margin"].Value.ToString()); var barcodeformat = BarcodeFormat.QR_CODE; var outputformat = OutputFormat.PNG; if (context.AllAttributes["barcodeformat"] != null) { if (!Enum.TryParse(context.AllAttributes["barcodeformat"].Value.ToString(), true, out barcodeformat)) { barcodeformat = BarcodeFormat.QR_CODE; } } if (context.AllAttributes["outputformat"] != null) { if (!Enum.TryParse(context.AllAttributes["outputformat"].Value.ToString(), true, out outputformat)) { outputformat = OutputFormat.PNG; } } if (String.IsNullOrEmpty(content)) { return; } var qrWriter = new ZXing.BarcodeWriterPixelData { Format = barcodeformat, Options = new QrCodeEncodingOptions { Height = height, Width = width, Margin = margin } }; var pixelData = qrWriter.Write(content); // creating a bitmap from the raw pixel data; if only black and white colors are used it makes no difference // that the pixel data ist BGRA oriented and the bitmap is initialized with RGB // the System.Drawing.Bitmap class is provided by the CoreCompat.System.Drawing package using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) using (var ms = new MemoryStream()) { // lock the data area for fast access var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } // save to stream as PNG bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); output.TagName = "img"; output.Attributes.Clear(); output.Attributes.Add("width", width); output.Attributes.Add("height", height); output.Attributes.Add("alt", alt); output.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(ms.ToArray()))); } }
/// <summary> /// 原生支付 模式二 /// 根据统一订单返回的code_url生成支付二维码。该模式链接较短,生成的二维码打印到结账小票上的识别率较高。 /// 注意:code_url有效期为2小时,过期后扫码不能再发起支付 /// </summary> /// <returns></returns> public ActionResult NativeByCodeUrl() { //创建支付应答对象 //RequestHandler packageReqHandler = new RequestHandler(null); var sp_billno = SystemTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(26); var nonceStr = TenPayV3Util.GetNoncestr(); //商品Id,用户自行定义 string productId = SystemTime.Now.ToString("yyyyMMddHHmmss"); //创建请求统一订单接口参数 //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId); //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId); //packageReqHandler.SetParameter("nonce_str", nonceStr); //packageReqHandler.SetParameter("body", "test"); //packageReqHandler.SetParameter("out_trade_no", sp_billno); //packageReqHandler.SetParameter("total_fee", "1"); //packageReqHandler.SetParameter("spbill_create_ip", HttpContext.UserHostAddress()?.ToString()); //packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify); //packageReqHandler.SetParameter("trade_type", TenPayV3Type.NATIVE.ToString()); //packageReqHandler.SetParameter("product_id", productId); //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key); //packageReqHandler.SetParameter("sign", sign); //string data = packageReqHandler.ParseXML(); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, "test", sp_billno, 1, HttpContext.UserHostAddress()?.ToString(), TenPayV3Info.TenPayV3Notify, TenPay.TenPayV3Type.NATIVE, null, TenPayV3Info.Key, nonceStr, productId: productId); //调用统一订单接口 var result = TenPayV3.Unifiedorder(xmlDataInfo); //var unifiedorderRes = XDocument.Parse(result); //string codeUrl = unifiedorderRes.Element("xml").Element("code_url").Value; string codeUrl = result.code_url; BitMatrix bitMatrix; bitMatrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, 600, 600); var bw = new ZXing.BarcodeWriterPixelData(); var pixelData = bw.Write(bitMatrix); using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) { using (var ms = new MemoryStream()) { var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); return(File(ms, "image/png")); } } }
/// <summary> /// 生成中间带有图片的二维码图片 /// </summary> /// <param name="contents">要生成二维码包含的信息</param> /// <param name="middleImg">要生成到二维码中间的图片</param> /// <param name="width">生成的二维码宽度(默认300像素)</param> /// <param name="height">生成的二维码高度(默认300像素)</param> /// <returns>中间带有图片的二维码</returns> public static Bitmap GeneratorQrImage(string contents, Image middleImg, int width = 300, int height = 300) { if (string.IsNullOrEmpty(contents)) { return(null); } if (middleImg == null) { return(null); //return GeneratorQrImage(contents); } ////本文地址:http://www.cnblogs.com/Interkey/p/qrcode.html //构造二维码写码器 MultiFormatWriter mutiWriter = new MultiFormatWriter(); Dictionary <EncodeHintType, object> hint = new Dictionary <EncodeHintType, object>(); hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8"); hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //生成二维码 BitMatrix bm = mutiWriter.encode(contents, BarcodeFormat.QR_CODE, width, height, hint); var writerSvg = new ZXing.BarcodeWriterPixelData { Format = ZXing.BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { ErrorCorrection = ErrorCorrectionLevel.H, CharacterSet = "UTF-8", DisableECI = true, Width = width, Height = height, } }; var pixelData = writerSvg.Write(bm); Bitmap bitmap = ConvertToBitmap(pixelData); //BarcodeWriter barcodeWriter = new BarcodeWriter(); //Bitmap bitmap = barcodeWriter.Write(bm); //获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸) int[] rectangle = bm.getEnclosingRectangle(); //计算插入图片的大小和位置 int middleImgW = Math.Min((int)(rectangle[2] / 3.5), middleImg.Width); int middleImgH = Math.Min((int)(rectangle[3] / 3.5), middleImg.Height); int middleImgL = (pixelData.Width - middleImgW) / 2; int middleImgT = (pixelData.Height - middleImgH) / 2; //将img转换成bmp格式,否则后面无法创建 Graphics对象 Bitmap bmpimg = new Bitmap(pixelData.Width, pixelData.Height, System.DrawingCore.Imaging.PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(bmpimg)) { g.InterpolationMode = System.DrawingCore.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.DrawingCore.Drawing2D.SmoothingMode.HighQuality; g.CompositingQuality = System.DrawingCore.Drawing2D.CompositingQuality.HighQuality; g.DrawImage(bitmap, 0, 0); } //在二维码中插入图片 Graphics myGraphic = Graphics.FromImage(bmpimg); //白底 myGraphic.FillRectangle(Brushes.White, middleImgL, middleImgT, middleImgW, middleImgH); myGraphic.DrawImage(middleImg, middleImgL, middleImgT, middleImgW, middleImgH); return(bmpimg); }
public void PrintLabelForQRCode() { int clientid = Convert.ToInt32(cmbBoxClient.SelectedValue); string MRNNo = cmbBoxMRNNO.SelectedValue.ToString(); int OrderId = Convert.ToInt32(cmbPONO.SelectedValue); int Itemid = Convert.ToInt32(cmbItem.SelectedValue); string Itemdesc = txtDescription.Text; int noOfStickers = Convert.ToInt32(txtNoOfStricker.Text); int barcodeCombinationid = 1; //int SelectMRPOrIndustrailuseValue; //int IFMRPIsZero; WMSData ws = new WMSData(); WhsData WMSDs1 = new WhsData(); DataTable dt = new DataTable(); try { // _dal_MrpPrint; // var user = WMSWebSession.GetInstance().User; dt = _dal_MrpPrint.GetPreferenceById(clientid); string labelColumnId = dt.Rows[0][0].ToString(); int[] labelColumnIds1 = new int[10]; int a = 0; foreach (var i in labelColumnId.Split(',')) { labelColumnIds1[a] = Convert.ToInt32(i); a++; } // Get picking strategy of Item int ItemId = Convert.ToInt32(cmbItem.SelectedValue); var PickingStrategy = _dal_MrpPrint.GetPickingStrategyOfItem(ItemId); if (PickingStrategy == 1) { barcodeCombinationid = 3; } else if (PickingStrategy == 2) { barcodeCombinationid = 4; } string barcodeType = barcodeCombinationid == 1 ? "OnlyItemCode" : (barcodeCombinationid == 2 ? "ItemCodeMRNNo" : (barcodeCombinationid == 3 ? "ItemCodePONo" : (barcodeCombinationid == 4 ? "ItemCodeBatchNo" : "ItemCodeSerialNo"))); //DataSet dsmrnItems = new DataSet(); DataTable dtmrnItems = new DataTable(); MrpModel.Client_Id = clientid; MrpModel.MRNNo = MRNNo.ToString(); string itemCode = _dal_MrpPrint.GetItemsCode(Convert.ToInt32(cmbItem.SelectedValue)); MrpModel.itemCode = itemCode.ToString().Trim(); MrpModel.OrderId = OrderId; dtmrnItems = _dal_MrpPrint.GetItemDetailsForLablePrinting(MrpModel); if (dtmrnItems != null && dtmrnItems.Rows.Count > 0) { int fid = 1; for (int i = 0; i < dtmrnItems.Rows.Count; i++) { for (int Noofst = 0; Noofst < noOfStickers; Noofst++) { string directoryPath = string.Format("{0}\\{1}", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Descripancy_Barcode"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } var writer = new ZXing.BarcodeWriter(); writer.Options.PureBarcode = true; writer.Format = BarcodeFormat.CODE_128; string barcodeString = dtmrnItems.Rows[i]["ItemCode"].ToString(); if (barcodeCombinationid == 2) { barcodeString = barcodeString + "_" + MRNNo; } else if (barcodeCombinationid == 3) { barcodeString = barcodeString + "_" + dtmrnItems.Rows[i]["ItemCode"].ToString(); } else if (barcodeCombinationid == 4) { barcodeString = barcodeString + "-" + dtmrnItems.Rows[i]["BatchNo"]; } else if (barcodeCombinationid == 5) { barcodeString = barcodeString + "-" + "NA"; } //QR code string imgPath1 = @"~\Descripancy_Barcode\QR_" + MRNNo + "_" + barcodeString + ".jpg"; // string FilePath = string.Format("{0}\\{1}", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Reports_PDF"); var qrCodeWriter = new ZXing.BarcodeWriterPixelData { Format = ZXing.BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = 100, Width = 100, Margin = 0 } }; var pixelData = qrCodeWriter.Write(barcodeString); using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) { using (var ms = new MemoryStream()) { var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } using (FileStream fs = new FileStream(imgPath1, FileMode.Create, FileAccess.ReadWrite)) { // save to stream as PNG bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); byte[] imgbytes = ms.ToArray(); fs.Write(imgbytes, 0, imgbytes.Length); } } } string path = string.Format("{0}\\{1}", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), imgPath1); path = "File:///" + path; ws.tblLabelBarcode.Rows.Add(path, fid); //MRN Number, PO Number, SO Number, Item Code, Description, Batch Number, Exp. Date, Mfg. Date, MRP, Quantity //if (labelColumnIds.Contains(1)) ws.tblLabelPrinting.Rows.Add("Description", dtmrnItems.Rows[i]["ItemDescription"], fid); //if (labelColumnIds.Contains(2)) ws.tblLabelPrinting.Rows.Add("ItemCode", dtmrnItems.Rows[i]["ClientItemDesc"], fid); if (labelColumnIds1.Contains(2)) { ws.tblLabelPrinting.Rows.Add("PONo", "PO No.: " + dtmrnItems.Rows[i]["PONumber"], fid); } if (labelColumnIds1.Contains(3)) { ws.tblLabelPrinting.Rows.Add("SONo", "SO No.: " + dtmrnItems.Rows[i]["SONumber"], fid); } if (labelColumnIds1.Contains(1)) { ws.tblLabelPrinting.Rows.Add("MRNNo", "MRN No.: " + dtmrnItems.Rows[i]["MRNNo"], fid); } if (labelColumnIds1.Contains(6)) { ws.tblLabelPrinting.Rows.Add("BatchNo", "Batch No.: " + dtmrnItems.Rows[i]["BatchNo"], fid); } if (labelColumnIds1.Contains(11)) { //if (mrnItem.SerialNo != null && qty < mrnItem.SerialNo.Length) // wmsDs.tblLabelPrinting.Rows.Add(@ReportRes.SerialNo, mrnItem.SerialNo[qty], fid); //else // wmsDs.tblLabelPrinting.Rows.Add(@ReportRes.SerialNo, "NA", fid); } if (labelColumnIds1.Contains(7)) { ws.tblLabelPrinting.Rows.Add("ExpDate", "Expiry Date: " + dtmrnItems.Rows[i]["ExpiryDate"], fid); } if (labelColumnIds1.Contains(8)) { ws.tblLabelPrinting.Rows.Add("MfgDate", "Mfg. Date: " + dtmrnItems.Rows[i]["ProductionDate"], fid); } //if ((labelColumnIds.Contains(9) && SelectMRPOrIndustrailuseValue != 2) || SelectMRPOrIndustrailuseValue == 1) // if (mrnItem.MRP == 0) // { // if (IFMRPIsZero == 2) // { // SelectMRPOrIndustrailuseValue = 3; // // wmsDs.tblLabelPrinting.Rows.Add(@ReportRes.MRP, "For Industrail use only", fid); // } // else if (IFMRPIsZero == 3) // { // SelectMRPOrIndustrailuseValue = 4; // // wmsDs.tblLabelPrinting.Rows.Add(@ReportRes.MRP, "Not for Retail Sale", fid); // } // } // else // { // wmsDs.tblLabelPrinting.Rows.Add(@ReportRes.MRP, mrnItem.MRP, fid); // } if (labelColumnIds1.Contains(10)) { ws.tblLabelPrinting.Rows.Add("Quantity", "Unit Qty.: " + dtmrnItems.Rows[i]["UnitQuantity"] + " " + dtmrnItems.Rows[i]["UOM_Name"], fid); } if (Convert.ToDouble(dtmrnItems.Rows[i]["MRP"]) == 0.0) { if (dtmrnItems.Rows[i]["MRPValue"] != null || dtmrnItems.Rows[i]["MRPValue"] != " ") { if (dtmrnItems.Rows[i]["MRPValue"] == "I") { ws.tblLabelPrinting.Rows.Add("MRP", "Industrial", fid); } else if (dtmrnItems.Rows[i]["MRPValue"] == "N") { ws.tblLabelPrinting.Rows.Add("MRP", "Not For sale", fid); } } } else { ws.tblLabelPrinting.Rows.Add("MRP", Convert.ToDouble(dtmrnItems.Rows[i]["MRP"]), fid); } // WMSDs1.tblLabelPrinting1.Rows.Add("ItemCode", "Item No.: " + dtmrnItems.Rows[i]["ItemCode1"], fid); fid = fid + 1; } //} } MRNLabelItem = ws.tblLabelPrinting; // MRNLabelItem1 = WMSDs1.tblLabelPrinting1; } // Variables Warning[] warnings; string[] streamIds; string mimeType = string.Empty; string encoding = string.Empty; string extension = string.Empty; // Setup the report viewer object and get the array of bytes ReportViewer viewer = new ReportViewer(); viewer.ProcessingMode = ProcessingMode.Local; //string reportPath = Server.MapPath(@"~\Reports\rptMRNLabels.rdlc"); string reportPath = "~/Report/rptAltasCopco_QR.rdlc"; viewer.LocalReport.ReportPath = reportPath; ReportDataSource rds = new ReportDataSource("dsWMS", (DataTable)ws.tblLabelBarcode); viewer.LocalReport.DataSources.Clear(); viewer.LocalReport.DataSources.Add(rds); viewer.LocalReport.EnableExternalImages = true; ReportParameter[] param = new ReportParameter[3]; string strPrintString = "ForIndustrialUseOnly"; string CompanyName = ConfigurationManager.AppSettings["CompanyName"]; string Address = ConfigurationManager.AppSettings["Address"]; param[0] = new ReportParameter("CompanyName", CompanyName); param[1] = new ReportParameter("Address", Address); param[2] = new ReportParameter("PrintString", strPrintString); viewer.LocalReport.SetParameters(param); // viewer.LocalReport.Refresh(); // string strPrintString = SelectMRPOrIndustrailuseValue == 3 ? ReportRes.ForIndustrialUseOnly : (SelectMRPOrIndustrailuseValue == 4 ? ReportRes.NotForRetailSale : string.Empty); //param[0] = new ReportParameter("PrintString", strPrintString); //viewer.LocalReport.SetParameters(param); // viewer.LocalReport.Refresh(); //using (System.IO.Stream report = System.IO.File.OpenRead(Server.MapPath(@"~\Reports\rptMRNLabelItems.rdlc"))) string subreportPath = "~/Report/rptAtlasCopcoItems.rdlc"; using (System.IO.Stream report = System.IO.File.OpenRead(subreportPath)) { viewer.LocalReport.LoadSubreportDefinition("rptAtlasCopcoItemsBarcode", report); } viewer.LocalReport.SubreportProcessing += new Microsoft.Reporting.WinForms.SubreportProcessingEventHandler(LocalReportLabel_SubreportProcessing); //using (System.IO.Stream report = System.IO.File.OpenRead("~/Report/rptAtlasCopco_Barcode.rdlc")) //{ // viewer.LocalReport.LoadSubreportDefinition("rptAtlasCopco_Barcode", report); //} //viewer.LocalReport.SubreportProcessing += new Microsoft.Reporting.WinForms.SubreportProcessingEventHandler(LocalReportLabel_SubreportProcessing1); // string deviceInfo = string.Format("<DeviceInfo><PageHeight>{0}</PageHeight><PageWidth>{1}</PageWidth></DeviceInfo>", "7.6cm", "9.0cm"); // viewer.RefreshReport(); byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings); //Server.MapPath("~/App_Data/ // string path1 = "~/Reports_PDF"; string FilePath = string.Format("{0}\\{1}", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Reports_PDF"); if (!Directory.Exists(FilePath)) { Directory.CreateDirectory(FilePath); } string file_name = MRNNo + "_LabelWithQRPrint.pdf"; //save the file in unique name if (System.IO.File.Exists(FilePath + "/" + file_name)) { System.IO.File.Delete(FilePath + "/" + file_name); } //if (System.IO.File.Exists(path1 + "/" + file_name)) // System.IO.File.Delete(path1 + "/" + file_name); //After that use file stream to write from bytes to pdf file on your server path FileStream file = new FileStream(FilePath + "/" + file_name, FileMode.OpenOrCreate, FileAccess.ReadWrite); file.Write(bytes, 0, bytes.Length); file.Dispose(); // string filePath = path1 + "/" + file_name; // Create Copy of SAME pdf ON Local Machine //string sourcePath = FilePath; //string targetPath = @"C:/Reports_PDF"; //// Use Path class to manipulate file and directory paths. //string sourceFile = System.IO.Path.Combine(sourcePath, file_name); //string destFile = System.IO.Path.Combine(targetPath, file_name); //// To copy a folder's contents to a new location: //// Create a new target folder, if necessary. //if (!System.IO.Directory.Exists(targetPath)) //{ // System.IO.Directory.CreateDirectory(targetPath); //} //// To copy a file to another location and //// overwrite the destination file if it already exists. //System.IO.File.Copy(sourceFile, destFile, true); //string NewFilePath = targetPath + "/" + file_name; string AdobeReaderExePath = @"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"; string DirName = AppDomain.CurrentDomain.BaseDirectory; string dir1 = DirName + @"\Reports_PDF\"; string[] dirs = Directory.GetFiles(dir1, "" + "*.*", SearchOption.AllDirectories); foreach (string dir in dirs) { if (File.Exists(dir)) { Process proc = new Process(); proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.StartInfo.Verb = "print"; proc.StartInfo.FileName = AdobeReaderExePath; proc.StartInfo.Arguments = String.Format(@"/p /h {0}", dir); proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; proc.Start(); proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; if (proc.HasExited == false) { proc.WaitForExit(Convert.ToInt32(100000)); } proc.EnableRaisingEvents = true; proc.Close(); KillAdobe("AcroRd32"); File.Delete(dir); } } string message = "Sticker are genrated"; MessageBox.Show(message); viewer.LocalReport.Refresh(); clear(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void MRPPrintQRLabels() { int clientid = Convert.ToInt32(cmbClient.SelectedValue); int Itemid = Convert.ToInt32(cmbItem.SelectedValue); string Itemdesc = txtItemDesc.Text; int noOfStickers = Convert.ToInt32(txtNoOfStrickers.Text); string Itemcode = _dal_MrpPrint.GetItemsCode(Convert.ToInt32(cmbItem.SelectedValue)); int stockKeepingqty = Convert.ToInt32(txtStockQty.Text); string StockkeepingUnit = _MRP_LabelPrint_Dal.GetUOMUnit(Convert.ToInt32(cmbUOM.SelectedValue)); int barcodeCombinationid = 1; string Mrp = txtMrp.Text.ToString(); //int SelectMRPOrIndustrailuseValue; //int IFMRPIsZero; WMSData ws = new WMSData(); WhsData WMSDs1 = new WhsData(); DataTable dt = new DataTable(); try { int fid = 1; for (int Noofst = 0; Noofst < noOfStickers; Noofst++) { string directoryPath = string.Format("{0}\\{1}", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Descripancy_Barcode"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory((directoryPath)); } var writer = new ZXing.BarcodeWriter(); writer.Format = BarcodeFormat.CODE_128; string barcodeString = Itemdesc; string imgPath1 = @"~\Descripancy_Barcode\QR_" + clientid + "_" + Itemcode + ".jpg"; var qrCodeWriter = new ZXing.BarcodeWriterPixelData { Format = ZXing.BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = 100, Width = 100, Margin = 0 } }; var pixelData = qrCodeWriter.Write(barcodeString); using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) { using (var ms = new MemoryStream()) { var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } using (FileStream fs = new FileStream(imgPath1, FileMode.Create, FileAccess.ReadWrite)) { // save to stream as PNG bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); byte[] imgbytes = ms.ToArray(); fs.Write(imgbytes, 0, imgbytes.Length); } } } string path = string.Format("{0}\\{1}", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), imgPath1); path = "File:///" + path; ws.tblLabelBarcode.Rows.Add(path, fid); ws.tblLabelPrinting.Rows.Add("ItemCode", "Item No.: " + Itemcode, fid); string desc = string.IsNullOrEmpty(Itemdesc) ? string.Empty : (Itemdesc.Length > 35 ? Itemdesc.Substring(0, 35) : Itemdesc); ws.tblLabelPrinting.Rows.Add("Description", "Item Name: " + desc, fid); ws.tblLabelPrinting.Rows.Add("Quantity: " + stockKeepingqty + " " + StockkeepingUnit, fid); if (Convert.ToDouble(Mrp) == 0.0 || Convert.ToDouble(Mrp) == 0) { string msg = txtMrp.Text; ws.tblLabelPrinting.Rows.Add("Quantity", msg, fid); } else { ws.tblLabelPrinting.Rows.Add("MRP", "MRP (Rs.): " + Convert.ToDouble(Mrp) * stockKeepingqty + " ( Inclusive of all taxes )", fid); } //if (SelectedMRPString == 1) // if (MRP == 0) // { // if (IfMRPIsZeroValue == 2) // { // SelectedMRPString = 3; // } // else if (IfMRPIsZeroValue == 3) // { // SelectedMRPString = 4; // } // else if (IfMRPIsZeroValue == 1) // { // SelectedMRPString = 2; // } // } // else // { // wmsDs.tblLabelPrinting.Rows.Add(@ReportRes.MRP, "MRP (Rs.): " + MRP * StockKeepingqty + " ( Inclusive of all taxes )", fid); // // wmsDs.tblLabelPrinting.Rows.Add(@ReportRes.MRP, "MRP (" + "" + " ): " + MRP * StockKeepingqty + " ( Inclusive of all taxes )", fid); // } //if (SelectedMRPString == 2) // wmsDs.tblLabelPrinting.Rows.Add(@ReportRes.Quantity, string.Empty, fid); //if (SelectedMRPString == 3) // wmsDs.tblLabelPrinting.Rows.Add(@ReportRes.Quantity, ReportRes.ForIndustrialUseOnly, fid); //if (SelectedMRPString == 4) // wmsDs.tblLabelPrinting.Rows.Add(@ReportRes.Quantity, ReportRes.NotForRetailSale, fid); string currentMonthYear = DateTime.Now.ToString("MMM-yyyy"); ws.tblLabelPrinting.Rows.Add("Quantity", "Month & Year of Packing: " + currentMonthYear, fid); fid = fid + 1; } MRNLabelItem = ws.tblLabelPrinting; // Variables Warning[] warnings; string[] streamIds; string mimeType = string.Empty; string encoding = string.Empty; string extension = string.Empty; // Setup the report viewer object and get the array of bytes ReportViewer viewer = new ReportViewer(); viewer.ProcessingMode = ProcessingMode.Local; string reportPath = "~/Report/rptAltasCopco_QR.rdlc"; viewer.LocalReport.ReportPath = reportPath; ReportDataSource rds = new ReportDataSource("dsWMS", (DataTable)ws.tblLabelBarcode); viewer.LocalReport.DataSources.Clear(); viewer.LocalReport.DataSources.Add(rds); viewer.LocalReport.EnableExternalImages = true; ReportParameter[] param = new ReportParameter[3]; string strPrintString = ""; string CompanyName = ConfigurationManager.AppSettings["CompanyName"]; string Address = ConfigurationManager.AppSettings["Address"]; param[0] = new ReportParameter("CompanyName", CompanyName); param[1] = new ReportParameter("Address", Address); param[2] = new ReportParameter("PrintString", strPrintString); viewer.LocalReport.SetParameters(param); viewer.LocalReport.Refresh(); string subreportPath = "~/Report/rptAtlasCopcoItems.rdlc"; using (System.IO.Stream report = System.IO.File.OpenRead(subreportPath)) { viewer.LocalReport.LoadSubreportDefinition("rptAtlasCopcoItems", report); } viewer.LocalReport.SubreportProcessing += new Microsoft.Reporting.WinForms.SubreportProcessingEventHandler(LocalReportLabel_SubreportProcessing); byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings); string FilePath = string.Format("{0}\\{1}", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Reports_PDF"); if (!Directory.Exists(FilePath)) { Directory.CreateDirectory(FilePath); } // string path1 = Server.MapPath("~/Reports_PDF"); string file_name = Itemcode + "_LabelWithQRPrint.pdf"; if (System.IO.File.Exists(FilePath + "/" + file_name)) { System.IO.File.Delete(FilePath + "/" + file_name); } //After that use file stream to write from bytes to pdf file on your server path FileStream file = new FileStream(FilePath + "/" + file_name, FileMode.OpenOrCreate, FileAccess.ReadWrite); file.Write(bytes, 0, bytes.Length); file.Dispose(); string filePath = FilePath + "/" + file_name; // Create Copy of SAME pdf ON Local Machine string sourcePath = FilePath; string targetPath = @"C:/Reports_PDF"; // Use Path class to manipulate file and directory paths. string sourceFile = System.IO.Path.Combine(sourcePath, file_name); string destFile = System.IO.Path.Combine(targetPath, file_name); // To copy a folder's contents to a new location: // Create a new target folder, if necessary. if (!System.IO.Directory.Exists(targetPath)) { System.IO.Directory.CreateDirectory(targetPath); } // To copy a file to another location and // overwrite the destination file if it already exists. System.IO.File.Copy(sourceFile, destFile, true); string NewFilePath = targetPath + "/" + file_name; string AdobeReaderExePath = @"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"; string DirName = AppDomain.CurrentDomain.BaseDirectory; string dir1 = DirName + @"\Reports_PDF\"; string[] dirs = Directory.GetFiles(dir1, "" + "*.*", SearchOption.AllDirectories); foreach (string dir in dirs) { if (File.Exists(dir)) { Process proc = new Process(); proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.StartInfo.Verb = "print"; proc.StartInfo.FileName = AdobeReaderExePath; proc.StartInfo.Arguments = String.Format(@"/p /h {0}", dir); proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; proc.Start(); proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; if (proc.HasExited == false) { proc.WaitForExit(Convert.ToInt32(10000)); } proc.EnableRaisingEvents = true; proc.Close(); KillAdobe("AcroRd32"); File.Delete(dir); } } string message = "Sticker are genrated"; MessageBox.Show(message); // clear(); viewer.LocalReport.Refresh(); } catch (Exception ex) { // _labelprintingService.SaveLog(ex.Message); MessageBox.Show(ex.Message); } }
public ActionResult Index(string codesStr) { var codes = GetCodes(codesStr); var dt0 = SystemTime.Now; //QrCode 根目录 var qrCodeDir = Path.Combine(CO2NET.Config.RootDictionaryPath, "App_Data", "QrCode"); if (!Directory.Exists(qrCodeDir)) { Directory.CreateDirectory(qrCodeDir); } //定义文件名和路径 var tempId = SystemTime.Now.ToString("yyyy-MM-dd-HHmmss"); //本次生成唯一Id var tempDirName = $"{tempId}_{Guid.NewGuid().ToString("n")}"; //临时文件夹名 var tempZipFileName = $"{tempDirName}.zip"; //临时压缩文件名 var tempZipFileFullPath = Path.Combine(qrCodeDir, tempZipFileName); //临时压缩文件完整路径 var tempDir = Path.Combine(qrCodeDir, tempDirName); Directory.CreateDirectory(tempDir);//创建临时目录 //说明文件 var readmeFile = Path.Combine(qrCodeDir, "readme.txt"); System.IO.File.Copy(readmeFile, Path.Combine(tempDir, "readme.txt")); //便利所有二维码内容 var i = 0; foreach (var code in codes) { if (code.IsNullOrEmpty()) { continue; //过滤为空的段落 } i++; //计数器 var finalCode = code.Length > 100 ? code.Substring(0, 100) : code;//约束长度 //二维码生成开始 BitMatrix bitMatrix;//定义像素矩阵对象 bitMatrix = new MultiFormatWriter().encode(finalCode, BarcodeFormat.QR_CODE /*条码或二维码标准*/, 600 /*宽度*/, 600 /*高度*/); var bw = new ZXing.BarcodeWriterPixelData(); var pixelData = bw.Write(bitMatrix); var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);//预绘制32bit标准的位图片 var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height) /*绘制矩形区域及偏移量*/, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { //假设位图的 row stride = 4 字节 * 图片的宽度 System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData);//从内存 Unlock bitmap 对象 } //二维码生成结束 var fileName = Path.Combine(tempDir, $"{i}.jpg");//二维码文件名 //保存二维码 var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite); { bitmap.Save(fileStream, System.Drawing.Imaging.ImageFormat.Png); fileStream.Close();//一定要关闭文件流 } } SenparcTrace.SendCustomLog("二维码生成结束", $"耗时:{SystemTime.DiffTotalMS(dt0)} ms,临时文件:{tempZipFileFullPath}");//记录日志 var dt1 = SystemTime.Now; while (Directory.GetFiles(tempDir).Length < i + 1 /* readme.txt */ && SystemTime.NowDiff(dt1) < TimeSpan.FromSeconds(30) /*最多等待时间*/) { Thread.Sleep(1000);//重试等待时间 } ZipFile.CreateFromDirectory(tempDir, tempZipFileFullPath, CompressionLevel.Fastest, false);//创建压缩文件 var dt2 = SystemTime.Now; while (SystemTime.NowDiff(dt2) < TimeSpan.FromSeconds(10) /*最多等待时间*/) { FileStream fs = null; try { fs = new FileStream(tempZipFileFullPath, FileMode.Open, FileAccess.Read, FileShare.None); } catch { Thread.Sleep(500); continue; } if (fs != null) { return(File(fs, "application/x-zip-compressed", $"SenparcQrCode_{tempId}.zip")); //TODO:删除临时文件 } } return(Content("打包文件失败!")); }
public ActionResult Index(string codesStr) { var codes = codesStr.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); var i = 0; //限制个数 if (codes.Length > 200) { codes = codes.Take(100).ToArray(); } var qrCodeDir = Path.Combine(CO2NET.Config.RootDictionaryPath, "App_Data", "QrCode"); if (!Directory.Exists(qrCodeDir)) { Directory.CreateDirectory(qrCodeDir); } //定义文件名和路径 var tempId = SystemTime.Now.ToString("yyyy-MM-dd-HHmmss"); var tempDirName = $"{tempId}_{Guid.NewGuid().ToString("n")}"; var tempZipFileName = $"{tempDirName}.zip"; var tempZipFileFullPath = Path.Combine(qrCodeDir, tempZipFileName); var tempDir = Path.Combine(qrCodeDir, tempDirName); Directory.CreateDirectory(tempDir);//创建临时目录 var readmeFile = Path.Combine(qrCodeDir, "readme.txt"); System.IO.File.Copy(readmeFile, Path.Combine(tempDir, "readme.txt")); //便利所有二维码内容 foreach (var code in codes) { if (code.IsNullOrEmpty()) { continue; } i++; var finalCode = code.Length > 100 ? code.Substring(0, 100) : code;//约束长度 BitMatrix bitMatrix; bitMatrix = new MultiFormatWriter().encode(finalCode, BarcodeFormat.QR_CODE, 600, 600); var bw = new ZXing.BarcodeWriterPixelData(); var pixelData = bw.Write(bitMatrix); var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb); var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } var fileName = Path.Combine(tempDir, $"{i}.jpg"); var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite); { bitmap.Save(fileStream, System.Drawing.Imaging.ImageFormat.Png); fileStream.Close(); } } SenparcTrace.SendCustomLog("二维码生成结束", tempZipFileFullPath); var dt1 = SystemTime.Now; while (Directory.GetFiles(tempDir).Length < i + 1 /* readme.txt */ && SystemTime.NowDiff(dt1) < TimeSpan.FromSeconds(30) /*最多等待时间*/) { Thread.Sleep(1000); } ZipFile.CreateFromDirectory(tempDir, tempZipFileFullPath, CompressionLevel.Fastest, false); var dt2 = SystemTime.Now; while (SystemTime.NowDiff(dt2) < TimeSpan.FromSeconds(10) /*最多等待时间*/) { FileStream fs = null; try { fs = new FileStream(tempZipFileFullPath, FileMode.Open, FileAccess.Read, FileShare.None); } catch { Thread.Sleep(500); continue; } if (fs != null) { return(File(fs /*$"~/App_Data/QrCode/{tempZipFileName}"*/ /*tempZipFileFullPath*/, "application/x-zip-compressed", $"SenparcQrCode_{tempId}.zip")); } } return(Content("打包文件失败!")); }