How to set current page number in barcode value in Header

Hi Team,

I Need to set current page number as bar code value (or append to bar code value) which is in Header part.
Could you please help me how can we do it?
For ex : I have a word template with a barcode in header. if I generate a pdf out of it by supplying merge field values dataset , i should get bar code with value as page number which is different for each page.
if my template has 3 pages , then I should get bar code value as below
Page 1
=======
BarCodevalue_1
Page 2
========
BarCodevalue_2

Page 3
=======
BarCodevalue_3

BarCode_Template_ Pagenumber.zip (8.3 KB)

@vbhasker You can put PAGE field into the DISPLAYBARCODE field value, like this:

{ DISPLAYBARCODE "SomeValue{ PAGE }" QR }

In this case the displayed value of DISPLAYBARCODE will depend on the value of PAGE field.

Hi Alexey,

Thanks for your reply. it is working with DISPLAYBARCODE however the barcode value field is not getting the actual bar code value. we are just getting field name in output pdf. Can we do the same with MERGEBARCODE ?
I have attached the sample template and output pdf for reference. In the attached output pdf , instead of Address we should get actual value of address string.

Thanks
–VijayasposeForum.zip (766.7 KB)

@vbhasker I cannot reproduce the problem on my side. I have used Aspose.Barcode as a custom barcode generator. Here is my full code:

Document doc = new Document(@"C:\Temp\in.xml");
doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();
doc.Save(@"C:\Temp\out.pdf");
public class CustomBarcodeGenerator : IBarcodeGenerator
{
    /// <summary>
    /// Converts barcode image height from Word units to Aspose.BarCode units.
    /// </summary>
    /// <param name="heightInTwipsString"></param>
    /// <returns></returns>
    private static float ConvertSymbolHeight(string heightInTwipsString)
    {
        // Input value is in 1/1440 inches (twips)
        int heightInTwips = TryParseInt(heightInTwipsString);

        if (heightInTwips == int.MinValue)
            throw new Exception("Error! Incorrect height - " + heightInTwipsString + ".");

        // Convert to mm
        return (float)(heightInTwips * 25.4 / 1440);
    }

    /// <summary>
    /// Converts barcode image color from Word to Aspose.BarCode.
    /// </summary>
    /// <param name="inputColor"></param>
    /// <returns></returns>
    private static Color ConvertColor(string inputColor)
    {
        // Input should be from "0x000000" to "0xFFFFFF"
        int color = TryParseHex(inputColor.Replace("0x", ""));

        if (color == int.MinValue)
            throw new Exception("Error! Incorrect color - " + inputColor + ".");

        return Color.FromArgb(color >> 16, (color & 0xFF00) >> 8, color & 0xFF);

        // Backward conversion -
        //return string.Format("0x{0,6:X6}", mControl.ForeColor.ToArgb() & 0xFFFFFF);
    }

    /// <summary>
    /// Converts bar code scaling factor from percent to float.
    /// </summary>
    /// <param name="scalingFactor"></param>
    /// <returns></returns>
    private static float ConvertScalingFactor(string scalingFactor)
    {
        bool isParsed = false;
        int percent = TryParseInt(scalingFactor);

        if (percent != int.MinValue && percent >= 10 && percent <= 10000)
            isParsed = true;

        if (!isParsed)
            throw new Exception("Error! Incorrect scaling factor - " + scalingFactor + ".");

        return percent / 100.0f;
    }

    /// <summary>
    /// Implementation of the GetBarCodeImage() method for IBarCodeGenerator interface.
    /// </summary>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public Image GetBarcodeImage(BarcodeParameters parameters)
    {
        if (parameters.BarcodeType == null || parameters.BarcodeValue == null)
            return null;

        BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR);

        string type = parameters.BarcodeType.ToUpper();

        switch (type)
        {
            case "QR":
                generator = new BarcodeGenerator(EncodeTypes.QR);
                break;
            case "CODE128":
                generator = new BarcodeGenerator(EncodeTypes.Code128);
                break;
            case "CODE39":
                generator = new BarcodeGenerator(EncodeTypes.Code39Standard);
                break;
            case "EAN8":
                generator = new BarcodeGenerator(EncodeTypes.EAN8);
                break;
            case "EAN13":
                generator = new BarcodeGenerator(EncodeTypes.EAN13);
                break;
            case "UPCA":
                generator = new BarcodeGenerator(EncodeTypes.UPCA);
                break;
            case "UPCE":
                generator = new BarcodeGenerator(EncodeTypes.UPCE);
                break;
            case "ITF14":
                generator = new BarcodeGenerator(EncodeTypes.ITF14);
                break;
            case "CASE":
                generator = new BarcodeGenerator(EncodeTypes.None);
                break;
        }

        if (generator.BarcodeType.Equals(EncodeTypes.None))
            return null;

        generator.CodeText = parameters.BarcodeValue;

        if (generator.BarcodeType.Equals(EncodeTypes.QR))
            generator.Parameters.Barcode.CodeTextParameters.TwoDDisplayText = parameters.BarcodeValue;

        if (parameters.ForegroundColor != null)
            generator.Parameters.Barcode.BarColor = ConvertColor(parameters.ForegroundColor);

        if (parameters.BackgroundColor != null)
            generator.Parameters.BackColor = ConvertColor(parameters.BackgroundColor);

        if (parameters.SymbolHeight != null)
        {
            generator.Parameters.ImageHeight.Pixels = ConvertSymbolHeight(parameters.SymbolHeight);
            generator.Parameters.AutoSizeMode = AutoSizeMode.None;
        }

        generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.None;

        if (parameters.DisplayText)
            generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below;

        generator.Parameters.CaptionAbove.Text = "";

        const float scale = 2.4f; // Empiric scaling factor for converting Word barcode to Aspose.BarCode
        float xdim = 1.0f;

        if (generator.BarcodeType.Equals(EncodeTypes.QR))
        {
            generator.Parameters.AutoSizeMode = AutoSizeMode.Nearest;
            generator.Parameters.ImageWidth.Inches *= scale;
            generator.Parameters.ImageHeight.Inches = generator.Parameters.ImageWidth.Inches;
            xdim = generator.Parameters.ImageHeight.Inches / 25;
            generator.Parameters.Barcode.XDimension.Inches =
                generator.Parameters.Barcode.BarHeight.Inches = xdim;
        }

        if (parameters.ScalingFactor != null)
        {
            float scalingFactor = ConvertScalingFactor(parameters.ScalingFactor);
            generator.Parameters.ImageHeight.Inches *= scalingFactor;

            if (generator.BarcodeType.Equals(EncodeTypes.QR))
            {
                generator.Parameters.ImageWidth.Inches = generator.Parameters.ImageHeight.Inches;
                generator.Parameters.Barcode.XDimension.Inches =
                    generator.Parameters.Barcode.BarHeight.Inches = xdim * scalingFactor;
            }

            generator.Parameters.AutoSizeMode = AutoSizeMode.None;
        }

        return generator.GenerateBarCodeImage();
    }

    /// <summary>
    /// Implementation of the GetOldBarcodeImage() method for IBarCodeGenerator interface.
    /// </summary>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public Image GetOldBarcodeImage(BarcodeParameters parameters)
    {
        if (parameters.PostalAddress == null)
            return null;

        BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Postnet)
        {
            CodeText = parameters.PostalAddress
        };

        // Hardcode type for old-fashioned Barcode
        return generator.GenerateBarCodeImage();
    }

    /// <summary>
    /// Parses an integer using the invariant culture. Returns Int.MinValue if cannot parse.
    /// 
    /// Allows leading sign.
    /// Allows leading and trailing spaces.
    /// </summary>
    public static int TryParseInt(string s)
    {
        return double.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out double temp)
            ? CastDoubleToInt(temp)
            : int.MinValue;
    }

    /// <summary>
    /// Casts a double to int32 in a way that uint32 are "correctly" casted too (they become negative numbers).
    /// </summary>
    public static int CastDoubleToInt(double value)
    {
        long temp = (long)value;
        return (int)temp;
    }

    /// <summary>
    /// Try parses a hex String into an integer value.
    /// on error return int.MinValue
    /// </summary>
    public static int TryParseHex(string s)
    {
        return int.TryParse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int result)
            ? result
            : int.MinValue;
    }
}

@alexey.noskov, I am using the same custom barcode generator code along with below code to test.
however I am not getting actual barcode value from BarCode_Data.xml. I have attached BarCode_Data.xml and template file(Sample_Template_PageNumber.xml) for reference.
sampleFiles.zip (741.2 KB)
OupputPDf1.zip (27.3 KB)

[Test]
public static void BarcodeTest()
{
    Aspose.Words.License licenseWords = new Aspose.Words.License();
    licenseWords.SetLicense(@"C:\Vijay\LatestAspose\LatestAspose\Aspose.Words Vs OpenXML Words\Aspose.Words VS OpenXML\Aspose.Words.NET.lic");

    DataSet pizzaDs = new DataSet();
    pizzaDs.ReadXml(MyDir + "BarCode_Data.xml");

    Document doc = new Document(MyDir + "Sample_Template_PageNumber.xml");
    DocumentBuilder builder = new DocumentBuilder(doc);

    doc.MailMerge.Execute(pizzaDs.Tables[0]);
    doc.MailMerge.ExecuteWithRegions(pizzaDs.Tables[1]);

    doc.FieldOptions.BarcodeGenerator = (new CustomBarcodeGenerator());

    doc.Save(ArtifactsDir + "Sample.pdf", SaveFormat.Pdf);
}

@vbhasker If you need to use barcode value from your data source, you can put a merge field into the DISPLAYBARCODE field:
{ DISPLAYBARCODE "{ MERGEFIELD field }{ PAGE }" QR }

@alexey.noskov
Thanks for your quick reply!.
The below syntax is working to get current page number along with actual bar code value.
however same syntax is not working with MERGEBARCODE.

logic that is working
=====================
{DISPLAYBARCODE "{MERGEFIELD field}{PAGE }" QR }
logic that is not working
=========================
{MERGEBARCODE "{MERGEFIELD field}{PAGE }" QR }

So can you please confirm that this logic will work only with DISPLAYBARCODE tag and not MERGEBARCODE?
I have attached sample template and output pdf with both syntax in template for reference.
testFiles.zip (761.3 KB)

@vbhasker MERGEBARCODE field works as a regular merge field, i.e. its parameter is a field name. Field example if in the document there is field like this:
{ MERGEBARCODE test QR }
barcode value should be in test field value in the data source:

Document doc = new Document(@"C:\Temp\in.docx");
doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();
doc.MailMerge.Execute(new string[] { "test" }, new string[] { "1234567890" });
doc.Save(@"C:\Temp\out.pdf");

Upon executing mail merge MERGEBARCODE field is converted to DISPLAYBARCODE field with the corresponding value. So in your case if it is require to construct barcode value from several fields, you should use DISPLAYBARCODE field with nested fields.

@alexey.noskov
Thanks for your confirmation on display barcode vs merge barcode.
The below syntax works for single document but we have one more requirement to have rolling page number in a batch process along with current page number.

Can you please let us know how we can do it?

Scenario example :

If my batch has 10 documents (each doc has 3 pages) to be appended ,
on my 4th document below is the expectation

Page 1
Bar code value + 10 (Rolling Page Number ) + 1 (Current Page Number)
Page 2
Bar code value + 11 (Rolling Page Number) + 2 (Current Page Number)
Page 3
Bar code value + 12 (Rolling Page Number ) + 3 (Current Page Number)

So, how to get the rolling page number along with current page number on each document page?

Appreciate your help.

Thanks
–Vijay

@vbhasker If each of your documents contains only one section, then you can specify PageSetup.RestartPageNumbering property and use PAGE field for "Current Page Number" and calculate "Rolling Page Number' using formula and “SECTION” field. Something like this:
{ DISPLAYBARCODE "{={MERGEFIELD field}+{=({SECTION}-1)*3+{PAGE}}+{PAGE }}" QR }

@alexey.noskov
Can you please tell me how to edit a merge field value in a header of a word document so that I can put a different value in each page?

Scenario Example:
{MergeField Sample}
Page 1 :
ABC00011101
Page 1 :
ABC00011102
Page 3 :
ABC00011103

The merge field value will be calculated internally and we want to replace it in the document based on current page number and total page count. Please suggest.

Thanks
–Vijay

@vbhasker I am afraid, there is no way to put different values of merge field on each page in page header. the only way is to have different section per page and each section should have it’s own header and different merge fields.
PAGE field on other hand is an exception, since it’s value depends on the page. Other content in the header/footer is repeated on each page.

@alexey.noskov

How can we concatenate values - give example with conditional expression

Scenario Example

Is there a way to give displaybarcode value as
Mergefield1 concatenate mergefield2 concatenate PAGE
Here mergefield2 will be a IF condition
Is this possible?

Appreciate your help.

Thanks
–Vijay

@vbhasker Sure you can use IF field for conditions in MS Word. For example see the following field code:
{ DISPLAYBARCODE "{MERGEFIELD field1}{MERGEFIELD field2}{PAGE}{IF "{MERGEFIELD field1}" = "0" "trueValue" "falseValue"}" QR }