Render a barcode in ASP.NET Web Form - c#

i am trying to show the barcode in asp.net page. already download the zen barcode render with sample code. i tried the sample it is working fine with me. once i try in my code barcode label is showing empty. i checked with sample code and mine i did not find any difference , only data transfer is the different. this is what i tried.
<barcode:BarcodeLabel ID="BarcodeLabel1" runat="server" BarcodeEncoding="Code39NC" LabelVerticalAlign="Bottom" Text="12345"></barcode:BarcodeLabel>
if (!IsPostBack)
{
List<string> symbologyDataSource = new List<string>(
Enum.GetNames(typeof(BarcodeSymbology)));
symbologyDataSource.Remove("Unknown");
barcodeSymbology.DataSource = symbologyDataSource;
barcodeSymbology.DataBind();
}
this is the function
BarcodeSymbology symbology = BarcodeSymbology.Unknown;
if (barcodeSymbology.SelectedIndex != 0)
{
symbology = (BarcodeSymbology)1;
}
symbology = (BarcodeSymbology)1;
string text = hidID.Value.ToString();
string scaleText = "1";
int scale;
if (!int.TryParse(scaleText, out scale))
{
if (symbology == BarcodeSymbology.CodeQr)
{
scale = 3;
}
else
{
scale = 1;
}
}
else if (scale < 1)
{
scale = 1;
}
if (!string.IsNullOrEmpty(text) && symbology != BarcodeSymbology.Unknown)
{
barcodeRender.BarcodeEncoding = symbology;
barcodeRender.Scale = 1;
barcodeRender.Text = text;
}
symbology is set as Code39NC from the dropdown. scale is 1 and text is coming from other form the value is passing as well. still the bacodelable is showing only value not the barcode picture.

Here are two code samples using ZXing to create a (QR) barcode as both an image and as a base64 encoded string. Both of these options can be used with an <img /> tag to embed the barcode in the page.
This is not an ASP.NET control. It is a library that creates barcodes from text.
// First Text to QR Code as an image
public byte[] ToQRAsGif(string content)
{
var barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = this._h,
Width = this._w,
Margin = 2
}
};
using (var bitmap = barcodeWriter.Write(content))
using (var stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Gif);
stream.Position = 0;
return stream.GetBuffer();
}
}
// From Text to QR Code as base64 string
public string ToQRAsBase64String(string content)
{
var barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = _h,
Width = _w,
Margin = 2
}
};
using (var bitmap = barcodeWriter.Write(content))
using (var stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Gif);
return String.Format("data:image/gif;base64,{0}", Convert.ToBase64String(stream.ToArray()));
}
}
Hope this helps! Happy coding.
UPDATE: Here is the link to their product page on codeplex: https://zxingnet.codeplex.com/

Related

Paragraph not changing to desired format in ppt with openxml

I'm trying to edit a paragraph in pptx through changing its text, font size, font style and alignment.
This is what i have done so far:
**this is the method im using to call the update paragraph**
public static void Main(string[] args)
{
using (PresentationDocument presentationDocument = PresentationDocument.Open("ppturl", true))
{
// Get the presentation part of the presentation document.
PresentationPart presentationPart = presentationDocument.PresentationPart;
// Verify that the presentation part and presentation exist.
if (presentationPart != null && presentationPart.Presentation != null)
{
// Get the Presentation object from the presentation part.
Presentation presentation = presentationPart.Presentation;
// Verify that the slide ID list exists.
if (presentation.SlideIdList != null)
{
SlideId sourceSlide = presentation.SlideIdList.ChildElements[0] as SlideId;
SlidePart slidePart = presentationPart.GetPartById(sourceSlide.RelationshipId) as SlidePart;
updateParagraph(slidePart);
}
}
}
Console.ReadLine();
CreateHostBuilder(args).Build().Run();
}
**Here im extracting the title in the slide because this is what i need.**
public static void updateParagraph(SlidePart slidePart)
{
if (slidePart == null)
{
throw new ArgumentNullException("presentationDocument");
}
if (slidePart.Slide != null)
{
// Find all the title shapes.
var shapes = from shape in slidePart.Slide.Descendants<Shape>()
where IsTitleShape(shape)
select shape;
foreach (P.Shape shape in shapes)
{
D.Paragraph paragraph = shape.TextBody.Elements<D.Paragraph>().FirstOrDefault();
shape.TextBody.RemoveAllChildren<D.Paragraph>();
AddNewParagraph(shape, "This is a new Slide");
}
}
}
**This is where i am trying to add a new paragraph with specific style**
public static void AddNewParagraph(this P.Shape shape, string NewText)
{
D.Paragraph p = new D.Paragraph();
P.TextBody docBody = shape.TextBody;
Justification justification1 = new Justification() { Val = JustificationValues.Center };
p.ParagraphProperties=new D.ParagraphProperties(justification1);
D.Run run = new D.Run(new D.Text(NewText));
D.RunProperties runProp = new D.RunProperties() { Language = "en-US", FontSize = 9, Dirty = false };
run.AppendChild(runProp);
D.Text newText = new D.Text(NewText);
run.AppendChild(newText);
Console.WriteLine("--------------------------------------------------------------");
Console.WriteLine(runProp.FontSize.ToString());
Console.WriteLine("--------------------------------------------------------------");
p.Append(run);
docBody.Append(p);
}
This is giving me an error whenever im trying to open the pptx "repair pptx error".
Can someone please provide a clear solution specific to pptx and not doc.?
Thankful..
You can try using Aspose.Slides for .NET. The following code example shows you how to change some paragraph properties with this library:
using (var presentation = new Presentation("example.pptx"))
{
var firstShape = (IAutoShape) presentation.Slides[0].Shapes[0];
var firstParagraph = firstShape.TextFrame.Paragraphs[0];
var firstPortion = firstParagraph.Portions[0];
firstPortion.Text = "New text.";
firstPortion.PortionFormat.FontHeight = 24;
firstPortion.PortionFormat.FontBold = NullableBool.True;
firstParagraph.ParagraphFormat.Alignment = TextAlignment.Center;
presentation.Save("example.pptx", SaveFormat.Pptx);
}
You can also evaluate Aspose.Slides Cloud SDK for .NET. This REST-based API allows you to make 150 free API calls per month for API learning and presentation processing. The following code example shows you how to change the paragraph settings using Aspose.Slides Cloud:
var slidesApi = new SlidesApi("my_client_id", "my_client_key");
var fileName = "example.pptx";
var slideIndex = 1;
var shapeIndex = 1;
var paragraphIndex = 1;
var portionIndex = 1;
var firstPortion = slidesApi.GetPortion(
fileName, slideIndex, shapeIndex, paragraphIndex, portionIndex);
firstPortion.Text = "New text.";
firstPortion.FontHeight = 24;
firstPortion.FontBold = Portion.FontBoldEnum.True;
slidesApi.UpdatePortion(
fileName, slideIndex, shapeIndex, paragraphIndex, portionIndex, firstPortion);
var firstParagraph = slidesApi.GetParagraph(
fileName, slideIndex, shapeIndex, paragraphIndex);
firstParagraph.Alignment = Paragraph.AlignmentEnum.Center;
slidesApi.UpdateParagraph(
fileName, slideIndex, shapeIndex, paragraphIndex, firstParagraph);
I work as a Support Developer at Aspose.

IText7 PDFHtml generator with header and footer for C#

I am trying to generating a PDF from predefined HTML content. I managed to generate the content, yet without the required HTML Header, HTML Footer, and Arabic language is not supported as well.
My requirements:
Arabic language support.
The ability to generate more than 10 pages.
The footer may differ from one page to another.
There is a web application that sends a request to a WCF service, and the service returns a byte array containing the PDF.
So, I have been searching for a couple of days for a good tool and I found SelectPdf, it is perfect except that it is NOT free, so the only solution is IText7 PDFHtml.
The thing is this library has good documentation for JAVA, and I am really struggling in following the C# examples and converting from JAVA API to C# code.
Anyone has done something similar before with c#?
After a long process of searching and trying, I have got it working and achieved the following features:
Image in the header.
Base64 image in the footer, in addition to the ability to write some text in the other side in the footer.
Generating the same footer for all pages except for the last one.
the number of the generated pages was unlimited.
Page numbering.
All the previous features were free of charge, however, supporting Arabic language needs a license, so I have to pay anyway :)
Kindly find below my C# code and post your improvements if you have any.
public class Pdfgenerator
{
public const string FONT = "Fonts/NotoNaskhArabic-Regular2.ttf";
public static string HEADER_TEXT = "<table width=\"100%\" border=\"0\"><tr><td>Header</td><td align=\"right\">Some title</td></tr></table>";
public static string FOOTER_TEXT = "<table width=\"100%\" border=\"0\"><tr><td>Footer</td><td align=\"right\">Some title</td></tr></table>";
public MemoryStream createPdf()
{
string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
MemoryStream file = new MemoryStream();
PdfDocument pdfDocument = null;
PdfDocument pdfDoc = null;
PdfDocument pdfDocument1 = null;
try
{
using (file)
{
PdfFont f = PdfFontFactory.CreateFont(apPath + FONT, PdfEncodings.IDENTITY_H);
string header = "pdfHtml Header and footer example using page-events";
Header headerHandler = new Header(header);
Footer footerHandler = new Footer();
ConverterProperties converterProperties = new ConverterProperties();
PdfWriter writer1 = new PdfWriter(apPath + "test1.pdf");
pdfDocument1 = new PdfDocument(writer1);
pdfDocument1.AddEventHandler(PdfDocumentEvent.START_PAGE, headerHandler);
pdfDocument1.AddEventHandler(PdfDocumentEvent.END_PAGE, footerHandler);
converterProperties = new ConverterProperties().SetBaseUri(apPath);
HtmlConverter.ConvertToDocument(File.ReadAllText(apPath + "content.html"), pdfDocument1, converterProperties);
footerHandler.lastPage = pdfDocument1.GetLastPage();
pdfDocument1.Close();
}
}
catch (Exception ex)
{
}
finally
{
file.Dispose();
}
return new MemoryStream();
}
}
Generating the header:
class Header : IEventHandler
{
private string header;
private Image image;
public Header(string header)
{
string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
this.header = header;
image = new Image(ImageDataFactory.Create(apPath + "Images/RANDOM_PHOTO.jpg"));
}
public void HandleEvent(Event #event)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent)#event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
Rectangle pageSize = page.GetPageSize();
Canvas canvas = new Canvas(new PdfCanvas(page), pdf, pageSize);
canvas.SetFontSize(18);
// Write text at position
canvas.Add(image);
canvas.Close();
}
}
Generating the footer:
class Footer : IEventHandler
{
public PdfPage lastPage = null;
protected PdfFormXObject placeholder;
protected float side = 20;
protected float x = 300;
protected float y = 25;
protected float space = 4.5f;
protected float descent = 3;
public Footer()
{
placeholder = new PdfFormXObject(new Rectangle(0, 0, side, side));
}
public void HandleEvent(Event #event)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent)#event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
int pageNumber = pdf.GetPageNumber(page);
Rectangle pageSize = page.GetPageSize();
// Creates drawing canvas
PdfCanvas pdfCanvas = new PdfCanvas(page);
Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
IList<iText.Layout.Element.IElement> elements = HtmlConverter.ConvertToElements("<table border=\"0\"><tr><td><img src=\"data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==\" alt=\"Italian Trulli\"></td></tr></table>");
Paragraph p = new Paragraph();
foreach (iText.Layout.Element.IElement e in elements)
{
if (e is IBlockElement) {
p.Add((IBlockElement)e);
}
}
if (lastPage == docEvent.GetPage()) {
}
else
{
canvas.ShowTextAligned(p, 25, 75, TextAlignment.LEFT);
}
canvas.Close();
// Create placeholder object to write number of pages
pdfCanvas.AddXObject(placeholder, x + space, y - descent);
pdfCanvas.Release();
}
public void writeTotal(PdfDocument pdf)
{
Canvas canvas = new Canvas(placeholder, pdf);
canvas.ShowTextAligned(pdf.GetNumberOfPages().ToString(),
0, descent, TextAlignment.LEFT);
canvas.Close();
}
}
I was trying to get a stream as an output, so if you want that as well you can use the following in your main service:
public byte[] GetData()
{
MemoryStream stream = new Pdfgenerator().createPdf();
byte[] arr = stream.ToArray();
return stream.ToArray();
}

Unable to capture screen of WkWebView in Xamarin IOS

I am trying to capture the screen in IOS, Other than WkWebview all other view component I am able to capture by below code.WkWebview is giving a blank page as captured data. If I am using UIWebview the same code working Is there anything specific to do to take screen shot WkWebView.
Code for screen capture.
public static UIImage SnapshotView(this UIView view)
{
UIGraphics.BeginImageContextWithOptions(view.Bounds.Size, false, UIScreen.MainScreen.Scale);
view.DrawViewHierarchy(view.Bounds, true);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return image;
}
WkWebView Configuration:
WKWebView _wkWebView = new WKWebView(ReaderView.Frame, new WKWebViewConfiguration());
_wkWebView.LoadFileUrl(tempUrl, tempUrl);
_wkWebView.ContentMode = UIViewContentMode.ScaleToFill;
_wkWebView.BackgroundColor = UIColor.Clear;
_wkWebView.Opaque = false;
_wkWebView.ScrollView.BackgroundColor = UIColor.Clear;
//_wkWebView.DrawViewHierarchy(_wkWebView.Bounds, true);
ReaderView.AddSubview(_wkWebView);
var imag = _wkWebView.SnapshotView();
I fixed the issue by replacing the WKWebView with PdfView.I am using this view for loading PDFs.
The latest code is below
pdfView = new PdfView();
pdfView.TranslatesAutoresizingMaskIntoConstraints = false;
ReaderView.AddSubview(pdfView);
pdfView.LeadingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.LeadingAnchor).Active = true;
pdfView.TrailingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TrailingAnchor).Active = true;
pdfView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor).Active = true;
pdfView.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor).Active = true;
// var path = Bundle.main.url(forResource: "test", withExtension: "pdf") else { return }
PdfDocument document;
// PdfDocument
using (urlString = new NSString(FilePath))
using (var tempUrl = NSUrl.CreateFileUrl(new string[] { urlString }))
document = new PdfDocument(tempUrl);
//if var document = PdfDocument(url: path) {
pdfView.Document = document;

Digit recognition with Tesseract OCR and c#

I use Tesseract and C# to read digits. Everything works well except for the number "8". Tesseract can not read the "8" Digit.
This is the picture I send to tesseract :
And tesseract reads "50005550055".
this is my method :
public string Process(Bitmap bitmap, MetaTraderObjects metaObjects, bool isNumber = false)
{
try
{
var graphicLib = new GraphicLib();
bitmap = graphicLib.PerformReadingTextEffects(bitmap.ToBytes(), metaObjects).ToBitmap();
var result = "";
var enginePath = Const.BaseAppPath + "\\tessdata";
using (var engine = new TesseractEngine(enginePath, "eng", EngineMode.Default))
{
var ver = engine.Version;
using (var img = Pix.LoadTiffFromMemory(graphicLib.ConvertBitMapToByteArray(bitmap.ToBytes())))
{
using (var page = engine.Process(img,(PageSegMode)8))
{
var text = page.GetText();
result = TextReformer.Reform(text, isNumber);
MemoryStream ms = new MemoryStream(bitmap.ToBytes());
Image i = Image.FromStream(ms);
}
}
}
return result;
}
catch (Exception ex)
{
ExceptionLog.Handel(ex);
return null;
}
}
How can I tell Tesseract that the vertical rod is a "8"?
I recommend you use the latest version of Tesseract. It could perform better.
Tesseract 4.1.0

How to create black and white images in Magick.NET

I would like create TIF, PNG, JPG and BMP like black and white images via
https://magick.codeplex.com.
What I found if I do like in my code I can generate only TIF black and why images but not images of other types.
Any clue how to fix it?
MagickReadSettings readSettings = new MagickReadSettings()
{
UseMonochrome = true
};
using (MagickImage image = new MagickImage(fileInfo.FullName, readSettings))
{
image.AddProfile(ColorProfile.SRGB);
if (Properties.Settings.Default.ImageFileExtentionToConvert.ToLower().Contains("tif"))
{
image.CompressionMethod = CompressionMethod.Group4;
image.ColorSpace = ColorSpace.Gray;
image.Format = MagickFormat.Tif;
}
else if (Properties.Settings.Default.ImageFileExtentionToConvert.ToLower().Contains("png"))
{
// image.ColorSpace = ColorSpace.Gray;
image.Settings.SetDefine(MagickFormat.Png, "compression-strategy", "0");
image.Settings.SetDefine(MagickFormat.Png, "compression-filter", "0");
image.Format = MagickFormat.Png;
}
else if (Properties.Settings.Default.ImageFileExtentionToConvert.ToLower().Contains("jpg"))
{
image.Settings.SetDefine(MagickFormat.Jpg, "compression-strategy", "0");
image.Settings.SetDefine(MagickFormat.Jpg, "compression-filter", "0");
image.Format = MagickFormat.Jpg;
}
else
{
image.CompressionMethod = CompressionMethod.NoCompression;
image.Format = MagickFormat.Bmp;
}
image.Write(newFileName);
}
I found the answer here https://magick.codeplex.com/discussions/637181
using (MagickImage image = new MagickImage(pathToTiffFile))
{
image.Threshold(60); // 60 is OK
image.Depth = 1;
image.Write(pathToOutputFile);
}

Categories

Resources