How can I select label print quantity from database in NiceLabel?
Selecting print quantity from database in NiceLabel Pro is quite easy.
- Run NiceLabel and create new label.
- Add new database by selecting “Data Access…” option in the “Data” menu to open the “Data Access Functions” dialog box.
- Once in the “Data Access Functions” dialog box, click the “New” button to open the”Database Access” dialog box.
- Define or browse for the database.
- Once you have selected the database you would like to use, go to the “Fields” tab and select fields you need.
- Go to “Data Retrieving” page.
- In the section “Number of Labels per Record”, select “Number of labels is defined at print time” and then “stored in a database field”.
- Select the database field that contains the quantity.
- Click OK to close the “Database Access” window.
- Click Close to close the “Database Access” window.
- Add objects to the label and save the label.
- When you start printing and the “Print” dialog is shown, you will see that the “Variable quantity (defined from database field)” option is selected.
How can I automate NiceLabel from a scripting language like VBScript or Python?
You can find two examples of automating NiceLabel from a scripting language. The first one is in VBScript and the other one in Python. Both samples do the same thing: run NiceLabel, open label file, iterate through a list of variables, set their values and print the label. At the end label is closed and NiceLabel shuts down.
Set nice = CreateObject("NiceLabel5.Application")
If (nice is Nothing) Then
MsgBox("Cannot open NiceLabel!")
Else
fileName = "c:\Labels\Sample.lbl"
Set lbl = nice.LabelOpenEx(fileName)
If (lbl is Nothing) Then
MsgBox("Cannot open '" & fileName & "'!")
Else
Set variables = lbl.Variables
For i = 1 to variables.Count
Set variable = variables.Item(i)
' Use only prompt variables that require prompt.
If (variable.VarType = 1) and (variable.DefType <> 2) Then
MsgBox(variable.Name)
variable.SetValue("Value" & CStr(i))
End if
' Release interface to variable.
Set variable = Nothing
Next
'Set printer
lbl.PrinterName = "Altec TTP-343 Plus"
' Print 1 label
quantity = "1"
lbl.Print(quantity)
' Release interface to variables list.
Set variables = Nothing
' Release interface to label to close it
Set lbl = Nothing
End If
' Close NiceLabel
nice.Quit
Set nice = Nothing
End if
And the same thing in Python.
import win32com.client
import os.path
# Run NiceLabel
nice = win32com.client.Dispatch("NiceLabel5.Application")
if (nice == None):
error = "Cannot open NiceLabel";
else:
fileName = os.path.normpath("c:/Users/alesp/Documents/My Labels/Labels/Sample.lbl");
lbl = nice.LabelOpenEx(fileName);
if (lbl == None):
error = "Cannot open '{0}'".format(fileName);
else:
variables = lbl.Variables;
for i in range (1, variables.Count + 1):
variable = variables.Item(i);
if (variable.VarType == 1) and (variable.DefType <> 2):
variable.SetValue("Value" + str(i));
# Release interface to variable.
variable = None;
# Set printer
#lbl.PrinterName = "Altec TTP-343 Plus";
# Print 1 label
quantity = "1";
lbl.Print(quantity);
# Release interface to variables list.
variables = None;
# Release interface to variables list and close label.
lbl = None;
nice.Quit();
nice = None;
Please note that these samples will only work on a desktop and not in NiceLabel Portal in a browser. You will also need to have NiceLabel 5 installed.
For more information about automating NiceLabel see the NiceLabel Programming Guide (PDF).
Working with Strings in Python Scripts in NiceForm and NiceLabel Portal
Strings are the basic unit of text in Python. Either single or double quotes can be used to quote strings. This can be useful in some cases:
s1 = "Let's go!" s2 = '"NiceLabel is the best!", she said.'
Special characters need to be escaped. Likely the most common special character you will encounter is the newline '\n'. Some of other special characters are:
\\ Backslash (\)
\" Double quote (")
\' Single quote (')
\n ASCII linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
In NiceForm version 5.2.3 (that uses Python 2.7) Python string constants are by default ASCII (single byte) strings. Basically this means that they are just a sequence of bytes. If you want to use define Unicode string literal you need to use the ‘u’ or ‘U’ prefix:
s1 = u"čćšđž" s2 = U"НИГЕЛАБЕЛ"
NiceForm variable values are already Unicode enabled so you do not have to do anything. The same goes for scripts running in NiceLabel Portal. Because NiceLabel Portal uses IronPython (that is implemented on .NET Framework) it means that all strings are Unicode strings.
Basic Operations
Strings can be concatenated (glued together) with the + operator, and repeated with *:
s = ""NiceLabel" + " " + "is the best!" # "NiceLabel is the best!" s2 = "Nice" * 3 # "NiceNiceNice"
To see if two strings are equal use the "==" operator. Other comparison operations are useful for putting words in alphabetical order. You should be aware though that Python does not handle uppercase and lowercase letters the same way people do. All the uppercase letters come before all the lowercase letters.
word = variable.Value
if word == "NiceLabel":
result.Value = "Your word is NiceLabel."
elif (word < "NiceLabel"):
result.Value = "Your word comes before NiceLabel."
elif (word > "NiceLabel"):
result.Value = "Your word comes after NiceLabel."
Sometimes it might be tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example:
s = "NiceLabel" s[0] = 'M'
This code will not work because the strings in Python are immutable, which means that you cannot change an existing string. The best you can do is create a new string that is a variation of the original one:
s = "NiceLabel" s2 = 'M' + s[1:]
If you need to count the number of characters in a string use the len() function:
len("NiceForm") # Returns 8.
To convert any data type to string use the str() function:
f = 123.56 result.Value = str(f)
String Slices
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
s = "NiceLabel, NiceForm and NiceLabel Portal" print s[0:9] # NiceLabel print s[11:19] # NiceForm print s[24:41] # NiceLabel Portal
The operator [n:m] returns the part of the string from the "n-eth" character to "m-eth" character, including the first but excluding the last. If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string.
s[:9] # NiceLabel s[24:] # NiceLabel Portal
Working with cases
There are several functions that allow you to work with character case.
s = "NiceLabel Portal" # String converted to lower case. lowercase = s.lower() # "nicelabel portal" # String converted to upper case. uppercase = s.upper() # "NICELABEL PORTAL" # String converted to title case. titlecase = s.title() # "Nicelabel Portal" # Make all lowercase letters uppercase and vice versa. swapcase = s.swapcase() # "nICElABEL pORTAL" # The capitalize method is like title except that it considers the # entire string to be a word. (i.e. it makes the first character # upper case and the rest lower case). capitalcase = s.capitalize() # "Nicelabel portal"
Searching for substrings
The find() method finds a substring within a larger string. It returns the leftmost index where the substring is found. If it is not found, –1 is returned. For searching in strings you can also use startswith(), endswith(), rfind(), count() and replace() methods. See attached files for more details.
Stripping
strip(), lstrip() and rstrip() methods can be used to remove characters you do not want in the string:
word = "999aaa999"
stripped = word.strip('9') # returns "aaa"
lstripped = word.lstrip('9') # returns "aaa999"
rstripped = word.rstrip('9') # returns "999aaa"
Checking Character Types
To check if a string contains a certain type of characters, use the following methods:
- isalnum(): Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
- isalpha(): Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
- isdigit(): Returns true if string contains only digits and false otherwise.
- islower(): Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
- isspace(): Returns true if string contains only whitespace characters and false otherwise.
- istitle(): Returns true if string is properly "title cased" and false otherwise.
- isupper(): Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
- isnumeric(): Returns true if string contains only numeric characters and false otherwise.
Padding strings
center() method returns a string that is centered in a string of a defined length. Padding is done using the specified fill character. ljust() returns the string left justified in a string of specified length. Similarly goes for rjust().
word = "abcd" # " abcd " centered = '"' + word.center(10, ' ') + '"' # "abcd " l = '"' + word.ljust(10, ' ') + '"' # " abcd" r = '"' + word.rjust(10, ' ') + '"'
String Substitution
There are a few different ways to produce a string with information that is only available at run-time. The most obvious way is to concatenate multiple strings together using the + operator, but that only works if all the values are strings. As an alternative, Python also supports a way to inject objects into a string. This uses placeholders inside a string to denote where objects should go, along with a list of objects that should fill them in. This is called string substitution, and is performed using the % operator.
Placeholders consist of a percent sign and a conversion format. This allows the string to specify how objects should get converted, rather than having to call separate function explicitly. The most common of these formats is %s, which is equivalent to the str() function.
'This object is %s' % 1 # is equivalent to 'This object is 1'
Formatting
For a more powerful alternative to the simple string substitution described in the previous section, Python also includes a robust formatting system for strings. Rather than relying on a less obvious operator, string formatting uses an explicit format() method on strings. In addition, the syntax used for the formatting string is considerably different from what was used in simple substitution previously.
Instead of using a percent sign and a format code, format() expects its placeholders to be
surrounded by curly braces. What goes inside those braces depends on how you plan to pass in the values and how they should be formatted. The first portion of the placeholder determines whether it should look for a positional argument or a keyword argument. For positional arguments, the content is a number, indicating the index of the value to work with, while for keyword arguments, you supply the key that references the appropriate value.
s = "{0} and {1} are the best!"
s = s.format("NiceLabel", "NiceForm")
# NiceLabel and NiceForm are the best!
You can find all the samples here
NiceLabel Portal
We have announced NiceLabel Portal today. I am very excited about this product because it brings powers of NiceLabel and NiceForm to the web. NiceLabel Portal allows running complex (or simple) labeling applications created by NiceLabel and NiceForm.
Here are two samples of such applications. First video shows a simple form where user can select a record from a database, set date, define whether she wants to print a logo on the label, select a printer and print the one of two label designs.
Second sample shows that even applications that do not print can be created.
For the client side of NiceLabel Portal you will have to have the latest version of Silverlight 4, Internet Explorer 7 or newer (32-bit version) and you also have to install a small ActiveX component that allows communication with printers. For installing ActiveX component on Windows XP you will have to have administrator privileges.
Since this is version 1 of the product not full functionality of NiceLabel and NiceForm was implemented.On the label you can use Text, Text Box, Bar code, Picture, Rectangle and Line objects. The following barcode symbologies can be used: EAN-8, EAN-13, UPC-A, UPC-E, UPC-E(1), GS1-128 (EAN-UCC 128), Code 39, CODE-128 (A, B and C subsets), PDF 417, DataMatrix and QR. For pictures you can use .JPG or .PNG files.”Concatenate”, “Subset”, “Linear”, “GS1-128”, “Date addition”, “ASC (FACT)”, “Link to file” functions can also be used. To make label designs flexible prompt variables, counters, date and time variables and global variables can be used. Properties like prefix, suffix, padding character can also be used.
For designing forms all objects except Button Group can be used: Frame, Text, Picture, Edit Field, Memo Field, Button, List Box, Combo Box, Check Box, Radio Group, Variable Prompt, Database Search, Database Navigator, Table and Preview. Also almost all actions were implemented: “Open label”, “Print label”, “Set printer”, “Set variable”, “Load variable data”, “Save variable data”, “For every record in a table”, “For loop”, “Refresh database”, “Execute SQL statement”, “Import data into database”, “Send data to TCP/IP” port, “Open another form”, “Open document/program” (with limitations), “Quit” and “Execute script”. Since Visual Basic script is not supported in Silverlight, Python is now used as a scripting language in forms.
All printers with Windows drivers can be used for printing.
NiceLabel Portal supports Unicode encoding so you can create multi-lingual form and label designs. You can also use any Windows font during label or form design but you have to make sure that all used fonts are also installed on client computers. If a font cannot be found, Arial font will be used.
Of course databases can also be used (see the first video). We recommend using “real” databases like Microsoft SQL server or Oracle, although text (CSV) files and databases that have OLE DB drivers (like Microsoft Excel, Microsoft Access, Microsoft SQL Server, Oracle, etc.) are also supported.
For the end I would like once again repeat that I am very proud and excited about NiceLabel Portal because it is very solid, stable product that can solve lots of problems that our existing and future customers have.
Variables in NiceLabel – Part 2
How can I create new variable?
There are several ways you can create new variable:
- Go to the “Variables” dialog box by selecting “Variables” option in the “Data” menu. You have two possibilities here. You can use the “Wizard” button. This will open “Variable Wizard” where you can easily create new variable. Or you can click the “New…” button that will open “Variable” dialog box. Using dialog box gives you complete control of how variable should behave. Note the “Advanced >>” button in the bottom left corner. Clicking this button allows you to see all properties you can set for a variable.
“Variable Wizard”:
“Variable” dialog box:
- You can use “Variables” drop down button in the “Standard” toolbar just below the menu bar in the main NiceLabel window. Selecting one of the four options (“Keyboard Input”, “Counter”, “Date”, “Time”) will open “Variable Wizard” with predefined settings for selected variable type.
- If you have “Variable” toolbar enabled (in the main window in NiceLabel) you can click either “Variable Wizard” (the one with the magic wand) or “New Variable” button.
- You can also use drop down menu in the “Toolbox” menu next to the object name. Almost all objects (except Line, Rectangle and Inverse) allow this.
Of course some variables are created automatically when you define new database or as an output result of a function.
Variables in NiceLabel – Part 1
What is variable?
Variable is a facility for storing data. The current value of the variable is the data actually stored in the variable. In NiceLabel variable can be used in many places: as a source of value for objects that are used as part of label design, in database filters, in functions and scripts. Variables allow you to design flexible and reusable labels.
What types of variables are there?
Depending on source of variable value there are several different types of variables in NiceLabel:
- Prompt variable
- Database variable
- System clock (date or time) variable
- Printer clock (date or time) variable
- Global variable
- Pick List
- Internal variable
- As you can see from the screenshot below you can distinguish them also by the icon in front of variable name.
Prompt variable
Prompt variable is a variable that requires from user to enter or confirm its value before printing. This is the most used type of variables. Variables of this type can also be set from NiceForm, NiceWatch and NicePrint or from your own application if you are using NiceLabel SDK.
Database variable
Database variable is variable that gets its value from database field. It is created automatically when user selects field from a database table.
System clock (date or time) variable
"System clock" variable is a variable that gets its value from the computer system clock. Because of this data format of such variable can only be date or time.
Printer clock (date or time) variable
"Printer clock" variable is similar to "System clock" variable but it gets its value from the thermal printer. If printer label is designed for does not support such functionality you will not be able to use it; it is not even available in the list of possible sources for variable.
Global variable
Global variable is a variable that can be used on many different labels. Once it is defined, it is stored outside the current label so it is available for any other label as well. Its last value is stored even after closing the label file and exiting the application. This comes handy for example when continuing serial numbers from previous printing is required. Values of global variables are stored in GLOBALS.TDB file. You can find the file in the "C:\Documents and Settings\All Users\Application Data\EuroPlus\NiceLabel5\System" folder on Windows XP or in the "c:\Users\All Users\EuroPlus\NiceLabel 5\system" folder in Windows Vista and Windows 7. Global variable can only be created manually in the Variable dialog box. Make sure to select Global as the Source for the variable in the General tab. If you copy your label file, which uses global variables to another computer, you also have to copy GLOBALS.TDB file to the new computer. If you miss this step, then NiceLabel won't find appropriate global variable and will notify you of this situation. At the same time a substitute global variable will be created, but last value of old variable will not be known, nor will the correct variable properties be restored. The same global variable is not limited for use on only one label. You can use it on as many labels as you like. Please note, that only one label, using the same global variable, can be printed at a time. When using global variables, they are locked for one label and this prevents more labels to use the same global variable at the same time.
Pick list
When pick list is used as a source for variable you can define a list of values that can be used (no duplicates are allowed). No other values can be used or typed in before printing. This type is useful if you have a small set of possible values that variable can use.
Internal variable
Internal variable gets its value automatically and you can not modify their properties or values. You can only enable or disable them and of course connect them with different objects on the label. In current version of NiceLabel (5.2.2.2865) there are 11 internal variables (in alphabetical order):
- ComputerName: Contains the information about the name of the computer where labels are processed.
- CurrentBatchQuantity: Contains information about the label quantity in the current label batch. The value is reset at beginning of each batch in the printing process.
- DefaultPrinterName: Contains the name of the default printer on the system.
- EPCData: Contains EPC data that will be encoded in the RF tag. This variable contains data only if RFID is enabled.
- LabelFileName: Contains full name of the current label, including the path to the file.
- LabelPrinterName: Contains the name of the printer that is used on the label.
- RequestedQuantity: Contains the quantity of the labels as specified by the user or external application.
- ShortLabelName: Contains the name of the label without the path. Only filename with the extension is returned.
- SystemUserName: Contains the name of the Windows user that is logged in and is running the application.
- TotalQuantityPrinted: Contains the quantity of all unique labels printed. Label copies are not included in this variable, only the number of different labels is.
- UserName: Contains the name of the user that is logged in and is using the application. This variable contains value only when you have enabled user management in NiceLabel.
If you want to see these variables you have to enable them in the “Variables” dialog box (see screenshot above).
How can I programmatically get a preview of a label from NiceLabel?
Getting a preview of a label from NiceLabel is quite easy. All you have to do is call GetLabelPreviewEx method of the INiceLabel interface. GetLabelPreviewEx has 6 parameters:
- file name: full path to the file where NiceLabel will generate image of the label. Extension part of the file name defines which graphics format will be used. You can use .bmp, .jpg, .png or .gif as the file name extension.
- width: width of image (in pixels)
- height: height of image (in pixels)
- label kind: there are 3 possible values that define the kind of label you want preview for; 0 – header label, main label, tail label
- label side: define whether you want to preview front side (use 0 as parameter value) or back side of the label (use 1 as value). Using back side of the label makes sense only if you have label designed as double sided.
- flag that defines whether to show border around preview or not (true or false)
Function will return true if graphics file was successfully created or false it file could not be created.
bool GetLabelPreviewEx(fileName, width, height, labelKind, labelSide, showBorder)
The following code will run NiceEngine, open label and get a preview of the label in a file called “preview.jpg” that is located in “c:\tmp”. Then you can load the image file in a component of your choice.
// Open NiceEngine NiceEngine5WR.NiceApp engine = new NiceEngine5WR.NiceApp(); // Open label NiceEngine5WR.NiceLabel label = engine.LabelOpenEx(“file.lbl”); string previewFileName = @"c:\tmp\preview.jpg"; int width = 640; int height = 480; previewStatus = label.GetLabelPreviewEx(previewFileName, width, height, 1, 0, false);
Label Structure 2.7
New version of Label Structure is now available from NiceLabel ftp server. So what is new?
- Information about number of objects, variables, functions and databases is now available.
- Global variables are now shown in a list of variables.
- Information about the time that is needed to load a label file can be shown. This is sort of a hidden feature, because you have to press CTRL + T, when “Label Info” page is selected.
- Support for changing paths to graphics files was added. This feature can come handy when you have lots of label files with graphics and want to change a location of those file. Usually this would mean opening all label files, changing paths to graphics and saving them. But now you can change them with a few clicks. Select the “Set paths…” option from the “Tools” menu to open a new window:
All you have to do is to enter the old path to the files, new path to files and select all the labels you would like to change. You have to have files in both places (the old and new path) in order for this to work, because paths are checked when label is opened and saved. It is always wise to make a backup of label files first just in case something goes wrong.
How can I programmatically get a list of variables from NiceLabel?
The following piece of code shows how you can programmatically get a list of variables from a label (.lbl) file. For this sample to work you will have to add reference to “niceengine5wr.dll” that is usually installed in the "c:\Program Files\Common Files\EuroPlus Shared\NiceEngine 5" folder. You will also have to compile your application as 32-bit (x86) application even if you want to run it on a 64-bit system, because NiceEngine and NiceLabel are 32-bit applications.
// Open NiceEngine
NiceEngine5WR.NiceApp engine = new NiceEngine5WR.NiceApp();
// Open label
NiceEngine5WR.NiceLabel label = engine.LabelOpenEx(“file.lbl”);
// List of variables where basic information about label variable will be stored.
// For this sample name, length and prompt order will be stored.
IList<Variable> variables = new List<Variable>();
if (label != null)
{
try
{
// Get a list of variables
NiceEngine5WR.IVariableList varList = label.Variables;
try
{
for (int i = 1; i <= varList.Count; i++)
{
NiceEngine5WR.IVar varIntf = varList.Item(i);
if (varIntf != null)
{
try
{
// Use only prompt variables that require prompt.
// Using other types of variables usually does not make sense.
if (varIntf.VarType == 1 && varIntf.DefType != 2)
{
Variable v = new Variable();
v.Name = varIntf.Name;
v.Length = varIntf.Length;
v.PromptOrder = varIntf.PromptOrder;
variables.Add(v);
}
}
finally
{
// Make sure that interfaces are correctly released otherwise you may get errors.
varIntf.Free();
varIntf = null;
}
}
else
{
// Show error
}
}
}
finally
{
varList.Free();
varList = null;
}
}
finally
{
// Close label by releasing the interface.
label.Free();
label = null;
}
}
Variable class definition looks like this:
public class Variable
{
public string Name
{
get;
set;
}
public string Value
{
get;
set;
}
public int Length
{
get;
set;
}
public int PromptOrder
{
get;
set;
}
}
NiceLabel 5.2.2.2865
NiceLabel Standard Series and Developer Series version 5.2.2.2865 have been released today. For more information and link to download page see the following forum announcement.