/// <summary> /// Create QR Code image /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Event arguments</param> private void OnEncode(object sender, EventArgs e) { // get error correction code ErrorCorrection ErrorCorrection = (ErrorCorrection)ErrorCorrectionComboBox.SelectedIndex; // get data for QR Code string Data = DataTextBox.Text.Trim(); if (Data.Length == 0) { MessageBox.Show("Data must not be empty."); return; } // save state ProgramState.State.EncodeErrorCorrection = ErrorCorrection; ProgramState.State.EncodeData = Data; ProgramState.SaveState(); // disable buttons EnableButtons(false); try { // multi segment if (SeparatorCheckBox.Checked && Data.IndexOf('|') >= 0) { string[] Segments = Data.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); // encode data QRCodeEncoder.Encode(ErrorCorrection, Segments); } // single segment else { // encode data QRCodeEncoder.Encode(ErrorCorrection, Data); } // create bitmap QRCodeImage = QRCodeToBitmap.CreateBitmap(QRCodeEncoder, 4, 8); } catch (Exception Ex) { MessageBox.Show("Encoding exception.\r\n" + Ex.Message); } // enable buttons EnableButtons(true); // repaint panel Invalidate(); return; }
public Image Encode ( string Code ) { QREncoder Encoder = new QREncoder(); Encoder.Encode( ErrorCorrection.H, Code ); Image image = QRCodeToBitmap.CreateBitmap( Encoder, 4, 8 ); return image; }
/// <summary> /// Could return bigger bitmap /// </summary> /// <param name="sAddress"></param> /// <param name="iSize"></param> /// <returns></returns> private static Bitmap CreateQRCode(string sAddress, int iSize) { // Adding new QRCode encoding system int iMinimumSize = 33; iSize = Math.Max(iSize, iMinimumSize); QREncoder enc = new QREncoder(); enc.ErrorCorrection = ErrorCorrection.H; // this leads to a 33 x 33 qrcode enc.ModuleSize = 1; enc.QuietZone = 4; int iModuleSize = Math.Max(1, (int)Math.Ceiling((double)iSize / (double)iMinimumSize)); enc.QuietZone = 4 * iModuleSize; enc.ModuleSize = iModuleSize; enc.Encode(sAddress); return(enc.CreateQRCodeBitmap()); }
/// <summary> /// Calls the my Azure API to shorten the long URL into an adddress like shl.pw/2v and returns QR Code image of the shortened URL /// </summary> /// <param name="sLongURL">URL to shorten and generate image of</param> /// <param name="iSize">Size of image to generate with ZXing</param> /// <param name="iCropBorder">Sometimes too much white space around QR Code and needs cropping</param> /// <returns>The (optionally cropped) QRCode Image of the shortened URL from ZXing</returns> public static QREncoder GetQREncoderObject(string sLongURL) { string url = "https://pwqrazurefunctionapp.azurewebsites.net/api/ShortenURLPost?code=bxwoszCCCjEGB2KTqiw/tcNCoNCKMdu9jdcbB2xiXcUoxPhMHWRTDA=="; try { // build WSG file link var linkToShorten = new ShortenThisURLWithAzure { Input = sLongURL }; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url); HttpClient connectClient = new HttpClient(); connectClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var body = JSONHelper.SerializeJSon <ShortenThisURLWithAzure>(linkToShorten); request.Content = new StringContent(body, Encoding.UTF8, "application/json"); var response = connectClient.SendAsync(request).Result; string responseContent = response.Content.ReadAsStringAsync().Result; BPSUtilities.WriteLog(responseContent); // this is dumb ShortenedURLResponseFromAzure shortUrl = JSONHelper.DeserializeJSon <ShortenedURLResponseFromAzure>(responseContent.Replace("[", "").Replace("]", "")); if (shortUrl != null) { if (!string.IsNullOrEmpty(shortUrl.ShortUrl)) { BPSUtilities.WriteLog($"'{shortUrl.LongUrl}' shortened to '{shortUrl.ShortUrl}'"); QREncoder enc = new QREncoder(); enc.ErrorCorrection = ErrorCorrection.H; // this leads to a 33 x 33 qrcode enc.ModuleSize = 1; enc.QuietZone = 4; enc.Encode(shortUrl.ShortUrl); return(enc); } } else { BPSUtilities.WriteLog("Short URL not generated."); } } catch (Exception ex) { BPSUtilities.WriteLog("Error: " + ex.Message); BPSUtilities.WriteLog(ex.StackTrace); } return(null); }
public override Image Encode(Store Code) { string json = JsonConvert.SerializeObject(new JsonFormat(Code)); QREncoder Encoder = new QREncoder(); Encoder.Encode(ErrorCorrection.H, json); Image image = QRCodeToBitmap.CreateBitmap(Encoder, 4, 8); return(image); }
private void button1_Click(object sender, EventArgs e) { Image logo = null; if (label1.Text.Length > 0) { try { logo = Image.FromFile(label1.Text); } catch { } } QREncoder encoder = new QREncoder(logo, textBox1.Text); pictureBox1.Image = encoder.Encode(); }
public void CreateQR(Store store) { string path = Utils.GetStoresPath() + store.storeName + ".png"; string json = JsonConvert.SerializeObject(store); QRStore qrStore = new QRStore(store.idStore, store.storeName); qrStore.products = ConvertStoreProductListToProductList(store.products); _QRencoder.Encode(ErrorCorrection.H, json); Bitmap QRStore = QRCodeToBitmap.CreateBitmap(_QRencoder, 4, 8); FileStream FS = new FileStream(path, FileMode.Create); QRStore.Save(FS, ImageFormat.Png); FS.Close(); Logger.Log(String.Format("Image succesfully created for store: {0}", qrStore.storeName)); }
//////////////////////////////////////////////////////////////////// // Draw Barcode //////////////////////////////////////////////////////////////////// private void DrawBarcode() { // save graphics state Contents.SaveGraphicsState(); // draw EAN13 barcode BarcodeEAN13 Barcode1 = new BarcodeEAN13("1234567890128"); Contents.DrawBarcode(1.3, 7.05, 0.012, 0.75, Barcode1, ArialNormal, 8.0); // create QRCode barcode QREncoder QREncoder = new QREncoder(); // set error correction code QREncoder.ErrorCorrection = ErrorCorrection.M; // set module size in pixels QREncoder.ModuleSize = 1; // set quiet zone in pixels QREncoder.QuietZone = 4; // encode your text or byte array QREncoder.Encode(ArticleLink); // convert QRCode to black and white image PdfImage BarcodeImage = new PdfImage(Document); BarcodeImage.LoadImage(QREncoder); // draw image (height is the same as width for QRCode) Contents.DrawImage(BarcodeImage, 6.0, 6.8, 1.2); // define a web link area coinsiding with the qr code Page.AddWebLink(6.0, 6.8, 7.2, 8.0, ArticleLink); // restore graphics sate Contents.RestoreGraphicsState(); return; }
private void OnEncode(object sender, EventArgs e) { // get error correction code ErrorCorrection ErrorCorrection = (ErrorCorrection)ErrorCorrectionComboBox.SelectedIndex; // get module size string ModuleStr = ModuleSizeTextBox.Text.Trim(); if (!int.TryParse(ModuleStr, out int ModuleSize) || ModuleSize < 1 || ModuleSize > 100) { MessageBox.Show("Module size error."); return; } // get quiet zone string QuietStr = QuietZoneTextBox.Text.Trim(); if (!int.TryParse(QuietStr, out int QuietZone) || QuietZone < 1 || QuietZone > 100) { MessageBox.Show("Quiet zone error."); return; } // get data for QR Code string Data = DataTextBox.Text.Trim(); if (Data.Length == 0) { MessageBox.Show("Data must not be empty."); return; } // disable buttons EnableButtons(false); try { QRCodeEncoder.ErrorCorrection = ErrorCorrection; QRCodeEncoder.ModuleSize = ModuleSize; QRCodeEncoder.QuietZone = QuietZone; // multi segment if (SeparatorCheckBox.Checked && Data.IndexOf('|') >= 0) { string[] Segments = Data.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); // encode data QRCodeEncoder.Encode(Segments); } // single segment else { // encode data QRCodeEncoder.Encode(Data); } // create bitmap QRCodeImage = QRCodeEncoder.CreateQRCodeBitmap(); } catch (Exception Ex) { MessageBox.Show("Encoding exception.\r\n" + Ex.Message); } // enable buttons EnableButtons(true); // repaint panel Invalidate(); return; }
public void Test ( bool Debug, string InputFileName ) { // create document using (Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch, InputFileName)) { // set document page mode to open the layers panel Document.InitialDocDisplay = InitialDocDisplay.UseLayers; // define font ArialFont = PdfFont.CreatePdfFont(Document, "Arial", FontStyle.Bold); // open layer control object (in PDF terms optional content object) PdfLayers Layers = new PdfLayers(Document, "PDF layers group"); // set layer panel to incluse all layers including ones that are not visible Layers.ListMode = ListMode.AllPages; // Add new page PdfPage Page = new PdfPage(Document); // Add contents to page PdfContents Contents = new PdfContents(Page); // heading Contents.DrawText(ArialFont, 24, 4.25, 10, TextJustify.Center, "PDF File Writer Layer Test/Demo"); // define layers PdfLayer DrawingTest = new PdfLayer(Layers, "Drawing Test"); PdfLayer Rectangle = new PdfLayer(Layers, "Rectangle"); PdfLayer HorLines = new PdfLayer(Layers, "Horizontal Lines"); PdfLayer VertLines = new PdfLayer(Layers, "Vertical Lines"); PdfLayer QRCodeLayer = new PdfLayer(Layers, "QRCode barcode"); PdfLayer Pdf417Layer = new PdfLayer(Layers, "PDF417 barcode"); PdfLayer NoBarcodeLayer = new PdfLayer(Layers, "No barcode"); // combine three layers into one group of radio buttons QRCodeLayer.RadioButton = "Barcode"; Pdf417Layer.RadioButton = "Barcode"; NoBarcodeLayer.RadioButton = "Barcode"; // set the order of layers in the layer pane Layers.DisplayOrder(DrawingTest); Layers.DisplayOrder(Rectangle); Layers.DisplayOrder(HorLines); Layers.DisplayOrder(VertLines); Layers.DisplayOrderStartGroup("Barcode group"); Layers.DisplayOrder(QRCodeLayer); Layers.DisplayOrder(Pdf417Layer); Layers.DisplayOrder(NoBarcodeLayer); Layers.DisplayOrderEndGroup(); // start a group layer Contents.LayerStart(DrawingTest); // sticky note annotation PdfAnnotation StickyNote = Page.AddStickyNote(2.0, 9.0, "My sticky note", StickyNoteIcon.Note); StickyNote.LayerControl = DrawingTest; // draw a single layer Contents.LayerStart(Rectangle); Contents.DrawText(ArialFont, 14, 1.0, 8.0, TextJustify.Left, "Draw rectangle"); Contents.LayerEnd(); // draw a single layer Contents.LayerStart(HorLines); Contents.DrawText(ArialFont, 14, 1.0, 7.5, TextJustify.Left, "Draw horizontal lines"); Contents.LayerEnd(); // draw a single layer Contents.LayerStart(VertLines); Contents.DrawText(ArialFont, 14, 1.0, 7.0, TextJustify.Left, "Draw vertical lines"); Contents.LayerEnd(); double Left = 4.0; double Right = 7.0; double Top = 9.0; double Bottom = 6.0; // draw a single layer Contents.LayerStart(Rectangle); Contents.SaveGraphicsState(); Contents.SetLineWidth(0.1); Contents.SetColorStroking(Color.Black); Contents.SetColorNonStroking(Color.LightBlue); Contents.DrawRectangle(Left, Bottom, 3.0, 3.0, PaintOp.CloseFillStroke); Contents.RestoreGraphicsState(); Contents.LayerEnd(); // save graphics state Contents.SaveGraphicsState(); // draw a single layer Contents.SetLineWidth(0.02); Contents.LayerStart(HorLines); for (int Row = 1; Row < 6; Row++) { Contents.DrawLine(Left, Bottom + 0.5 * Row, Right, Bottom + 0.5 * Row); } Contents.LayerEnd(); // draw a single layer Contents.LayerStart(VertLines); for (int Col = 1; Col < 6; Col++) { Contents.DrawLine(Left + 0.5 * Col, Bottom, Left + 0.5 * Col, Top); } Contents.LayerEnd(); // restore graphics state Contents.RestoreGraphicsState(); // terminate a group of layers Contents.LayerEnd(); // define QRCode barcode QREncoder QREncoder = new QREncoder(); QREncoder.ErrorCorrection = ErrorCorrection.M; QREncoder.Encode(QRCodeArticle); PdfImage QRImage = new PdfImage(Document); QRImage.LoadImage(QREncoder); // define PDF417 barcode Pdf417Encoder Pdf417Encoder = new Pdf417Encoder(); Pdf417Encoder.ErrorCorrection = ErrorCorrectionLevel.AutoMedium; Pdf417Encoder.Encode(Pdf417Article); PdfImage Pdf417Image = new PdfImage(Document); Pdf417Image.LoadImage(Pdf417Encoder); // draw a single layer Contents.LayerStart(QRCodeLayer); Contents.DrawText(ArialFont, 14, 1.0, 2.5, TextJustify.Left, "QRCode Barcode"); Contents.DrawImage(QRImage, 3.7, 2.5 - 1.75, 3.5); Contents.LayerEnd(); // draw a single layer Contents.LayerStart(Pdf417Layer); Contents.DrawText(ArialFont, 14, 1.0, 2.5, TextJustify.Left, "PDF417 Barcode"); Contents.DrawImage(Pdf417Image, 3.7, 2.5 - 1.75 * Pdf417Encoder.ImageHeight / Pdf417Encoder.ImageWidth, 3.5); Contents.LayerEnd(); // draw a single layer Contents.LayerStart(NoBarcodeLayer); Contents.DrawText(ArialFont, 14, 1.0, 3.0, TextJustify.Left, "Display no barcode"); Contents.LayerEnd(); // create pdf file Document.CreateFile(); // start default PDF reader and display the file Process Proc = new Process(); Proc.StartInfo = new ProcessStartInfo(InputFileName); Proc.Start(); } return; }
//////////////////////////////////////////////////////////////////// // Create table example //////////////////////////////////////////////////////////////////// public void CreateBookList() { // Add new page Page = new PdfPage(Document); // Add contents to page Contents = new PdfContents(Page); PdfFont TitleFont = PdfFont.CreatePdfFont(Document, "Verdana", FontStyle.Bold); PdfFont AuthorFont = PdfFont.CreatePdfFont(Document, "Verdana", FontStyle.Italic); // create stock table PdfTable BookList = new PdfTable(Page, Contents, NormalFont, 9.0); // divide columns width in proportion to following values BookList.SetColumnWidth(1.0, 2.5, 1.2, 1.0, 0.5, 0.6, 1.2); // event handlers BookList.TableStartEvent += BookListTableStart; BookList.TableEndEvent += BookListTableEnd; BookList.CustomDrawCellEvent += BookListDrawCellEvent; // set display header at the top of each additional page BookList.HeaderOnEachPage = true; // make some changes to default header style BookList.DefaultHeaderStyle.Alignment = ContentAlignment.MiddleCenter; BookList.DefaultHeaderStyle.FontSize = 9.0; BookList.DefaultHeaderStyle.MultiLineText = true; BookList.DefaultHeaderStyle.TextBoxTextJustify = TextBoxJustify.Center; BookList.DefaultHeaderStyle.BackgroundColor = Color.Blue; BookList.DefaultHeaderStyle.ForegroundColor = Color.LightCyan; BookList.DefaultHeaderStyle.TextBoxLineBreakFactor = 0.2; // headers BookList.Header[0].Value = "Book Cover"; BookList.Header[1].Value = "Book Title and Authors"; BookList.Header[2].Value = "Date\nPublished"; BookList.Header[3].Value = "Type"; BookList.Header[4].Value = "In\nStock"; BookList.Header[5].Value = "Price"; BookList.Header[6].Value = "Weblink"; // default cell style BookList.DefaultCellStyle.Alignment = ContentAlignment.MiddleCenter; // create private style for type column BookList.Cell[3].Style = BookList.CellStyle; BookList.Cell[3].Style.RaiseCustomDrawCellEvent = true; // create private style for in stock column BookList.Cell[4].Style = BookList.CellStyle; BookList.Cell[4].Style.Format = "#,##0"; BookList.Cell[4].Style.Alignment = ContentAlignment.MiddleRight; // create private style for price column BookList.Cell[5].Style = BookList.CellStyle; BookList.Cell[5].Style.Format = "#,##0.00"; BookList.Cell[5].Style.Alignment = ContentAlignment.MiddleRight; // book list text file StreamReader Reader = new StreamReader("BookList.txt"); // loop for records for (;;) { // read one line string TextLine = Reader.ReadLine(); if (TextLine == null) { break; } // split to fields (must be 8 fields) string[] Fld = TextLine.Split(new char[] { '\t' }); if (Fld.Length != 8) { continue; } // book cover PdfImage Cell0Image = new PdfImage(Document); Cell0Image.LoadImage(Fld[6]); BookList.Cell[0].Value = Cell0Image; // note create text box set Value field TextBox Box = BookList.Cell[1].CreateTextBox(); Box.AddText(TitleFont, 10.0, Color.DarkBlue, Fld[0]); Box.AddText(NormalFont, 8.0, Color.Black, ", Author(s): "); Box.AddText(AuthorFont, 9.0, Color.DarkRed, Fld[2]); // date, type in-stock and price BookList.Cell[2].Value = Fld[1]; BookList.Cell[3].Value = Fld[3]; BookList.Cell[4].Value = int.Parse(Fld[5]); BookList.Cell[5].Value = double.Parse(Fld[4], NFI.PeriodDecSep); // QRCode and web link QREncoder Encoder = new QREncoder(); Encoder.ErrorCorrection = ErrorCorrection.M; Encoder.Encode(Fld[7]); PdfImage QRImage = new PdfImage(Document); QRImage.LoadImage(Encoder); BookList.Cell[6].Value = QRImage; BookList.Cell[6].WebLink = Fld[7]; // draw it BookList.DrawRow(); } // close book list BookList.Close(); // exit return; }
/// <summary> /// Command line encode /// </summary> /// <param name="Args">Arguments array</param> public static void Encode ( string[] Args ) { // help if (Args == null || Args.Length < 2) { throw new ArgumentException("help"); } bool TextFile = false; string InputFileName = null; string OutputFileName = null; string Code; string Value; QREncoder Encoder = new QREncoder(); for (int ArgPtr = 0; ArgPtr < Args.Length; ArgPtr++) { string Arg = Args[ArgPtr]; // file name if (Arg[0] != '/' && Arg[0] != '-') { if (InputFileName == null) { InputFileName = Arg; continue; } if (OutputFileName == null) { OutputFileName = Arg; continue; } throw new ArgumentException(string.Format("Invalid option. Argument={0}", ArgPtr + 1)); } // search for colon int Ptr = Arg.IndexOf(':'); if (Ptr < 0) { Ptr = Arg.IndexOf('='); } if (Ptr > 0) { Code = Arg.Substring(1, Ptr - 1); Value = Arg.Substring(Ptr + 1); } else { Code = Arg.Substring(1); Value = string.Empty; } Code = Code.ToLower(); Value = Value.ToLower(); switch (Code) { case "error": case "e": ErrorCorrection EC; switch (Value) { case "low": case "l": EC = ErrorCorrection.L; break; case "medium": case "m": EC = ErrorCorrection.M; break; case "quarter": case "q": EC = ErrorCorrection.Q; break; case "high": case "h": EC = ErrorCorrection.H; break; default: throw new ArgumentException("Error correction option in error"); } Encoder.ErrorCorrection = EC; break; case "module": case "m": if (!int.TryParse(Value, out int ModuleSize)) { ModuleSize = -1; } Encoder.ModuleSize = ModuleSize; break; case "quiet": case "q": if (!int.TryParse(Value, out int QuietZone)) { QuietZone = -1; } Encoder.QuietZone = QuietZone; break; case "text": case "t": TextFile = true; break; default: throw new ApplicationException(string.Format("Invalid argument no {0}, code {1}", ArgPtr + 1, Code)); } } if (TextFile) { string InputText = File.ReadAllText(InputFileName); Encoder.Encode(InputText); } else { byte[] InputBytes = File.ReadAllBytes(InputFileName); Encoder.Encode(InputBytes); } Encoder.SaveQRCodeToPngFile(OutputFileName); return; }