IronBarCode stream only - c#

I want to create an QrCode using IronBarCode, and then save it as a Stream or Byte[].
However both methods expect the file to be saved prior to creation:
var absolute = Request.Scheme + "://" + Request.Host + url;
var qrcode = IronBarCode.QRCodeWriter.CreateQrCode(absolute);
qrcode.AddAnnotationTextAboveBarcode(device.Name);
qrcode.AddBarcodeValueTextBelowBarcode(absolute);
var f = qrcode.ToJpegStream();
var y = qrcode.ToJpegBinaryData();
ToJpegStream() and ToJpegBinaryData expects the absolute string to be an actual file path. I want to create a QrCode and save it as a Byte[] or Stream, however the error thrown is "The filename, directory name, or volume label syntax is incorrect."

AddBarcodeValueTextBelowBarcode method parameter for string is FontPath. That is why it was trying to find the font file that does not exist.
string absolute = "https://ironsoftware.com/";
string Name = "Product URL:";
//Add Annotation(text) below the generated barcode
var qrcode = QRCodeWriter.CreateQrCode(absolute);
qrcode.AddAnnotationTextBelowBarcode(Name);
qrcode.ToJpegBinaryData();
//Add Barcode value below the generated barcode
var qrcode = QRCodeWriter.CreateQrCode(absolute);
qrcode.AddBarcodeValueTextBelowBarcode();
qrcode.ToJpegBinaryData();
The below image is FontPath. FontPath is actually the directory path that actually lead to the Font file.
//This will add Barcode value into QRCode
.AddBarcodeValueTextBelowBarcode()
If you want to add absolute path to the QRCode you should use
//This will add your text to Barcode
.AddAnnotationTextBelowBarcode(absolute)
For more information on how to use the method please refer to the API reference:
https://ironsoftware.com/csharp/barcode/object-reference/api/IronBarCode.GeneratedBarcode.html#IronBarCode_GeneratedBarcode_AddBarcodeValueTextBelowBarcode

The issue mentioned isn't reproducible with the code provided. The code below is adapted from your code and the from the example. It's been tested.
Create a new Windows Forms App (.NET Framework)
Download/install NuGet package: Barcode
Add a Button to Form1 (name: btnCreateQRCode)
Add a PictureBox to Form1 (name: pictureBox1)
Add using directives:
using IronBarCode;
using System.IO;
Form1.cs:
public partial class Form1 : Form
{
private byte[] _qrCode = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private byte[] CreateBarCode(string url, string annotationText)
{
//create new instance
GeneratedBarcode qrCode = QRCodeWriter.CreateQrCode(url);
qrCode.AddAnnotationTextAboveBarcode(annotationText);
qrCode.AddBarcodeValueTextBelowBarcode(url);
byte[] qrCodeBytes = qrCode.ToJpegBinaryData();
return qrCodeBytes;
}
private void btnCreateQRCode_Click(object sender, EventArgs e)
{
_qrCode = CreateBarCode("https://www.google.com/search?q=how+to+search", "How To Search");
using (MemoryStream ms = new MemoryStream(_qrCode))
{
pictureBox1.Image = Image.FromStream(ms);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; //fit to size
pictureBox1.Refresh();
}
}
}
Resources:
Create QR Code

Related

Overwrite/Update the existing image file in the folder

I'm using a webcam to capture an image and place it to picturebox and save the image to my project folder and get the image path then save to sql database. The problem is i do not know how i gonna update/overwrite the existing file
NOTE: My data is bind in datagridview when i click the cell the image will be retrieved on another form, so basically it based on the ID.
Here's what i've tried to achieve that
private void BtnOk_Click(object sender, EventArgs e)
{
if (picCapturedImage.Image != null)
{
using (var bitmap = new Bitmap(picCapturedImage.Image))
{
bitmap.Save(Common.CustomerPath, ImageFormat.Png);
_updCustomer.picCustomerImage.Image = Image.FromFile(Common.CustomerPath);
}
}
Close();
}
When i run this code it replace the image of User.Png not the capture image(Image1, Image2, etc)
User.Png is my default image when user doesn't want to browse or capture an image
Here's the code for saving the image in the project folder
I used loop to avoid overwriting the image in the project folder, so when i saved the image
Image0, Image1, Image2, etc
if (picCapturedImage.Image != null) {
using (var bitmap = new Bitmap(picCapturedImage.Image))
{
for (int i = 0; i < int.MaxValue; i++)
{
var fileName = $#"..\..\Resources\Photos\Image{i}.png";
if (!File.Exists(fileName)) {
bitmap.Save(fileName, ImageFormat.Png);
Common.CustomerPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $#"..\..\Resources\Photos\Image{i}.png"));
_regCustomer.picCustomerImage.Image = Image.FromFile(Common.CustomerPath);
break;
}
}
}
}
Close();
Here's the code where i save the path
public class Common
{
public static string CustomerPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"..\..\Resources", "User.png"));
}
Here's the code for retrieving the image path
_updCustomer.picCustomerImage.Image = Image.FromFile(customer.ImagePath);

MigraDoc: Rendering the same document twice

I want to render a "Document"-object twice, but on the second generation the PDF-File shows an error:
Error on this page. Maybe this page couldn't appear correctly. Please talk to the document-creator.
Sorry, it is german...
This is my example-code:
using System;
using System.Windows.Forms;
using MigraDoc.Rendering;
using MigraDoc.DocumentObjectModel;
using PdfSharp.Pdf;
using System.Diagnostics;
namespace Temp
{
public partial class Form1 : Form
{
Document document; //using the same document- and renderer-object ..
PdfDocumentRenderer renderer; //..creates the error
public Form1()
{
InitializeComponent();
document = new Document();
renderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always);
}
private void button1_Click(object sender, EventArgs e)
{
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();
paragraph.AddFormattedText("Hello World", TextFormat.Bold);
SaveFile(renderer);
}
private void SaveFile(PdfDocumentRenderer renderer)
{
renderer.Document = document;
renderer.RenderDocument();
string pdfFilename = string.Format("Rekla-{0:dd.MM.yyyy_hh-mm-ss}.pdf", DateTime.Now);
renderer.PdfDocument.Save(pdfFilename);
Process.Start(pdfFilename);
}
}
}
Of course i could always create a new "Document"-object:
private void button1_Click(object sender, EventArgs e)
{
Document document = new Document(); //Creating a new document-object solves the problem..
PdfDocumentRenderer renderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always);
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();
paragraph.AddFormattedText("Hi", TextFormat.Bold);
SaveFile(renderer, document);
}
This works. But i need to change the current document while performing other button-click-events. The second code-snippet doesn't solve this task.
Does someone know how to fix the first code-snippet?
Do not re-use the Renderer. Create a new Renderer in the SaveFile method and everything should be fine.
If a new Renderer is not enough, call document.Clone() and assign that to the Renderer.
A method I have found very useful for repeatedly saving a Migradoc pdf to a file is to save the document to a MemoryStream/byte array when I render it. Then when I need to save the pdf file, I just save the byte array.
Put this part in your constructor where you want to render the document:
// First we render our document and save it to a byte array
bytes[] documentBytes;
Document doc;
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
PdfDocumentRenderer pdfRender = new PdfDocumentRenderer();
pdfRender.Document = doc;
pdfRender.RenderDocument();
pdfRender.Save(ms, false);
documentBytes = ms.ToArray();
}
Put this part in your button event where you want to save to a file:
// Then we save the byte array to a file when needed
string filename;
using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create))
{
fs.Write(documentBytes, 0, documentBytes.Length);
}

hardcoded to relative paths

I'm working on a project that on the click of a button a random image for a folder I specified will appear in a specific picturebox.
Here's what I have already:
namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
Random r = new Random();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(r.Next(3).ToString() + ".jpg");
}
}
Now how can i add a relative path to this? My hardcoded path is c:/users/ben/documents/visualstudio/projects/projectnet/resources/pictures.
Thanks in advance!
You could try this in your button1_Click handler:
string imageFileName = r.Next(3).ToString() + ".jpg";
string basePath = #"c:\users\ben\documents\visualstudio\projects\projectnet\resources\pictures";
pictureBox1.Image = Image.FromFile(Path.Combine(basePath, imageFileName);
As mentioned in the comments to your question it is a good idea to read your base directory from an external source, i.e. app.config, if you intend to run your application on a computer other than your own.

In C# winforms using telerik assembly references how to export radGridView to pdf ( Im not using MCV or WPF, implementing in normal winforms)

using Telerik.WinControls.Data;
using Telerik.WinControls.UI.Export;
namespace Directory
{
public partial class radForm : Form
{
public radForm()
{
InitializeComponent();
}
private void radForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'directoryDataSet.DirDetails' table. You can move, or remove it, as needed.
this.dirDetailsTableAdapter.Fill(this.directoryDataSet.DirDetails);
}
// Button click
private void button1_Click(object sender, EventArgs e)
{
ExportToPDF exporter = new ExportToPDF(this.radGridView1);
//The FileExtension property allows you to change the default (*.pdf) file extension of the exported file
exporter.FileExtension = "pdf";
exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;
// This to make the grid fits to the PDF page width
exporter.FitToPageWidth = true;
// Exporting data to PDF is done through the RunExport method of ExportToPDF object
string fileName = "c:\\Directory-information.pdf";
exporter.RunExport(fileName);
}
}
}
Some how Im missing something here and my gridview isn't exporting into pdf and no file creation takes place.
private void button1_Click(object sender, EventArgs e)
{
ExportToPDF exporter = new ExportToPDF(this.radGridView1);
exporter.FileExtension = "pdf";
exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;
exporter.ExportVisualSettings = true;
exporter.PageTitle = "Directory Details";
exporter.FitToPageWidth = true;
string fileName = "c:\\Directory-information.pdf";
exporter.RunExport(fileName);
MessageBox.Show("Pdf file created , you can find the file c:\\Directory-informations.pdf");
}

How can I show an image in webBrowser control directly from memory?

How can I show an image in webBrowser control directly from memory instead of hard disk?
When I use RAM Disk software to create a virtual drive, it is possible to address an image source to load it like this:
img src = "Z:/image.jpg" that Z is a RAM Disk drive. Is it possible to do that in .NET programmaticly? or use MemoryStream to do that?
I would really appreciate some suggestions about this.
You can encode the image in base64. For example
<img src="data:image/gif;base64,MyImageDataEncodedInBase64=" alt="My Image data in base 64" />
Here is a full example of how you can accomplish this:
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ImageEncodedInBase64InAWebBrowser
{
[ComVisible(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string url = Directory.GetCurrentDirectory() + "\\page.html";
webBrowser1.Url = new Uri(url);
webBrowser1.ObjectForScripting = this;
}
private void button1_Click(object sender, EventArgs e)
{
string imageInBase64 = ReadImageInBase64();
webBrowser1.Document.InvokeScript("setImageData", new[] { imageInBase64 });
}
private string ReadImageInBase64()
{
string imagePath = Directory.GetCurrentDirectory() + "\\opensource.png";
using (var fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
return Convert.ToBase64String(buffer);
}
}
}
}
And this Javascript code:
function setImageData(imageBase64) {
var myImg = document.getElementById("myImg");
myImg.src = "data:image/png;base64," + imageBase64;
}

Categories