Add Barcode Image in PDF using C#

I am generating barcode with the help of Aspose.PDF since 2 months but could not complete. Please help me.I shall highly obliged for this kindness.

1.its not taking page in graphics its only taking image in the graphics.
2.barcode image is not coming inside the rectangle.
3.Rectangle is not coming properly as per given coordinates and per barcode.

@naresh.mahto

Are you using our free web app or on-premises/back-end API for this?

@Atir_Tahir
We are using licensed version of Aspose.PDF. In our project we are using API in .NET Core.
We have tried by table to create dynamic barcode. But coordinates are not showing Barcode and Rectangle as per expected.
I have attached the sample of barcode which we need.

BarcodeTest.png (87.3 KB)

@naresh.mahto

Have you tried adding the barcode image using ImageStamp in the PDF? Please check the below article(s) in the API documentation which may help you adding the barcode image by specifying the XIndent and YIndent Properties. In case you still face any issues, please share a sample barcode image, rectangle coordinates, sample source file and an expected output PDF. We will test the scenario in our environment and address it accordingly.

@asad.ali

I have tried adding the barcode image using ImageStamp in the PDF.But it is working only when we want to print 1 barcode.But we need barcode as a dynamic with rectangle.
I have attached sample pdf file What we want actually.
E.g if want print 4 barcode then we need generate 4 rectangle with barcode image and text.OldPortrait.pdf (42.4 KB)

@naresh.mahto

You can please use table in order to obtain the required formatting and expected output. Please check the below sample code snippet and attached PDF output:

string barcodeText = "MVP20220119J06561210";
string barcodeImage = dataDir + "barcode.jpg";

Document pdfDocument = new Document();
Page page = pdfDocument.Pages.Add();
page.SetPageSize(PageSize.A3.Width, PageSize.A3.Height);
page.PageInfo.Margin = new MarginInfo(0, 0, 0, 0);

Table table = new Table();
table.ColumnAdjustment = ColumnAdjustment.AutoFitToWindow;
table.IsBordersIncluded = true;
table.ColumnWidths = "50% 50%";

Aspose.Pdf.Image img = new Image();
img.HorizontalAlignment = HorizontalAlignment.Center;
img.File = barcodeImage;

Row row1 = table.Rows.Add();
row1.DefaultCellPadding = new MarginInfo(0, 5, 0, 10);
row1.DefaultCellBorder = new BorderInfo(BorderSide.Top | BorderSide.Left | BorderSide.Right, 2f, Color.Black);
Cell cell1 = row1.Cells.Add();
Cell cell2 = row1.Cells.Add();

cell1.Alignment = HorizontalAlignment.Center;
cell1.Paragraphs.Add(img);
cell2.Alignment = HorizontalAlignment.Center;
cell2.Paragraphs.Add(img);

Row row2 = table.Rows.Add();
row2.DefaultCellPadding = new MarginInfo(0, 10, 0, 5);
row2.DefaultCellBorder = new BorderInfo(BorderSide.Bottom | BorderSide.Left | BorderSide.Right, 2f, Color.Black);
Cell cell3 = row2.Cells.Add(barcodeText);
cell3.Alignment = HorizontalAlignment.Center;
Cell cell4 = row2.Cells.Add(barcodeText);
cell4.Alignment = HorizontalAlignment.Center;

Row row3 = table.Rows.Add();
row3.DefaultCellPadding = new MarginInfo(0, 5, 0, 10);
row3.DefaultCellBorder = new BorderInfo(BorderSide.Top | BorderSide.Left | BorderSide.Right, 2f, Color.Black);
Cell cell5 = row3.Cells.Add();
Cell cell6 = row3.Cells.Add();

cell5.Alignment = HorizontalAlignment.Center;
cell5.Paragraphs.Add(img);
cell6.Alignment = HorizontalAlignment.Center;
cell6.Paragraphs.Add(img);

Row row4 = table.Rows.Add();
row4.DefaultCellPadding = new MarginInfo(0, 10, 0, 5);
row4.DefaultCellBorder = new BorderInfo(BorderSide.Bottom | BorderSide.Left | BorderSide.Right, 2f, Color.Black);
Cell cell7 = row4.Cells.Add(barcodeText);
cell7.Alignment = HorizontalAlignment.Center;
Cell cell8 = row4.Cells.Add(barcodeText);
cell8.Alignment = HorizontalAlignment.Center;

page.Paragraphs.Add(table);

pdfDocument.Save(dataDir + "Barcode.pdf");

Barcode.pdf (53.8 KB)

@asad.ali

The code you shared for its for static barcode. We need to implement the dynamic barcode Such as:100 or 150 barcode at a time. In some cases barcode column also dynamically increases as per page size.
How can i print the barcode dynamically using rectangle.

@naresh.mahto

The shared code snippet was just a sample. It was an example of how you can implement table approach to properly align and style the barcode images with text inside a PDF. You can change it as per your requirements in order to make it dynamic. For example, you can add this code inside a loop to read barcode images from some list or directory along with respective text and add rows and cells inside table.

Regarding column and page size, you can easily control it dynamically or you can specify the height and width of the barcode image inside table cell. In case you still face any issue while achieving it, please share the code snippet that you have tried so far to implement dynamic approach along with the information of how you are getting barcode images and text information and how they are supposed to impact the page and column size. We will try to create another example for you and share it with you.

@asad.ali
I want to implement the print barcode dynamically by Rectangle and Coordinates.
I have existing code using PDFSharp.

PdfDocument document = new PdfDocument();

PdfPage page = document.AddPage();

using(XGraphics gfx = XGraphics.FromPdfPage(page)){

while(labelcount<labelremaining)
{

XRect rect=new XRect(coord.X,coor.Y,labelsize.Width,labelsize.Height);
gfx.DrawRectangle(pen,XBrushesh.Transparent,rect);

XImage barCodeimage=CreateBarcode(“Test1”,barsize.Width,barsize.Height,false,1);
XPoint barCodepoint=new XPoint(coor.X,Coor.Y);

gfx.DrawString(“test1”,font,Xbruseshes.Black,coord.X,coord.Y);
gfx.DrawImage(barCodeimage,barCodepoint);

++labelcount;InventoryPrintLabels - 2022-02-03T211120.511.pdf (9.6 KB)
InventoryPrintLabels (10).pdf (61.6 KB)

}
}
document.Save(@“C\HelloWorld.pdf”);

@naresh.mahto

Please share the sample values for coord.X,coor.Y,labelsize.Width,labelsize.Height variables for our reference. We will use them to draw the rectangle and add barcode images in the PDF. Also, please share a sample output PDF document as well that is generated using the same values you will be sharing with us. It would help us comparing the results generated at our end during testing.

@asad.ali

Please find below the sample values.
coord.X==306;
coor.Y=113;
labelsize.Width=306;
labelsize.Height=113;

**Note: How i can add graphics to pdf page.And draw the rectangle and coordinates.

@naresh.mahto

Please note that these values could mean anything from perspective of Aspose.PDF as compared to PDFSharp. For example, Aspose.PDF follows a coordinating system where (0,0) means bottom-left. That is why we requested an expected output PDF as well generated using these values.

Please use the same values at your end to place barcode and text in the PDF and share that PDF with us so that we would know where you expect to put the image and text on PDF using Aspose.PDF.

@asad.ali @Atir_Tahir

I have attached the expected output PDF .InventoryPrintLabels - 2022-02-03T211120.511.pdf (9.6 KB)
InventoryPrintLabels (10).pdf (61.6 KB)

@denis.kovalskiy

I need to add the shapes(Rectangle) inside the imagestamp.So that the barcode image will be inside the shapes.

@naresh.mahto

The Graph Shape Rectangle and image stamp are two different things. You cannot add an image stamp inside a shape. You can only draw a shape with text in it. For example, below code:

Document doc = new Document();
            
Page page = doc.Pages.Add();
page.PageInfo.Margin = new MarginInfo(0, 0, 0, 0);


var canvas = new Drawing.Graph((float)page.PageInfo.Width, (float)page.PageInfo.Height);//tf.Rectangle.Width, pg.PageInfo.Height
//canvas.Margin = new MarginInfo() { Bottom = 0, Left = 0, Right = 0, Top = 0 };
//canvas.Left = 0;
//canvas.Top = 0;
//canvas.Border = new BorderInfo(BorderSide.All, 1f, Color.Black);
page.Paragraphs.Add(canvas);

Aspose.Pdf.Drawing.Rectangle rect = new Aspose.Pdf.Drawing.Rectangle(100, 354, 72, 30); //new Aspose.Pdf.Drawing.Rectangle(0, 700, 100, 750);
var c = ColorTranslator.FromHtml("#FFFF00");
//rect.GraphInfo.Color = Aspose.Pdf.Color.FromRgb(c);
//rect.GraphInfo.FillColor = alphaColor;
//canvas.Shapes.Add(rect);
rect.Text = new TextFragment("test address , test address esttest address , test address testtest address , test address test");
rect.GraphInfo.Color = Aspose.Pdf.Color.FromRgb(c);
canvas.Shapes.Add(rect);
doc.Save(dataDir + "rectangle.pdf");

Also, you need to have 4 values of coordinates in order to draw a shape inside PDF Page. Furthermore, Aspose.PDF also offers FloatingBox class that has the feature of border and you can add images as well as text inside it. It takes two coordinates values i.e. Top/Left and you can also set its height and width. Please check below code snippet where we added a floating box along with barcode image and text inside it:

Document doc1 = new Document();
Page Pdfpage = doc1.Pages.Add();
Pdfpage.PageInfo.Margin = new MarginInfo(0, 0, 0, 0);

//coord.X == 306;
//coor.Y = 113;
//labelsize.Width = 306;
//labelsize.Height = 113;
FloatingBox fb = new FloatingBox(306, 113);
fb.Top = 10;
fb.Left = 10;
fb.Border = new BorderInfo(BorderSide.All, Color.Black);

Aspose.Pdf.Image image = new Aspose.Pdf.Image();
image.FixWidth = 150;
image.FixHeight = 100;
image.File = dataDir + "Barcode.jpg";
image.HorizontalAlignment = HorizontalAlignment.Center;
image.VerticalAlignment = VerticalAlignment.Top;

TextFragment textFragment1 = new TextFragment("ABC20220223J11522556");
//// Set text properties
textFragment1.TextState.FontSize = 12;
textFragment1.TextState.FontStyle = FontStyles.Bold;
textFragment1.TextState.Font = FontRepository.FindFont("Courier New");
textFragment1.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Black);
textFragment1.HorizontalAlignment = HorizontalAlignment.Center;
textFragment1.VerticalAlignment = VerticalAlignment.Bottom;

fb.Paragraphs.Add(image);
fb.Paragraphs.Add(textFragment1);

Pdfpage.Paragraphs.Add(fb);
doc1.Save(dataDir + "floatingbox.pdf");

floatingbox.pdf (54.0 KB)

Please note that you cannot consider coordinates values the same in both PDFSharp and Aspose.PDF. They both have their own implementation of PDF Coordinating System and separate Classes and Objects to achieve functionality. Please try to understand how Aspose.PDF deals with coordinates and what classes can be used to achieve your requirement and you will be able to create expected PDF document.

@asad.ali

I need to print the barcode from left to right dynamically sometime it will 2 columns and 3 or 4 columns.
I have used the below lines of code. I have attached the sample file.
test.pdf (219.0 KB)

Page pdfpage=doc.Pages.Add();
//coord.X == 306;
//coor.Y = 113;
//labelsize.Width = 306;
//labelsize.Height = 113;
FloatingBox fb = new FloatingBox(306, 113);
fb.Border = new BorderInfo(BorderSide.All, Color.Black);
pdfpage.PageInfo.Margin=new MarginInfo(1,0,0,1);
Aspose.Pdf.Image image = new Aspose.Pdf.Image();
image.FixWidth = 150;
image.FixHeight = 100;
image.File = dataDir + “Barcode.jpg”;
image.HorizontalAlignment = HorizontalAlignment.Center;
image.VerticalAlignment = VerticalAlignment.Top;

TextFragment textFragment1 = new TextFragment(“ABC20220223J11522556”);
//// Set text properties
textFragment1.TextState.FontSize = 12;
textFragment1.TextState.FontStyle = FontStyles.Bold;
textFragment1.TextState.Font = FontRepository.FindFont(“Courier New”);
textFragment1.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Black);
textFragment1.HorizontalAlignment = HorizontalAlignment.Center;
textFragment1.VerticalAlignment = VerticalAlignment.Bottom;

fb.Paragraphs.Add(image);
fb.Paragraphs.Add(textFragment1);

pdfpage.Paragraphs.Add(fb);

@naresh.mahto

Please try to use the below code snippet:

Document doc1 = new Document();
Page Pdfpage = doc1.Pages.Add();
Pdfpage.PageInfo.Margin = new MarginInfo(0, 0, 0, 0);

int fbWidth = 306;
int fbHeight = 113;
decimal noOfCols = 3;
decimal noOfBarcodes = 15;
decimal noOfRows = Math.Ceiling(noOfBarcodes/noOfCols);

Pdfpage.SetPageSize((double)(fbWidth * noOfCols), (double)(fbHeight * noOfRows));

for(decimal i = 0; i < noOfRows; i++)
{
 for(decimal j = 0; j < noOfCols; j++)
 {
  FloatingBox fb = new FloatingBox(fbWidth, fbHeight);
  fb.Top = (double)(i * fbHeight);
  fb.Left = (double)(j * fbWidth);
  fb.Border = new BorderInfo(BorderSide.All, Color.Black);

  Aspose.Pdf.Image image = new Aspose.Pdf.Image();
  image.FixWidth = 150;
  image.FixHeight = 100;
  image.File = dataDir + "Barcode.jpg";
  image.HorizontalAlignment = HorizontalAlignment.Center;
  image.VerticalAlignment = VerticalAlignment.Top;

  TextFragment textFragment1 = new TextFragment("ABC20220223J11522556");
  //// Set text properties
  textFragment1.TextState.FontSize = 12;
  textFragment1.TextState.FontStyle = FontStyles.Bold;
  textFragment1.TextState.Font = FontRepository.FindFont("Courier New");
  textFragment1.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Black);
  textFragment1.HorizontalAlignment = HorizontalAlignment.Center;
  textFragment1.VerticalAlignment = VerticalAlignment.Bottom;

  fb.Paragraphs.Add(image);
  fb.Paragraphs.Add(textFragment1);

  Pdfpage.Paragraphs.Add(fb);
 }
}
doc1.Save(dataDir + "floatingbox.pdf");

floatingbox.pdf (136.6 KB)

@asad.ali,
We need a dynamic number of columns and we have shared you code snippet for you . The main issue is that alignment is not coming correct while printing 1 barcode and also we notice that barcode image width is not equal to text width .It should be same .
For your reference I am attaching two pdf files in which new file we have alignment issue. We need barcode same as old file. Please check and revert asap , so that we will implement the changes on time.
Document doc = new Document();
int label = 0;

        try
        {
            if (strCodes == null || strCodes.Length == 0 || labelsPerPage == 0)
                return new byte[] { };
           
            int pageCount = 0;
            int totalPages = strCodes.Length / labelsPerPage + ((strCodes.Length % labelsPerPage) > 0 ? 1 : 0);
          //  Graph graph = new Graph(200, 400);
            while (pageCount < totalPages)
            {
                Page pdfPage = doc.Pages.Add();
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(612,792);

               
                pdfPage.SetPageSize(612, 792);
                pdfPage.PageInfo.IsLandscape = IsLandscape;
               
                Graph graph = new Graph(612, 792);

                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    if (pageCount == 0)
                    {
                        codeSize = new SizeF(0, 0);
                      
                        //barSize = new Aspose.Pdf.PageSize(200,0);
                        barSize = new Aspose.Pdf.PageSize(384, 0);
                     

                        TextFragment textFragment = new TextFragment("ABC20220223J11522556");
                        // Set text properties
                        textFragment.TextState.FontSize = 12;
                        textFragment.TextState.Font = FontRepository.FindFont("Courier New");
                        double width = textFragment.Rectangle.Width;

                        codeSize.Width = Convert.ToSingle(width);
                        codeSize.Height = 12;
                        double minFitWidth = GT(codeSize.Width, barSize.Width) ? codeSize.Width : barSize.Width;//200

                        //labelSize.Width = 306;
                        //labelSize.Height = 113;
                        labelSize.Width = 612;
                        labelSize.Height = 396;
                        //barSize.Height = 99;
                        barSize.Height = labelSize.Height - codeSize.Height;
                        if (GT(barSize.Height, barSize.Width / GOLDENRATIO))
                            barSize.Height = barSize.Width / Convert.ToSingle(GOLDENRATIO);
                        bCoords = new Aspose.Pdf.Point(0, 0);
                        
                        cCoords = new Aspose.Pdf.Point(0, 0);
                        //bCoords.X = 78;// ;
                        //cCoords.X = 80;// ;
                        //bCoords.Y = 12;
                        //cCoords.Y = 97;

                        bCoords.X = 162;// ;
                        cCoords.X = 233.98;// ;
                        bCoords.Y = 117;
                        cCoords.Y = 276;
                    }
                    Aspose.Pdf.Facades.PdfFileStamp fileStamp = new Aspose.Pdf.Facades.PdfFileStamp(doc);
                    int labelCount = 0;
                    int labelRemaining = (labelCount + 1) > strCodes.Length ? strCodes.Length : (labelCount + 1);//14
                    Aspose.Pdf.Point gCoords = new Aspose.Pdf.Point((int)margins.Width, (int)margins.Height);//0,0

                   
                    while (labelCount < labelRemaining)
                    {
                        if (LTE(gCoords.X + labelSize.Width, pdfPage.PageInfo.Width) && LTE(gCoords.Y + labelSize.Height, pdfPage.PageInfo.Height))
                        {
                            Aspose.Pdf.Drawing.Rectangle rect = new Aspose.Pdf.Drawing.Rectangle((int)gCoords.X, (int)gCoords.Y, labelSize.Width, labelSize.Height);

                             MemoryStream mystream2 = new MemoryStream(CreateBarCode(strCodes[labelCount], (int)barSize.Width, (int)barSize.Height, false, 1));

                           
                            FloatingBox fb = new FloatingBox(labelSize.Width, labelSize.Height);
                            fb.Top = (double)gCoords.Y;
                            fb.Left = (double)gCoords.X;
                            fb.Padding.Top = bCoords.Y;

                            fb.Border = new BorderInfo(BorderSide.All, Aspose.Pdf.Color.Black);
                            pdfPage.PageInfo.Margin = new MarginInfo(1, 0, 0, 1);
                            
                            Aspose.Pdf.Image image = new Aspose.Pdf.Image();
                            image.FixWidth = (int)barSize.Width ;
                            image.FixHeight = (int)barSize.Height ;
                            image.ImageStream = mystream2;
                           
                            image.HorizontalAlignment = HorizontalAlignment.Center;
                           
                            TextFragment textFragment1 = new TextFragment("ABC20220223J11522556");
                            //// Set text properties
                            textFragment1.TextState.FontSize = 12;
                            textFragment1.TextState.FontStyle = FontStyles.Bold;
                            textFragment1.TextState.Font = FontRepository.FindFont("Courier New");
                            textFragment1.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Black);
                            textFragment1.HorizontalAlignment = HorizontalAlignment.Center;
                            //textFragment1.VerticalAlignment = VerticalAlignment.Bottom;
                           
                            fb.Paragraphs.Add(image);
                            fb.Paragraphs.Add(textFragment1);

                            pdfPage.Paragraphs.Add(fb);
                            ++labelCount;
                            gCoords.X += labelSize.Width + gaps.Width;//306

                            if (GT(gCoords.X + labelSize.Width, pdfPage.PageInfo.Width))
                            {
                                gCoords.X = margins.Width;
                                gCoords.Y += labelSize.Height + gaps.Height;
                            }

                        }
                        else
                        {
                            throw new InvalidOperationException("Label Print Combinations Invalid for the Page");
                        }
                    }
                    //  pdfPage.Paragraphs.Add(graph);

                }
                ++pageCount;
            }
        }
        catch (Exception exp)
        {
          
            throw exp;
        }

Old file.pdf (5.4 KB)
new file.pdf (143.6 KB)

@NehaKh

Have you tried the code snippet that we have shared in our previous here? You only need to change below parameters in the above code to get the required output:

int fbWidth = 306;
int fbHeight = 113;
decimal noOfCols = 3;
decimal noOfBarcodes = 15;
decimal noOfRows = Math.Ceiling(noOfBarcodes/noOfCols);

Regarding image height and width, below values can be changes as per desire to set the image dimensions:

image.FixWidth = 150;
image.FixHeight = 100;

You can also set the image width equal to the width of text. The text width can be obtained by using the following method:

textFragment.TextState.MeasureString(textFragment.Text)

Please apply this changes and share updated code snippet with us in case you are still unable to achieve what you require.

Hi @asad.ali,

The things which you shared to us is not working for 1or 2 barcode.
I have shared you only the value coming for 1 barcode. actually its dynamic we cant give values like that in dynamic. can you please look again my code shared in previous msg and suggest some logic to fix it.