Create QRCode with C# and save it as an image - c#

I'm receiving data from a URL on our web application that's dynamically generated using an API's response. I have to handle it by putting it in a QRCode and send this QRCode back to the front-end for my client to download it. We're using C# for back-end and React.js for the front-end.
I've tried to use ZXIng libraries for C# but with no success. I've tried a lot of code, but nothing seems to happen.

Try the following code. It's been tested, but you may need to adapt it for your usage which shouldn't be too difficult.
Download/install NuGet package: ZXing.Net
Add the following using directives:
using System.IO;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
Code:
private Bitmap CreateQrCode(string data)
{
//specify desired options
QrCodeEncodingOptions options = new QrCodeEncodingOptions()
{
CharacterSet = "UTF-8",
DisableECI = true,
Width = 250,
Height = 250
};
//create new instance and set properties
BarcodeWriter writer = new BarcodeWriter()
{
Format = BarcodeFormat.QR_CODE,
Options = options
};
//create QR code and return Bitmap
return writer.Write(data);
}
private byte[] GetQrCodeBytes(string data, System.Drawing.Imaging.ImageFormat imgFormat)
{
using (MemoryStream ms = new MemoryStream())
{
//create QR code and save to file
using (Bitmap bmp = CreateQrCode(data))
{
//save to MemoryStream
bmp.Save(ms, imgFormat);
}
return ms.ToArray();
}
}
private string GetTextFromQrCode(byte[] qrcodeBytes)
{
//specify desired options
DecodingOptions options = new DecodingOptions()
{
CharacterSet = "UTF-8"
};
//create new instance and set properties
BarcodeReader reader = new BarcodeReader() { Options = options };
using (MemoryStream ms = new MemoryStream(qrcodeBytes))
{
using (Bitmap bmp = (Bitmap)Bitmap.FromStream(ms))
{
//decode QR code
Result r = reader.Decode(bmp);
//return QR code text
return r.Text;
}
}
}
private string GetTextFromQrCode(string filename)
{
//specify desired options
DecodingOptions options = new DecodingOptions()
{
CharacterSet = "UTF-8"
};
//create new instance and set properties
BarcodeReader reader = new BarcodeReader() { Options = options };
//read image and convert to Bitmap
using (Bitmap bmp = (Bitmap)Bitmap.FromFile(filename))
{
//decode QR code
Result r = reader.Decode(bmp);
//return QR code text
return r.Text;
}
}
private void SaveQrCode(string data, string filename, System.Drawing.Imaging.ImageFormat imgFormat)
{
//create QR code and save to file
using (Bitmap bmp = CreateQrCode(data))
{
bmp.Save(filename, imgFormat);
}
}
Decode QR Code (Usage 1):
string filename = #"C:\Temp\TestQrCode.png"
string qrcodeText = GetTextFromQrCode(filename);
Decode QR Code (Usage 2):
Note: In the code below, the QR code is read from a file and placed in a byte[]. Reading from a file is for demonstration/testing purposes.
string filename = #"C:\Temp\TestQrCode.png"
byte[] qrcodeBytes = File.ReadAllBytes(filename);
string qrcodeText = GetTextFromQrCode(qrcodeBytes);
Save QR Code (Usage 1):
string qrcodeText = "This is a test";
string filename = #"C:\Temp\TestQrCode.png"
//get filename extension
string ext = Path.GetExtension(filename);
if (ext == ".bmp" || ext == ".dib" || ext == ".rle")
SaveQrCode(qrcodeText, filename, System.Drawing.Imaging.ImageFormat.Bmp);
else if (ext == ".jpg" || ext == ".jpeg" || ext == ".jfif" || ext == ".jpe")
SaveQrCode(qrcodeText, fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
else if (ext == ".png")
SaveQrCode(qrcodeText, fileName, System.Drawing.Imaging.ImageFormat.Png);
Save QR Code (Usage 2):
Note: In the code below, the QR code is saved to a byte[], then written to a file. Writing to a file is for demonstration/testing purposes.
string qrcodeText = "This is a test";
string filename = #"C:\Temp\TestQrCode.png"
//get filename extension
string ext = Path.GetExtension(filename);
byte[] qrcodeBytes = null;
if (ext == ".bmp" || ext == ".dib" || ext == ".rle")
qrcodeBytes = GetQrCodeBytes(qrcodeText, System.Drawing.Imaging.ImageFormat.Bmp);
else if (ext == ".jpg" || ext == ".jpeg" || ext == ".jfif" || ext == ".jpe")
qrcodeBytes = GetQrCodeBytes(qrcodeText, System.Drawing.Imaging.ImageFormat.Jpeg);
else if (ext == ".png")
qrcodeBytes = GetQrCodeBytes(qrcodeText, System.Drawing.Imaging.ImageFormat.Png);
//save to file
File.WriteAllBytes(fileName, qrcodeBytes);
Resources
How to read and create barcode images using C# and ZXing.NET
Basic with QR Code using Zxing Library
Setting the filter to an OpenFileDialog to allow the typical image formats?

Related

Revit API - No Space Tags family is loaded in the project

How can I add Space Tags family using only API? I'm trying use
doc.Create.NewSpaces2(level, phase, view);
(https://www.revitapidocs.com/2019/94b4e479-2301-2e78-6201-5bb5614ed796.htm)
in my project, but I'm getting error "No Space Tags family is loaded in the project".
When I added Annotations/Mechanical/Space Tag.rfa using Revit GUI everything is working.
You could embed the SpaceTag.rfa in your DLL as a resource, and then load it into Revit file programmatically when one is not present.
Here's an example:
1. Check if Family exists:
var loadedFam = new FilteredElementCollector(Doc)
.OfClass(typeof(Family))
.Cast<Family>()
.FirstOrDefault(x.Name == famName);
2. Load the Family if it doesn't exist:
if (loadedFam == null)
{
var resourcePath = GetFamilyFromResource(famName);
if (string.IsNullOrWhiteSpace(resourcePath) ||
!e.Document.LoadFamilySymbol(resourcePath,symbolName, out fs)) return null;
}
3. My utility methods here are:
private static string GetFamilyFromResource(string resourceName)
{
var contents = Resources.StreamBinaryEmbeddedResource(AppCommand.AppInstance.Assembly,
$"FullPathToResource.{resourceName}.rfa");
if (!contents.Any()) return string.Empty;
var filePath = Path.Combine(Path.GetTempPath(), $"{resourceName}.rfa");
using (var fileStream = File.Open(filePath, FileMode.Create))
using (var writer = new BinaryWriter(fileStream))
{
writer.Write(contents);
}
if (!File.Exists(filePath) || new FileInfo(filePath).Length <= 0) return string.Empty;
return filePath;
}
public static byte[] StreamBinaryEmbeddedResource(Assembly assembly, string fileName)
{
using (var stream = assembly.GetManifestResourceStream(fileName))
{
if (stream == null) return new byte[] { };
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int)stream.Length);
stream.Dispose();
return buffer;
}
}

Export docx/doc First Header and Footer as docx File Using openXML

I want to ask how can i convert Header/Footer part of MS Word Document (doc/docx)
to HTML.
I'm opening the Document like:
using (WordprocessingDocument wDoc = WordprocessingDocument.Open(memoryStream, true))
a.k.a OpenXML
I'm converting the Document with WmlToHtmlConverter which converts the document excellent except that the headers and footers are skipt, cuz html standart doesnt support pagination. I was wondering how can i get them and extract them as html.
I'm trying by getting them like :
using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(mainFileMemoryStream, true))
{
Document mainPart = wdDoc.MainDocumentPart.Document;
DocumentFormat.OpenXml.Packaging.HeaderPart firstHeader =
wdDoc.MainDocumentPart.HeaderParts.FirstOrDefault();
if (firstHeader != null)
{
using (var headerStream = firstHeader.GetStream())
{
return headerStream.ReadFully();
}
}
return null;
}
and then passing it to the Convertion Function, but i get exception which says:
File Contains Corrupted Data, with stack trace:
at System.IO.Packaging.ZipPackage..ctor(Stream s, FileMode packageFileMode, FileAccess packageFileAccess)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.OpenCore(Stream stream, Boolean readWriteMode)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(Stream stream, Boolean isEditable, OpenSettings openSettings)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(Stream stream, Boolean isEditable)
at DocxToHTML.Converter.HTMLConverter.ParseDOCX(Byte[] fileInfo, String fileName) in D:\eTemida\eTemida.Web\DocxToHTML.Converter\HTMLConverter.cs:line 96
Any Help will be appreciated
a lot of struggle led me to the following solution:
I Created a function for converting byte array of docx Document to Html As Follows
public string ConvertToHtml(byte[] fileInfo, string fileName = "Default.docx")
{
if (string.IsNullOrEmpty(fileName) || Path.GetExtension(fileName) != ".docx")
return "Unsupported format";
//FileInfo fileInfo = new FileInfo(fullFilePath);
string htmlText = string.Empty;
try
{
htmlText = ParseDOCX(fileInfo, fileName);
}
catch (OpenXmlPackageException e)
{
if (e.ToString().Contains("Invalid Hyperlink"))
{
using (MemoryStream fs = new MemoryStream(fileInfo))
{
UriFixer.FixInvalidUri(fs, brokenUri => FixUri(brokenUri));
}
htmlText = ParseDOCX(fileInfo, fileName);
}
}
return htmlText;
}
Where the ParseDOCX does all the convertion. The code of ParseDOCX :
private string ParseDOCX(byte[] fileInfo, string fileName)
{
try
{
//byte[] byteArray = File.ReadAllBytes(fileInfo.FullName);
using (MemoryStream memoryStream = new MemoryStream())
{
memoryStream.Write(fileInfo, 0, fileInfo.Length);
using (WordprocessingDocument wDoc = WordprocessingDocument.Open(memoryStream, true))
{
int imageCounter = 0;
var pageTitle = fileName;
var part = wDoc.CoreFilePropertiesPart;
if (part != null)
pageTitle = (string)part.GetXDocument().Descendants(DC.title).FirstOrDefault() ?? fileName;
WmlToHtmlConverterSettings settings = new WmlToHtmlConverterSettings()
{
AdditionalCss = "body { margin: 1cm auto; max-width: 20cm; padding: 0; }",
PageTitle = pageTitle,
FabricateCssClasses = true,
CssClassPrefix = "pt-",
RestrictToSupportedLanguages = false,
RestrictToSupportedNumberingFormats = false,
ImageHandler = imageInfo =>
{
++imageCounter;
string extension = imageInfo.ContentType.Split('/')[1].ToLower();
ImageFormat imageFormat = null;
if (extension == "png") imageFormat = ImageFormat.Png;
else if (extension == "gif") imageFormat = ImageFormat.Gif;
else if (extension == "bmp") imageFormat = ImageFormat.Bmp;
else if (extension == "jpeg") imageFormat = ImageFormat.Jpeg;
else if (extension == "tiff")
{
extension = "gif";
imageFormat = ImageFormat.Gif;
}
else if (extension == "x-wmf")
{
extension = "wmf";
imageFormat = ImageFormat.Wmf;
}
if (imageFormat == null)
return null;
string base64 = null;
try
{
using (MemoryStream ms = new MemoryStream())
{
imageInfo.Bitmap.Save(ms, imageFormat);
var ba = ms.ToArray();
base64 = System.Convert.ToBase64String(ba);
}
}
catch (System.Runtime.InteropServices.ExternalException)
{ return null; }
ImageFormat format = imageInfo.Bitmap.RawFormat;
ImageCodecInfo codec = ImageCodecInfo.GetImageDecoders().First(c => c.FormatID == format.Guid);
string mimeType = codec.MimeType;
string imageSource = string.Format("data:{0};base64,{1}", mimeType, base64);
XElement img = new XElement(Xhtml.img,
new XAttribute(NoNamespace.src, imageSource),
imageInfo.ImgStyleAttribute,
imageInfo.AltText != null ?
new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
return img;
}
};
XElement htmlElement = WmlToHtmlConverter.ConvertToHtml(wDoc, settings);
var html = new XDocument(new XDocumentType("html", null, null, null), htmlElement);
var htmlString = html.ToString(SaveOptions.DisableFormatting);
return htmlString;
}
}
}
catch (Exception)
{
return "File contains corrupt data";
}
}
So far everything looked nice and easy but then i realized that the Header and the Footer of the Document are just skipt, so i had to somehow convert them.
I tried to use the GetStream() Method of HeaderPart, but of course exception was throw, cuz the Header tree is not the same as the one of the Document.
Then i decided to extract the Header and Footer as new documents (having hard time with this) with openXML's WordprocessingDocument headerDoc = WordprocessingDocument.Create(headerStream,Document) but unfortunaly the convertion of this document was also unsuccsesful as you might thing, because this is just creating a plain docx document without any settings,styles,webSettings etc. . This took a lot of time to figute out.
SO finaly i decided to Create a new Document Via Cathal's DocX Library and it finaly came to live. The Code is as follows :
public string ConvertHeaderToHtml(HeaderPart header)
{
using (MemoryStream headerStream = new MemoryStream())
{
//Cathal's Docx Create
var newDocument = Novacode.DocX.Create(headerStream);
newDocument.Save();
using (WordprocessingDocument headerDoc = WordprocessingDocument.Open(headerStream,true))
{
var headerParagraphs = new List<OpenXmlElement>(header.Header.Elements());
var mainPart = headerDoc.MainDocumentPart;
//Cloning the List is necesery because it will throw exception for the reason
// that you are working with refferences of the Elements
mainPart.Document.Body.Append(headerParagraphs.Select(h => (OpenXmlElement)h.Clone()).ToList());
//Copies the Header RelationShips as Document's
foreach (IdPartPair parts in header.Parts)
{
//Very important second parameter of AddPart, if not set the relationship ID is being changed
// and the wordDocument pictures, etc. wont show
mainPart.AddPart(parts.OpenXmlPart,parts.RelationshipId);
}
headerDoc.MainDocumentPart.Document.Save();
headerDoc.Save();
headerDoc.Close();
}
return ConvertToHtml(headerStream.ToArray());
}
}
So that was with the Header. I'm passing the HeaderPart and getting its Header then Elements. Extracting the relationships, which is very important if you have images in the header, and importing them in the Document itself And the Document is Ready for convertion.
The same steps are used to Generate the Html out of the Footer.
Hope This will help some in his Duty.

Save an image to a specified path with default filename without SaveFileDialog in C#? [duplicate]

This question already has answers here:
How to save a WPF BitmapSource image to a file?
(2 answers)
Closed 5 years ago.
A WPF button opens a file dialog to open an image and display it in an image control
I want to use another button event to open the image in another app, is this possible?
Try this:
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imagebox.Source as BitmapImage));
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
if (data != null)
{
string filename = dlg.FileName;
System.IO.File.WriteAllBytes(filename, data);
}
}
If you don't want to use a dialog you could just specify the file name in a string variable:
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imagebox.Source as BitmapImage));
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
if (data != null)
{
const string filename = #"c:\test\1.jpg";
System.IO.File.WriteAllBytes(filename, data);
}

Image extract from pdf using itextsharp in c#

Hello i am using
public void ExtractImagesFromPDF(string sourcePdf, string outputPath)
{
// NOTE: This will only get the first image it finds per page.
PdfReader pdf = new PdfReader(sourcePdf);
RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);
try
{
for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
{
Response.Write("Page " + pageNumber.ToString());
PdfDictionary pg = pdf.GetPageN(pageNumber);
// recursively search pages, forms and groups for images.
PdfObject obj = FindImageInPDFDictionary(pg);
if (obj != null)
{
int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
PdfObject pdfObj = pdf.GetPdfObject(XrefIndex);
PdfStream pdfStrem = (PdfStream)pdfObj;
bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
if ((bytes != null))
{
using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
{
memStream.Seek(0, SeekOrigin.Begin);
memStream.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
// must save the file while stream is open.
if (!Directory.Exists(outputPath))
Directory.CreateDirectory(outputPath);
string path = System.IO.Path.Combine(outputPath, String.Format(#"{0}.jpg", pageNumber));
System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
System.Drawing.Imaging.ImageCodecInfo jpegEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);
img.Save(path, jpegEncoder, parms);
}
}
}
else
{
}
}
}
catch
{
throw;
}
finally
{
pdf.Close();
raf.Close();
}
}
code but does not extract my pdf file , parameter is not valid error and i am using third party dll use for extract image so where get all images from pdf but i want to use itextsharp dll , please check and help me.

File being used (without opening it) c#

I got a strange error with this program, It download a photo from internet, then I convert it to .jpeg and then I delete the first photo (in .png).
But i got an error: File is being used by another process. Why is happening this? I didn't open the file, and nobody is using it.
string outFile;
outFile = Path.GetTempFileName();
try
{
webClient.DownloadFile(foto, outFile);
if (foto.Substring(foto.Length - 3) == "png")
{
System.Drawing.Image image1 = System.Drawing.Image.FromFile(outFile);
foto = foto.Remove(foto.Length - 3) + "jpg";
string outFile2 = Path.GetTempFileName();
image1.Save(outFile2, System.Drawing.Imaging.ImageFormat.Jpeg);
System.IO.File.Delete(outFile);
outFile = outFile2;
}
}
FromFile is keeping the file open, you have to use something like this:
// Load image
FileStream filestream;
filestream = new FileStream("Filename",FileMode.Open, FileAccess.Read);
currentImage = System.Drawing.Image.FromStream(filestream);
filestream.Close();
The system.Drawing.Image is holding on to the file, Just wrap the image1 in a using statement.
string foto = "http://icons.iconarchive.com/icons/mazenl77/I-like-buttons/64/Style-Config-icon.png";
string outFile = Path.GetTempFileName();
WebClient webClient = new WebClient();
try
{
webClient.DownloadFile(foto, outFile);
if (Path.GetExtension(foto).ToUpper() == ".PNG")
{
string outFile2 = Path.GetTempFileName();
using (System.Drawing.Image image1 = System.Drawing.Image.FromFile(outFile))
{
image1.Save(outFile2, System.Drawing.Imaging.ImageFormat.Jpeg);
}
System.IO.File.Delete(outFile);
}
}

Categories