This commit is contained in:
2025-09-26 22:17:37 +03:00
parent 2216f21c47
commit 1f90602550
14 changed files with 1040 additions and 95 deletions

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

View File

@@ -0,0 +1,288 @@
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using Newtonsoft.Json;
namespace RecticelPrintService
{
public class LabelPrinter
{
private PrintData _labelData;
// Label dimensions in millimeters (80x110mm)
private const float LABEL_WIDTH_MM = 80f;
private const float LABEL_HEIGHT_MM = 110f;
// Convert mm to hundredths of an inch (used by .NET printing)
private float MmToHundredthsOfInch(float mm)
{
return mm * 3.937f; // 1mm = 0.03937 inches, * 100 for hundredths
}
public bool PrintLabel(string printerName, string jsonData)
{
try
{
// Parse JSON data
_labelData = JsonConvert.DeserializeObject<PrintData>(jsonData);
if (_labelData == null)
{
Console.WriteLine("Failed to parse JSON data");
return false;
}
// Set up print document
PrintDocument printDoc = new PrintDocument();
printDoc.PrinterSettings.PrinterName = printerName;
// Check if printer exists
if (!printDoc.PrinterSettings.IsValid)
{
Console.WriteLine($"Printer '{printerName}' not found or not available");
Console.WriteLine("Available printers:");
foreach (string printer in PrinterSettings.InstalledPrinters)
{
Console.WriteLine($" - {printer}");
}
return false;
}
// Set paper size for 80x110mm labels
PaperSize labelSize = new PaperSize("Label 80x110mm",
(int)MmToHundredthsOfInch(LABEL_WIDTH_MM),
(int)MmToHundredthsOfInch(LABEL_HEIGHT_MM));
printDoc.DefaultPageSettings.PaperSize = labelSize;
printDoc.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
// Set print event handler
printDoc.PrintPage += PrintDoc_PrintPage;
// Print the document
printDoc.Print();
return true;
}
catch (Exception ex)
{
Console.WriteLine($"Error printing label: {ex.Message}");
return false;
}
}
private void PrintDoc_PrintPage(object sender, PrintPageEventArgs e)
{
try
{
Graphics g = e.Graphics;
// Define fonts
Font companyFont = new Font("Arial", 10, FontStyle.Bold);
Font headerFont = new Font("Arial", 8, FontStyle.Bold);
Font dataFont = new Font("Arial", 9, FontStyle.Bold);
Font labelFont = new Font("Arial", 7);
Font barcodeFont = new Font("Courier New", 6, FontStyle.Bold);
// Define brushes and pens
Brush textBrush = Brushes.Black;
Pen borderPen = new Pen(Color.Black, 2);
Pen dividerPen = new Pen(Color.Gray, 1);
// Calculate positions (in pixels, 300 DPI assumed)
float dpiX = e.Graphics.DpiX;
float dpiY = e.Graphics.DpiY;
// Convert mm to pixels
float labelWidth = (LABEL_WIDTH_MM / 25.4f) * dpiX;
float labelHeight = (LABEL_HEIGHT_MM / 25.4f) * dpiY;
// Content area (similar to your HTML preview)
float contentX = (3f / 25.4f) * dpiX; // 3mm margin
float contentY = (15f / 25.4f) * dpiY; // 15mm from bottom
float contentWidth = (60f / 25.4f) * dpiX; // 60mm width
float contentHeight = (85f / 25.4f) * dpiY; // 85mm height
// Draw main content border
g.DrawRectangle(borderPen, contentX, contentY, contentWidth, contentHeight);
// Calculate row height
float rowHeight = contentHeight / 10f; // 9 rows + spacing
float currentY = contentY;
// Row 1: Company Header
string companyText = "INNOFA RROMANIA SRL";
SizeF companySize = g.MeasureString(companyText, companyFont);
float companyX = contentX + (contentWidth - companySize.Width) / 2;
g.DrawString(companyText, companyFont, textBrush, companyX, currentY + rowHeight/3);
currentY += rowHeight;
// Horizontal divider after company
g.DrawLine(dividerPen, contentX, currentY, contentX + contentWidth, currentY);
// Row 2: Customer Name
string customerName = _labelData.CustomerName ?? "N/A";
SizeF customerSize = g.MeasureString(customerName, headerFont);
float customerX = contentX + (contentWidth - customerSize.Width) / 2;
g.DrawString(customerName, headerFont, textBrush, customerX, currentY + rowHeight/3);
currentY += rowHeight;
// Horizontal divider after customer
g.DrawLine(dividerPen, contentX, currentY, contentX + contentWidth, currentY);
// Vertical divider (40% from left)
float verticalDividerX = contentX + contentWidth * 0.4f;
g.DrawLine(dividerPen, verticalDividerX, currentY, verticalDividerX, contentY + contentHeight);
// Row 3: Quantity
g.DrawString("Quantity ordered", labelFont, textBrush, contentX + 5, currentY + rowHeight/4);
string quantity = _labelData.Cantitate.ToString();
SizeF qtySize = g.MeasureString(quantity, dataFont);
float qtyX = verticalDividerX + (contentWidth * 0.6f - qtySize.Width) / 2;
g.DrawString(quantity, dataFont, textBrush, qtyX, currentY + rowHeight/4);
currentY += rowHeight;
// Horizontal divider
g.DrawLine(dividerPen, contentX, currentY, contentX + contentWidth, currentY);
// Row 4: Customer Order
g.DrawString("Customer order", labelFont, textBrush, contentX + 5, currentY + rowHeight/4);
string customerOrder = $"{_labelData.ComAchizClient}-{_labelData.NrLinieComClient}";
if (string.IsNullOrEmpty(_labelData.ComAchizClient)) customerOrder = "N/A";
SizeF orderSize = g.MeasureString(customerOrder, dataFont);
float orderX = verticalDividerX + (contentWidth * 0.6f - orderSize.Width) / 2;
g.DrawString(customerOrder, dataFont, textBrush, orderX, currentY + rowHeight/4);
currentY += rowHeight;
// Horizontal divider
g.DrawLine(dividerPen, contentX, currentY, contentX + contentWidth, currentY);
// Row 5: Delivery Date
g.DrawString("Delivery date", labelFont, textBrush, contentX + 5, currentY + rowHeight/4);
string deliveryDate = _labelData.DataLivrare ?? "N/A";
if (!string.IsNullOrEmpty(deliveryDate) && deliveryDate != "N/A")
{
try
{
DateTime dt = DateTime.Parse(deliveryDate);
deliveryDate = dt.ToString("dd/MM/yyyy");
}
catch { }
}
SizeF dateSize = g.MeasureString(deliveryDate, dataFont);
float dateX = verticalDividerX + (contentWidth * 0.6f - dateSize.Width) / 2;
g.DrawString(deliveryDate, dataFont, textBrush, dateX, currentY + rowHeight/4);
currentY += rowHeight;
// Horizontal divider
g.DrawLine(dividerPen, contentX, currentY, contentX + contentWidth, currentY);
// Row 6: Description (double height)
g.DrawString("Description", labelFont, textBrush, contentX + 5, currentY + rowHeight/4);
string description = _labelData.DescrComProd ?? "N/A";
// Word wrap description if needed
RectangleF descRect = new RectangleF(verticalDividerX + 5, currentY + 5,
contentWidth * 0.6f - 10, rowHeight * 2 - 10);
g.DrawString(description, dataFont, textBrush, descRect);
currentY += rowHeight * 2;
// Horizontal divider
g.DrawLine(dividerPen, contentX, currentY, contentX + contentWidth, currentY);
// Row 7: Size
g.DrawString("Size", labelFont, textBrush, contentX + 5, currentY + rowHeight/4);
string size = _labelData.Dimensiune ?? "N/A";
SizeF sizeSize = g.MeasureString(size, dataFont);
float sizeX = verticalDividerX + (contentWidth * 0.6f - sizeSize.Width) / 2;
g.DrawString(size, dataFont, textBrush, sizeX, currentY + rowHeight/4);
currentY += rowHeight;
// Horizontal divider
g.DrawLine(dividerPen, contentX, currentY, contentX + contentWidth, currentY);
// Row 8: Article Code
g.DrawString("Article Code", labelFont, textBrush, contentX + 5, currentY + rowHeight/4);
string articleCode = _labelData.CustomerArticleNumber ?? "N/A";
SizeF artSize = g.MeasureString(articleCode, dataFont);
float artX = verticalDividerX + (contentWidth * 0.6f - artSize.Width) / 2;
g.DrawString(articleCode, dataFont, textBrush, artX, currentY + rowHeight/4);
currentY += rowHeight;
// Horizontal divider
g.DrawLine(dividerPen, contentX, currentY, contentX + contentWidth, currentY);
// Row 9: Prod Order
g.DrawString("Prod Order", labelFont, textBrush, contentX + 5, currentY + rowHeight/4);
string prodOrder = _labelData.SequentialNumber ?? $"{_labelData.ComandaProductie}-{_labelData.Cantitate}";
SizeF prodSize = g.MeasureString(prodOrder, dataFont);
float prodX = verticalDividerX + (contentWidth * 0.6f - prodSize.Width) / 2;
g.DrawString(prodOrder, dataFont, textBrush, prodX, currentY + rowHeight/4);
// Bottom barcode area
float barcodeY = contentY + contentHeight + (5f / 25.4f) * dpiY; // 5mm below content
float barcodeWidth = contentWidth;
float barcodeHeight = (10f / 25.4f) * dpiY; // 10mm height
// Draw barcode representation (simple lines)
DrawSimpleBarcode(g, contentX, barcodeY, barcodeWidth, barcodeHeight, prodOrder);
// Barcode text
SizeF barcodeTextSize = g.MeasureString(prodOrder, barcodeFont);
float barcodeTextX = contentX + (contentWidth - barcodeTextSize.Width) / 2;
g.DrawString(prodOrder, barcodeFont, textBrush, barcodeTextX, barcodeY + barcodeHeight + 5);
// Vertical barcode on the right side
float verticalBarcodeX = contentX + contentWidth + (5f / 25.4f) * dpiX; // 5mm to the right
float verticalBarcodeWidth = (8f / 25.4f) * dpiX; // 8mm width
DrawSimpleVerticalBarcode(g, verticalBarcodeX, contentY + rowHeight * 2,
verticalBarcodeWidth, contentHeight - rowHeight * 2, customerOrder);
// Dispose resources
companyFont.Dispose();
headerFont.Dispose();
dataFont.Dispose();
labelFont.Dispose();
barcodeFont.Dispose();
borderPen.Dispose();
dividerPen.Dispose();
}
catch (Exception ex)
{
Console.WriteLine($"Error in PrintPage event: {ex.Message}");
}
}
private void DrawSimpleBarcode(Graphics g, float x, float y, float width, float height, string data)
{
// Simple barcode representation using alternating lines
float barWidth = 2f;
bool drawBar = true;
for (float currentX = x; currentX < x + width; currentX += barWidth)
{
if (drawBar)
{
g.FillRectangle(Brushes.Black, currentX, y, barWidth, height * 0.8f);
}
drawBar = !drawBar;
}
}
private void DrawSimpleVerticalBarcode(Graphics g, float x, float y, float width, float height, string data)
{
// Simple vertical barcode representation
float barHeight = 2f;
bool drawBar = true;
for (float currentY = y; currentY < y + height; currentY += barHeight)
{
if (drawBar)
{
g.FillRectangle(Brushes.Black, x, currentY, width * 0.8f, barHeight);
}
drawBar = !drawBar;
}
}
}
}

View File

@@ -0,0 +1,49 @@
using Newtonsoft.Json;
namespace RecticelPrintService
{
public class PrintData
{
[JsonProperty("order_id")]
public int OrderId { get; set; }
[JsonProperty("comanda_productie")]
public string ComandaProductie { get; set; }
[JsonProperty("customer_name")]
public string CustomerName { get; set; }
[JsonProperty("cantitate")]
public int Cantitate { get; set; }
[JsonProperty("com_achiz_client")]
public string ComAchizClient { get; set; }
[JsonProperty("nr_linie_com_client")]
public string NrLinieComClient { get; set; }
[JsonProperty("data_livrare")]
public string DataLivrare { get; set; }
[JsonProperty("dimensiune")]
public string Dimensiune { get; set; }
[JsonProperty("descr_com_prod")]
public string DescrComProd { get; set; }
[JsonProperty("customer_article_number")]
public string CustomerArticleNumber { get; set; }
[JsonProperty("cod_articol")]
public string CodArticol { get; set; }
[JsonProperty("sequential_number")]
public string SequentialNumber { get; set; }
[JsonProperty("current_label")]
public int CurrentLabel { get; set; }
[JsonProperty("total_labels")]
public int TotalLabels { get; set; }
}
}

View File

@@ -0,0 +1,81 @@
using System;
using System.Web;
namespace RecticelPrintService
{
class Program
{
static void Main(string[] args)
{
try
{
if (args.Length == 0)
{
Console.WriteLine("Recticel Print Service - No arguments provided");
Console.WriteLine("Usage: RecticelPrintService.exe \"recticel-print://printer/data\"");
Console.ReadKey();
return;
}
string url = args[0];
Console.WriteLine($"Received print request: {url}");
// Parse the custom protocol URL
// Format: recticel-print://printer_name/base64_encoded_json_data
if (!url.StartsWith("recticel-print://"))
{
Console.WriteLine("Invalid protocol. Expected: recticel-print://");
Console.ReadKey();
return;
}
// Remove protocol prefix
string data = url.Substring("recticel-print://".Length);
// Split printer name and data
string[] parts = data.Split('/');
if (parts.Length < 2)
{
Console.WriteLine("Invalid URL format. Expected: recticel-print://printer_name/data");
Console.ReadKey();
return;
}
string printerName = HttpUtility.UrlDecode(parts[0]);
string encodedData = HttpUtility.UrlDecode(parts[1]);
Console.WriteLine($"Target Printer: {printerName}");
Console.WriteLine($"Data Length: {encodedData.Length}");
// Decode base64 JSON data
byte[] dataBytes = Convert.FromBase64String(encodedData);
string jsonData = System.Text.Encoding.UTF8.GetString(dataBytes);
Console.WriteLine($"Decoded JSON: {jsonData}");
// Parse and print the label
var printer = new LabelPrinter();
bool success = printer.PrintLabel(printerName, jsonData);
if (success)
{
Console.WriteLine("✅ Label printed successfully!");
}
else
{
Console.WriteLine("❌ Failed to print label!");
}
// Keep console open for debugging (remove in production)
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
Console.ReadKey();
}
}
}
}

View File

@@ -0,0 +1,19 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("RecticelPrintService")]
[assembly: AssemblyDescription("Direct label printing service for Recticel Quality System")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Recticel")]
[assembly: AssemblyProduct("Recticel Print Service")]
[assembly: AssemblyCopyright("Copyright © Recticel 2025")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("41ed6235-3c76-4723-a5f6-02d2fa51e677")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{41ED6235-3C76-4723-A5F6-02D2FA51E677}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>RecticelPrintService</RootNamespace>
<AssemblyName>RecticelPrintService</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Drawing.Printing" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="Newtonsoft.Json">
<HintPath>..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="LabelPrinter.cs" />
<Compile Include="PrintData.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net472" />
</packages>