Печать штрих-кода в отчетах Microsoft Dynamics NAV с использованием ActiveХ
Вступительное слово:
Как только я закончил писать первую статью, стало необходимо получить отчет, из Microsoft Dynamics NAV в котором был необходим двухмерный штрих-код PDF417, причем с возможностью как горизонтальной, так и вертикальной ориентацией Штрих-кода в отчетах Microsoft Dynamics NAV. Для успешного выполнения поставленной задачи необходимо использовать ActiveХ. Данными свойствами обладает компонента ActiveBarcode (http://www.activebarcode.com/) стоимость этой OCX компоненты 699 EUR.
Для демонстрации печати штрих-кода в отчетах Microsoft Dynamics NAV будем использовать демонстрационную версию ActiveBarcode. Я преднамеренно в архив примера положил только используемые файлы, а не весть дистрибутив ActiveBarcode, Вы всегда можете скачать полный дистрибутив с сайта разработчиков этой компоненты.
(К стати, есть идея написать, свой ActiveХ с подобными свойствами, тем более есть опыт написания для FastReport’а аналогичного компонента, если у кого ни будь есть желание помочь, свяжитесь со мной.)
Что получилось:
Как и в первой статье, сразу же перейду к тому, что у меня получилось.
Описание ActiveBarcode:
В кратком изложении опишу компоненту ActiveBarcode, более подробная документация находится на сайте разработчиков.
ActiveBarcode поддерживает следующие типы штрих-кодов.
OCX: Properties (Свойства)
| Name | Type | Description | read-only |
| Text | char | Text contains the content of the barcode. General without check digit. | - |
| ShowText | bool | TRUE: The barcode has a human readable text. (default) FALSE: The barcode is displayed without the text. |
- |
| Type | long | Specifies the barcode type. (*) | - |
| Rotate | long | Rotate contains the orientation of the displayed barcode in degreess (0,90,180,270). | - |
| Alignment | AlignConstants | Alignment sets the alignment (on the left, on the right, centered) of the barcode. You can pass AlignLeft, AlignCenter or AlignRight. | - |
| TypeName | char | Contains the name of the barcode type. | - |
| IsValid | bool | Returns TRUE if the barcode is valid. If it’s invalid, the text cannot be coded with the selected barcode type. | read-only |
| IsSizeOk | bool | Returns TRUE if the barcode is displayed correct. If it’s FALSE, the barcode cannot be displayed because the controls dimensions are too small to display the barcode correct. | read-only |
| Checksum | long | Returns the check digit. | read-only |
| Picture | pictureobject | Returns the barcode picture. | read-only |
| BackColor | OLE_Color | Background color of the barcode. | - |
| ForeColor | OLE_Color | Foreground color of the barcode. | - |
| Font | fontobject | Specifies the font by name, style, effects and the size for the text line. | - |
| Version | char | Returns the controls version number. | read-only |
| BorderHeight | long | BorderHeight sets the height of the border above and under the barcode in pixels. The border is painted in the current background color (BackColor). | - |
| BorderWidth | long | BorderWidth sets the width of the border on the left and the right of the barcode in pixels. The border is painted in the current background color (BackColor). | - |
| MaxBorderHeight | long | MaxBorderHeight returns the maximum possible value of BorderHeight. | read-only |
| MaxBorderWidth | long | MaxBorderWidth returns the maximum possible value of BorderWidth. | read-only |
| NotchHeightInPercent | long | Sets the length of the notches in percent. | - |
| PrintFix | bool | If you have the problem that the bars of the code are too thin when printing (i.e. with Excel), set this property to true. | - |
| AutoType | bool | This property should not be used. It’s only implemented for compatibility purposes to old versions. ActiveBarcde tries to detect the barcode type automatically | - |
OCX: Events (События)
| Name | Parameter | Description |
| TypeChange | BarcodeType:long | Is triggered when the barcode type is changed. The property Type is passed and can be used. |
| TextChange | Text:char | Is triggered when the barcode text is changed. The property Text is passed and can be used. |
| ShowTextChange | ShowText:bool | Is triggered when the display of the barcode text enabled or disabled. The property ShowText is passed and can be used. |
| AutoTypeChange | AutoType:bool | Is triggered when the Autotype option is enabled or disabled. The property Autotype is passed and can be used. |
| PrintFixChange | PrintFix:bool | Is triggered when the PrintFix option is enabled or disabled. The property PrintFix is passed and can be used. |
OCX: Methods (Методы)
| Name | Parameter | Description |
| CopyToClipboard | : bool | Copies the barcode in meta graphic format to the clipboard. Returns TRUE if successful. |
| CopyToClipboardBySize | (Width: Integer, Height: Integer): Bool | Copies the barcode in meta graphic format to the clipboard. The size of the barcode is specified by the arguments width and height. Returns TRUE if successful. |
| CreatePictureBySize | (Width: Integer, Height: Integer): Bool | Allows a custom sized Picture property to be handled. The size of the barcode picture is specified by the arguments width and height. Returns TRUE if successful. |
| SaveAs | (path: WideString): Smallint | Saves the current barcode as image file (BMP, JPEG, PNG, TIFF, Targa, GIF, WMF, EMF, PBM, PGM, PPM, WBMP and XPM). The image size is the current size of the control. The image file type used is defined by the extension of the file name (e.g. BMP for a Windows Bitmap). |
| SaveAsBySize | (path: WideString, Width: Integer, Height: Integer): Smallint | Saves the current barcode as image file (BMP, JPEG, PNG, TIFF, Targa, GIF, WMF, EMF, PBM, PGM, PPM, WBMP and XPM). The image size is specified by the parameters width and height. The image file type used is defined by the extension of the file name (e.g. BMP for a Windows Bitmap). |
| SaveAsBySizeExtended | (path: WideString, Width: Integer, Height: Integer, Format: Integer, ColorDepth: Integer, Transparent: Integer, Flags: Integer, Angle: Integer, DPI: Integer): Smallint | Extended version of the SaveAsBySize Method. |
| SetDemoText | - | Sets the property Text to a valid default value. Use this for demonstration or test purposes to get a valid code. |
| BinaryWriteAsPNGBySize | (Width: Integer, Height: Integer): OleVariant | Returns the current barcode in binary PNG image format. The size is specified by Width and Height parameters. This method is only available in the Enterprise Edition. |
| BinaryWriteAsPNG | : OleVariant | Returns the current barcode in current size binary PNG image format. This method is only available in the Enterprise Edition. |
| AboutBox | - | Opens the info dialog of ActiveBarcode and shows Version and other details. |
| SaveAsPNG | (path: WideString): Smallint | Saves the current barcode as PNG image file. The image size is the current size of the control. |
| SaveAsPNGBySize | (path: WideString, Width: Integer, Height: Integer): Smallint | Saves the current barcode as PNG image file. The image size is specified by the paramters width and height. |
Описание примера:
Первоначальная идея заключается в том, что бы с помощью ActiveBarcode получить картинку с изображением нужного нам типа штрих-кода и потом его импортировать в отчет.
Для того чтобы пример заработал, необходимо распаковать архив с примером и зарегистрировать в системе OCX ActiveBarcode. Для это запустите Register.bat, командный файл, для регистрации в системе OCX ActiveBarcode. Так же Вам необходимо импортировать тестовые объекты Navision в Вашу систему.
Объект Форма (50510 Test Barcode OCX) которая по своей сути является Формой ввода данных, нужно внести Номер записи, Расположение (0: Горизонтальная ориентация Штрих-кода, 90: Повернутое на 90 градусов по часовой стрелке, 180: Повернутое на 180 градусов по часовой стрелке, 270: Повернутое на 270 градусов по часовой стрелке), Тип штрих-кода, и Данные, которые будут кодироваться в штрих-коде. Внимание, корректность штрих-кода не проверяется при вводе, но в принципе корректность штрих-кода можно проверить с помощью ActiveBarcode для этого есть свойство IsValid и Checksum. Так же что бы проверить соответствие штрих-кода спецификациям воспользуйтесь программой ActiveBarcodeApp.exe.
Весь алгоритм формирования отчета находится в объекте Репорт (50510 Test Barcode OCX). Я его очень хорошо прокомментировал, надеюсь, что у читателя не возникнет затруднений понять логику работы.
//====================================================================// // ActiveBarcode OCX for Microsoft Dynamics NAV version 5.1 or later // // Version 1.0 // // Date 02/02/2009 // // Copyright Oleg Leontyev AKA LOGic_BBS 2009 // // E-mail: oleg_leontev@mail.ru // // ICQ: 171341703 // // WWW: www.logic-pfr.narod.ru // // This is a freeware! Use at own risk! // //====================================================================// Test Barcode OCX - OnAfterGetRecord() _ActiveBarcode.ShowText(TRUE); // Выводить текстовое значение штрих-кода в коде. (default TRUE). _ActiveBarcode.Font.Size(11); // Размер шрифта текстового значения в штрих-коде. // Доступны все свойства шрифта. // ************************************************************************// // Ориентация штрих-кода на отчете. // CASE FORMAT("Test Barcode OCX".Rotate) OF '0': _ActiveBarcode.Rotate(0); // Горизонтально '90': _ActiveBarcode.Rotate(90); // Повернутое на 90 градусов по часовой стрелке '180': _ActiveBarcode.Rotate(180); // Повернутое на 180 градусов по часовой стрелке '270': _ActiveBarcode.Rotate(270); // Повернутое на 270 градусов по часовой стрелке END; // ************************************************************************// // Данные для штрихового кодирования с контрольной суммой если контрольная // сумма описана в спецификации. // _ActiveBarcode.Text("Test Barcode OCX".Text); // ************************************************************************// // Тип Штрих-кодов: // Codabar,Code 25 Industrial,Code 25 Interleaved,Code 39,Code 39 Extended,Code 93,Code 93 Extended, // Code 128,Code 128A,Code 128B,Code 128C,Data Matrix,DUN-14,EAN-2,EAN-5,EAN-8,EAN-13,EAN-14, // EAN-18,EAN 99,EAN-128,EAN Velocity,GS1-128,Identcode,ISBN,-ISBN-10,,-ISBN-13,-ISBN-13 Dual, // ISSN,ISMN,ITF-14,JAN,Leitcode,MSI Plessey,NVE,PDF 417,PostNet,PZN,RoyalMail,SCC-14,SSCC-18, // UCC-128,UPC-A,UPC-E // _ActiveBarcode.TypeName(FORMAT("Test Barcode OCX".Type)); // ************************************************************************// // Генерируем картинку со Штрих-кодом с параметрами Width (Ширина) = 100 Height // (Высота) = 300 для вертикального размещения на отчете // и с параметрами Width (Ширина) = 300 Height (Высота) = 100 для горизонтального. // IF (FORMAT("Test Barcode OCX".Rotate) = '90') OR (FORMAT("Test Barcode OCX".Rotate) = '270') THEN _ActiveBarcode.SaveAsBySize((ENVIRON('USERPROFILE')+'\LOCALS~1\Temp\picture.bmp'), 100, 300) ELSE _ActiveBarcode.SaveAsBySize((ENVIRON('USERPROFILE')+'\LOCALS~1\Temp\picture.bmp'), 300, 100); // ************************************************************************// // Импортируем картинку в базу, для последующей печати. // Picture.IMPORT((ENVIRON('USERPROFILE')+'\LOCALS~1\Temp\picture.bmp'));
На что еще хочется обратить внимание, уважаемого читателя. Мне ужасно не нравятся вот такие «информативные» сообщения.
Что бы пользователь получил, нормальное, читаемое сообщение о том что в системе не зарегистрирована ActiveХ ActiveBarcode, написана следующая функция.
IsActiveBarcodelRegistered(Hard : Boolean) : Boolean // Функция проверки установлена ли в системе OCX ActiveBarcode // IsActiveBarcodelRegistered(Hard : Boolean); // IF ActiveBarcodelRegistered THEN EXIT(TRUE); ActiveBarcodelRegistered := OLEControl.GET('{8A04E844-F5EF-11CF-8939-444553540000}'); IF Hard AND NOT ActiveBarcodelRegistered THEN ERROR(Text001); EXIT(ActiveBarcodelRegistered);
Теперь, если в системе не зарегистрирован ActiveХ ActiveBarcode пользователь получить читаемое сообщение об ошибке.
Реализацию этой функции можно посмотреть в Форме (50510 Test Barcode OCX).
Описание архива:
Содержимое ActiveBarcode.zip
- Active Barcode OCX.JPG – Отчет Microsoft Dynamics NAV.
- ActiveBarcodeApp.exe – Программа для тестирования штрих-кодов.
- Barcode.ocx – ActiveХ ActiveBarcode.
- Register.bat – Командный файл для регистрации в системе OCX ActiveBarcode.
- UnRegister.bat – Командный файл для разрегистрирования OCX ActiveBarcode.
- Barcode OCX Nav_51.fob – Объекты в фобах для Microsoft Dynamics_NAV 5.1.
- Barcode OCX.txt – Объекты в тексте Microsoft Dynamics_NAV.
Благодарности:
Моей жене, за то, что до сих пор меня любит.
Об авторе:
Олег Леонтьев.
AKA LOGic_BBS
Со мной всегда можно связаться по адресу oleg_leontev@mail.ru или посетите мой сайт http://www.logic-pfr.narod.ru
Метки: Олег Леонтьев










































