Generate barcode in c# using Itext7
Install Itext7 from Nuget
Copy this code to your controller
[HttpGet]
public ActionResult GenerateBarcode()
{
return View();
}
[HttpPost]
public ActionResult GenerateBarcode(string barcode)
{
if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Itext7Barcodes.pdf"))
System.IO.File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Itext7Barcodes.pdf");
using (var writer = new iText.Kernel.Pdf.PdfWriter(new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Itext7Barcodes.pdf", FileMode.Create)))
{
DataTable dt = new DataTable();
dt.Columns.Add("Barcode");
for (int i = 0; i < 20; i++)
{
DataRow row = dt.NewRow();
row["Barcode"] = barcode;
dt.Rows.Add(row);
}
using (var pdf = new iText.Kernel.Pdf.PdfDocument(writer))
{
var doc = new Document(pdf,new iText.Kernel.Geom.PageSize(24,12));
doc.SetMargins(5, 5, 1, 1);
for (int i = 0; i < dt.Rows.Count; i++)
{
var page = pdf.AddNewPage();
PdfFont font = PdfFontFactory.CreateFont("Times-BoldItalic", false);
PdfCanvas pdfCanvas = new PdfCanvas(page);
pdfCanvas.SetFontAndSize(font, 1.0f);
pdfCanvas.BeginText();
pdfCanvas.SetTextMatrix(1.2f, 7.5f);
pdfCanvas.ShowText("Product Name");
pdfCanvas.EndText();
var bc = new Barcode128(pdf);
bc.SetTextAlignment(0);
bc.SetCodeType(Barcode128.CODE128);
bc.SetStartStopText(false);
bc.SetCode(barcode);
bc.SetExtended(true);
//Here's how to add barcode to PDF with IText7
var img = new Image(bc.CreateFormXObject(pdf));
img.ScaleToFit(60, 5);
doc.Add(img);
}
doc.Close();
}
}
System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Itext7Barcodes.pdf");
return Json(0, JsonRequestBehavior.AllowGet);
}
|
copy this code to your view
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | @{ ViewBag.Title = "GenerateBarcode"; } @using (Html.BeginForm("GenerateBarcode", "Home", FormMethod.Post)) { <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <h2>Generate Bar Code</h2> <input type="text" name="barcode" Class="form-control col-4" ID="textCode" /> <br /> <input type="submit" Class="btn btn-primary" ID="btnGenerate" value="Generate" /> <hr /> </div> </div> } |




0 Comments