Clean repository and update .gitignore
- Remove build artifacts from git tracking (build/, dist/, __pycache__/, *.spec) - Updated .gitignore to properly exclude generated files - Added old_code/ documentation folder - Updated sample_data.txt to show new 5-field format - Exclude user-specific conf/app.conf from tracking
This commit is contained in:
296
old_code/DOTTED_TEXT_SOLUTION.md
Normal file
296
old_code/DOTTED_TEXT_SOLUTION.md
Normal file
@@ -0,0 +1,296 @@
|
||||
# Print Quality Issue - Dotted/Pixelated Text Solution
|
||||
|
||||
## 🔍 Problem Identified
|
||||
|
||||
**Issue:** Text appears dotted/pixelated on printed labels (like dot-matrix printer output)
|
||||
- PDF looks perfect on screen ✅
|
||||
- But printed output has dotted text ❌
|
||||
- Not smooth/sharp like expected
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Root Cause
|
||||
|
||||
The problem is in the **print pipeline**, not the PDF:
|
||||
|
||||
1. **PDF is generated correctly** at 1200 DPI with vector fonts
|
||||
2. **Printing process rasterizes** (converts to bitmap) the PDF
|
||||
3. **Rasterization happens at LOW resolution** (150-300 DPI typically)
|
||||
4. **Result:** Dotted text instead of smooth vectors
|
||||
|
||||
### Why This Happens:
|
||||
|
||||
```
|
||||
PDF (Vector) → SumatraPDF → Low DPI Raster → Printer Driver → Dotted Output
|
||||
↑ Problem here! Converts to low-res bitmap
|
||||
```
|
||||
|
||||
The printer receives a **bitmap image** at low resolution, not the original vector graphics.
|
||||
|
||||
---
|
||||
|
||||
## ✅ Solutions Implemented
|
||||
|
||||
### **Solution 1: Printer Quality Configuration (CRITICAL)**
|
||||
|
||||
Updated `print_label.py` to configure printer for HIGH QUALITY before printing:
|
||||
|
||||
```python
|
||||
# New function: configure_printer_quality()
|
||||
- Sets PrintQuality = 600 DPI (not draft mode)
|
||||
- Sets TTOption = DMTT_BITMAP (sharper text)
|
||||
- Configures paper size to 35mm x 25mm
|
||||
```
|
||||
|
||||
**This is now automatic** - runs before every print job.
|
||||
|
||||
---
|
||||
|
||||
### **Solution 2: GhostScript Printing (BEST QUALITY)**
|
||||
|
||||
Added GhostScript as primary printing method:
|
||||
|
||||
**Why GhostScript is Better:**
|
||||
- ✅ Maintains **vector graphics** (not rasterized)
|
||||
- ✅ Renders directly to printer at **1200 DPI**
|
||||
- ✅ Perfect text anti-aliasing
|
||||
- ✅ No intermediate bitmap conversion
|
||||
|
||||
**Printing Priority:**
|
||||
1. **GhostScript** (if installed) - BEST quality
|
||||
2. SumatraPDF (fallback) - Good quality
|
||||
3. ShellExecute (fallback) - Uses default PDF viewer
|
||||
4. Open file (last resort) - Manual printing
|
||||
|
||||
---
|
||||
|
||||
## 🚀 How to Get Best Quality
|
||||
|
||||
### **Option A: Install GhostScript (Recommended)**
|
||||
|
||||
1. **Download GhostScript:**
|
||||
- Go to: https://ghostscript.com/releases/gsdnld.html
|
||||
- Download: "GPL Ghostscript 10.04.0 for Windows (64 bit)"
|
||||
|
||||
2. **Install:**
|
||||
- Run installer
|
||||
- Use default installation path
|
||||
- No special configuration needed
|
||||
|
||||
3. **Test:**
|
||||
```powershell
|
||||
python print_pdf_ghostscript.py
|
||||
```
|
||||
Should show: ✅ GhostScript found
|
||||
|
||||
4. **Print:**
|
||||
- Just run your GUI normally
|
||||
- It will automatically use GhostScript
|
||||
- You'll see: "Using GhostScript for high-quality vector printing..."
|
||||
|
||||
**Result:** Perfect, sharp text with no dotting!
|
||||
|
||||
---
|
||||
|
||||
### **Option B: Configure Printer (Without GhostScript)**
|
||||
|
||||
If you can't install GhostScript, the code now **automatically** configures printer quality.
|
||||
|
||||
But you should also manually check:
|
||||
|
||||
1. **Open Printer Preferences:**
|
||||
```powershell
|
||||
.\configure_label_size.ps1
|
||||
```
|
||||
|
||||
2. **Set Quality to HIGHEST:**
|
||||
- Look for "Print Quality" or "Resolution"
|
||||
- Set to: **600 DPI** or **Best** or **High Quality**
|
||||
- NOT "Draft" or "Normal" or "Economy"
|
||||
|
||||
3. **Disable Dithering:**
|
||||
- Look for "Dithering" or "Halftone"
|
||||
- Set to: **None** or **Off**
|
||||
|
||||
4. **Set Graphics Mode:**
|
||||
- Look for "Graphics" or "Text Quality"
|
||||
- Set to: **Vector** or **High Quality**
|
||||
|
||||
---
|
||||
|
||||
## 📊 Quality Comparison
|
||||
|
||||
| Method | Text Quality | Speed | Installation |
|
||||
|--------|--------------|-------|--------------|
|
||||
| **GhostScript** | ⭐⭐⭐⭐⭐ Perfect | Fast | Requires install |
|
||||
| **SumatraPDF + Quality Config** | ⭐⭐⭐⭐ Very Good | Fast | No install needed |
|
||||
| **SumatraPDF (default)** | ⭐⭐ Dotted | Fastest | No install needed |
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Testing
|
||||
|
||||
### Test 1: Check Current Method
|
||||
```powershell
|
||||
# Start GUI
|
||||
.\venv\Scripts\python.exe label_printer_gui.py
|
||||
|
||||
# Watch console output:
|
||||
# Should say one of:
|
||||
# "Using GhostScript for high-quality vector printing..." ← BEST
|
||||
# "Label sent to printer via SumatraPDF..." ← OK
|
||||
```
|
||||
|
||||
### Test 2: Verify GhostScript
|
||||
```powershell
|
||||
python print_pdf_ghostscript.py
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```
|
||||
✅ GhostScript found at: C:\Program Files\gs\gs10.04.0\bin\gswin64c.exe
|
||||
GhostScript is available for high-quality PDF printing
|
||||
```
|
||||
|
||||
### Test 3: Print Test Label
|
||||
```powershell
|
||||
python test_quality.py
|
||||
```
|
||||
|
||||
Check printed output:
|
||||
- ✅ Text should be **smooth and sharp**
|
||||
- ✅ No dotted appearance
|
||||
- ✅ Crisp edges on checkmark image
|
||||
- ✅ Professional quality
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Troubleshooting
|
||||
|
||||
### Still seeing dotted text?
|
||||
|
||||
#### Check 1: Printer Driver Quality
|
||||
```powershell
|
||||
# Run configuration script
|
||||
.\configure_printer_quality.ps1
|
||||
|
||||
# Manually verify:
|
||||
# Settings > Printers > Labels > Printing preferences
|
||||
# Quality = HIGHEST (600 DPI or more)
|
||||
```
|
||||
|
||||
#### Check 2: Print Method Used
|
||||
Look at console output when printing:
|
||||
- **GOOD:** "Using GhostScript..."
|
||||
- **OK:** "Printer configured: 35x25mm @ HIGH QUALITY"
|
||||
- **BAD:** "Could not configure printer quality"
|
||||
|
||||
If you see "Could not configure printer quality":
|
||||
- Printer driver doesn't support programmatic quality changes
|
||||
- MUST configure manually in printer preferences
|
||||
|
||||
#### Check 3: Label Material
|
||||
- **Wrong:** Plain paper (not designed for thermal printing)
|
||||
- **Right:** Thermal labels (heat-sensitive or transfer)
|
||||
|
||||
Wrong label material can cause poor quality even with correct settings.
|
||||
|
||||
#### Check 4: Printer Hardware
|
||||
```powershell
|
||||
# Print self-test from printer
|
||||
# (Usually hold button while powering on)
|
||||
```
|
||||
|
||||
If self-test also shows dotted text:
|
||||
- Printer may be in draft mode
|
||||
- Check printer's physical control panel
|
||||
- Look for "Quality" or "Darkness" dial/setting
|
||||
- May need firmware update
|
||||
|
||||
---
|
||||
|
||||
## 📝 Technical Details
|
||||
|
||||
### Why Dotted Text Happens:
|
||||
|
||||
**Normal printing workflow:**
|
||||
```
|
||||
PDF → Printer Driver → Sharp output
|
||||
```
|
||||
|
||||
**What was happening:**
|
||||
```
|
||||
PDF (vector, 1200 DPI)
|
||||
↓
|
||||
SumatraPDF rasterizes at LOW DPI (150-300)
|
||||
↓
|
||||
Bitmap sent to printer
|
||||
↓
|
||||
Printer prints bitmap → DOTTED TEXT
|
||||
```
|
||||
|
||||
**What we fixed:**
|
||||
```
|
||||
Method 1 (GhostScript):
|
||||
PDF (vector) → GhostScript → Printer @ 1200 DPI → SHARP TEXT
|
||||
|
||||
Method 2 (Quality Config):
|
||||
PDF → Configure printer to 600 DPI → SumatraPDF → Better quality
|
||||
```
|
||||
|
||||
### Key Settings:
|
||||
|
||||
1. **PrintQuality = 600**: Tells Windows to render at 600 DPI minimum
|
||||
2. **TTOption = 2 (DMTT_BITMAP)**: Renders TrueType fonts as graphics (sharper)
|
||||
3. **GhostScript -r1200**: Renders PDF at full 1200 DPI resolution
|
||||
4. **TextAlphaBits=4**: Anti-aliasing for smooth text edges
|
||||
|
||||
---
|
||||
|
||||
## 🎓 Recommendations
|
||||
|
||||
### For Production Use:
|
||||
|
||||
1. **Install GhostScript** on all computers
|
||||
- One-time setup
|
||||
- Always best quality
|
||||
- No manual configuration needed
|
||||
|
||||
2. **Keep PDF backup enabled**
|
||||
- Review PDFs to confirm they look correct
|
||||
- PDFs are always high quality
|
||||
|
||||
3. **Test periodically**
|
||||
- Print quality can change after:
|
||||
- Windows updates
|
||||
- Driver updates
|
||||
- Printer hardware changes
|
||||
|
||||
---
|
||||
|
||||
## 📞 Quick Reference
|
||||
|
||||
### If text is dotted:
|
||||
```powershell
|
||||
# 1. Install GhostScript (best solution)
|
||||
# Download from: https://ghostscript.com/releases/gsdnld.html
|
||||
|
||||
# 2. Or configure printer manually
|
||||
.\configure_label_size.ps1
|
||||
# Set quality to HIGHEST
|
||||
|
||||
# 3. Test
|
||||
python test_quality.py
|
||||
```
|
||||
|
||||
### Check print method:
|
||||
```powershell
|
||||
# Look for this in console output:
|
||||
"Using GhostScript..." # ← You have best quality!
|
||||
"Printer configured: 35x25mm @ HIGH QUALITY" # ← Good
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Last Updated:** February 13, 2026
|
||||
**Status:** Multiple solutions implemented - GhostScript recommended for best quality
|
||||
189
old_code/NEW_FEATURES.md
Normal file
189
old_code/NEW_FEATURES.md
Normal file
@@ -0,0 +1,189 @@
|
||||
# Label Printing - New Features Guide
|
||||
|
||||
## Overview
|
||||
|
||||
The label printer now supports:
|
||||
1. **Multiple Templates** - Choose between OK and NOK labels
|
||||
2. **Multiple Copies** - Print multiple labels in one operation
|
||||
|
||||
## File Format
|
||||
|
||||
The monitored file (`check.txt`) now supports an extended format:
|
||||
|
||||
```
|
||||
ARTICLE;NR_ART;SERIAL;TEMPLATE_TYPE;COUNT
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Position | Description | Values | Default |
|
||||
|-----------|----------|-------------|--------|---------|
|
||||
| ARTICLE | 1 | Article/Command number | Any text | Required |
|
||||
| NR_ART | 2 | Article number | Any text | Required |
|
||||
| SERIAL | 3 | Serial number | Any text | Required |
|
||||
| TEMPLATE_TYPE | 4 | Template selection | 0 = OK, 1 = NOK | 0 (OK) |
|
||||
| COUNT | 5 | Number of copies | 1-100 | 1 |
|
||||
|
||||
## Templates
|
||||
|
||||
### Template Files
|
||||
|
||||
- `conf/label_template_ok.svg` - Template for OK labels (TEMPLATE_TYPE=0)
|
||||
- `conf/label_template_nok.svg` - Template for NOK labels (TEMPLATE_TYPE=1)
|
||||
- `conf/label_template.svg` - Default fallback template
|
||||
|
||||
### Customizing Templates
|
||||
|
||||
Edit the SVG files to customize the layout:
|
||||
- Both templates use the same variables: `{Article}`, `{NrArt}`, `{Serial}`
|
||||
- Modify colors, fonts, or layout as needed
|
||||
- Keep dimensions at 35mm × 25mm (landscape)
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Example 1: Print 1 OK Label
|
||||
```
|
||||
COM-2024-001;ART-12345;SN-20260213-001;0;1
|
||||
```
|
||||
|
||||
### Example 2: Print 3 OK Labels
|
||||
```
|
||||
COM-2024-002;ART-67890;SN-20260213-002;0;3
|
||||
```
|
||||
|
||||
### Example 3: Print 1 NOK Label
|
||||
```
|
||||
COM-2024-003;ART-11111;SN-20260213-003;1;1
|
||||
```
|
||||
|
||||
### Example 4: Print 5 NOK Labels
|
||||
```
|
||||
COM-2024-004;ART-22222;SN-20260213-004;1;5
|
||||
```
|
||||
|
||||
### Example 5: Backward Compatibility (Old Format)
|
||||
```
|
||||
COM-2024-005;ART-33333;SN-20260213-005
|
||||
```
|
||||
This will default to OK template with 1 copy.
|
||||
|
||||
## Testing
|
||||
|
||||
### Quick Test
|
||||
|
||||
1. **Start the application**:
|
||||
```powershell
|
||||
.\venv\Scripts\python.exe label_printer_gui.py
|
||||
```
|
||||
|
||||
2. **Select your printer** in the GUI
|
||||
|
||||
3. **Edit the monitored file** (default: `C:\Users\Public\Documents\check.txt`):
|
||||
```
|
||||
TEST-OK;123456;SN-001;0;2
|
||||
```
|
||||
|
||||
4. **Save the file** - The app will automatically:
|
||||
- Detect OK template (type=0)
|
||||
- Print 2 copies
|
||||
|
||||
5. **Test NOK template**:
|
||||
```
|
||||
TEST-NOK;789012;SN-002;1;1
|
||||
```
|
||||
|
||||
### PDF Testing
|
||||
|
||||
Use "Microsoft Print to PDF" to test without physical printer:
|
||||
- Select "Microsoft Print to PDF" in the GUI
|
||||
- PDFs will be saved to `pdf_backup/` folder
|
||||
- Check that the correct template was used
|
||||
|
||||
## Workflow
|
||||
|
||||
```
|
||||
File Modified
|
||||
↓
|
||||
Read Parameters (Article, NrArt, Serial, Template, Count)
|
||||
↓
|
||||
Select Template (OK or NOK)
|
||||
↓
|
||||
For each copy (1 to Count):
|
||||
├─ Generate PDF from SVG template
|
||||
├─ Replace variables {Article}, {NrArt}, {Serial}
|
||||
├─ Save to pdf_backup/
|
||||
└─ Print via SumatraPDF
|
||||
↓
|
||||
Clear file (write "-")
|
||||
↓
|
||||
Show success message
|
||||
```
|
||||
|
||||
## Safety Limits
|
||||
|
||||
- **Maximum copies**: 100 per operation
|
||||
- **Minimum copies**: 1
|
||||
- Invalid values default to 1 copy
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Template Not Found
|
||||
- **Symptom**: Message "Using SVG template: conf/label_template.svg"
|
||||
- **Cause**: `label_template_ok.svg` or `label_template_nok.svg` missing
|
||||
- **Fix**: Ensure both template files exist in `conf/` folder
|
||||
|
||||
### Wrong Template Printed
|
||||
- **Symptom**: NOK template used when OK expected
|
||||
- **Cause**: TEMPLATE_TYPE parameter incorrect
|
||||
- **Fix**: Check 4th parameter is 0 for OK, 1 for NOK
|
||||
|
||||
### Only 1 Label Printed
|
||||
- **Symptom**: COUNT parameter ignored
|
||||
- **Cause**: Invalid COUNT value or missing parameter
|
||||
- **Fix**: Ensure 5th parameter is a number between 1-100
|
||||
|
||||
## Technical Details
|
||||
|
||||
### File Parsing
|
||||
|
||||
The system tries:
|
||||
1. **Semicolon format**: `value1;value2;value3;value4;value5`
|
||||
2. **Key=value format** (fallback):
|
||||
```
|
||||
article=COM-2024-001
|
||||
nr_art=ART-12345
|
||||
serial=SN-001
|
||||
template=0
|
||||
count=3
|
||||
```
|
||||
|
||||
### Multiple Copy Handling
|
||||
|
||||
- Each label is printed sequentially
|
||||
- 0.5 second delay between copies
|
||||
- Progress shown in GUI for multiple copies
|
||||
- All copies use the same PDF template
|
||||
|
||||
### Backward Compatibility
|
||||
|
||||
Old format (3 parameters) still works:
|
||||
```
|
||||
ARTICLE;NR_ART;SERIAL
|
||||
```
|
||||
Automatically uses: OK template, 1 copy
|
||||
|
||||
## Log Files
|
||||
|
||||
Print actions are logged to `logs/print_log_YYYYMMDD.csv`:
|
||||
- Date/Time
|
||||
- Article, NrArt, Serial
|
||||
- Printer name
|
||||
- PDF filename
|
||||
- Template used
|
||||
- Number of copies
|
||||
- Success/Failure status
|
||||
|
||||
---
|
||||
|
||||
**Version**: February 2026
|
||||
**Compatible with**: Citizen CTS-310, Zebra ZD420/ZD421
|
||||
303
old_code/PAPER_SIZE_ISSUE_ANALYSIS.md
Normal file
303
old_code/PAPER_SIZE_ISSUE_ANALYSIS.md
Normal file
@@ -0,0 +1,303 @@
|
||||
# Label Printing Workflow Analysis - Paper Size Issue
|
||||
|
||||
## 🔍 Problem Identified
|
||||
|
||||
**Issue:** Labels printing on 90cm continuous roll instead of 35mm x 25mm label
|
||||
- PDF is created with correct size (35mm x 25mm)
|
||||
- Printer receives PDF but ignores the page dimensions
|
||||
- Printer defaults to continuous roll mode
|
||||
- Label content prints at the end of a long paper strip
|
||||
|
||||
---
|
||||
|
||||
## 📊 Current Workflow Analysis
|
||||
|
||||
### Step 1: PDF Generation ✅ (Working)
|
||||
```
|
||||
print_label_pdf.py creates PDF:
|
||||
- Page size: 3.5cm x 2.5cm (35mm x 25mm)
|
||||
- Layout: 1/3 image + 2/3 text area
|
||||
- Quality: 1200 DPI, no compression
|
||||
```
|
||||
**Status:** PDF dimensions are CORRECT
|
||||
|
||||
### Step 2: Printing via SumatraPDF ❌ (Problem)
|
||||
```
|
||||
SumatraPDF command:
|
||||
-print-to <printer>
|
||||
-silent
|
||||
-print-settings noscale,landscape,fit
|
||||
<pdf_file>
|
||||
```
|
||||
**Problem:** SumatraPDF doesn't communicate page size to printer driver
|
||||
- Printer uses its default paper size setting
|
||||
- If printer is set to "Continuous" or "Roll" mode → prints on long paper
|
||||
- No explicit paper size passed to printer driver
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Root Cause
|
||||
|
||||
Thermal label printers need EXPLICIT paper size configuration:
|
||||
|
||||
1. **Windows Printing System Issue:**
|
||||
- PDF page size ≠ Printer paper size
|
||||
- Printer driver must be told: "USE THIS EXACT SIZE"
|
||||
- SumatraPDF: Generic PDF viewer, doesn't set printer DEVMODE
|
||||
|
||||
2. **Printer Default Settings:**
|
||||
- Most thermal printers default to continuous roll
|
||||
- Without explicit size, they print entire "page" length
|
||||
- Result: 90cm of paper with label at the end
|
||||
|
||||
---
|
||||
|
||||
## ✅ Proposed Solutions
|
||||
|
||||
### **Solution 1: Configure Printer Paper Size (Recommended)**
|
||||
|
||||
#### Manual Configuration:
|
||||
1. Open **Printer Preferences** for "Labels" printer
|
||||
2. Go to **Page Setup** or **Paper/Quality** tab
|
||||
3. Set paper size to **Custom: 35mm x 25mm**
|
||||
4. Set orientation to **Landscape**
|
||||
5. Save as default
|
||||
|
||||
#### PowerShell Script:
|
||||
```powershell
|
||||
# Run the printer configuration script
|
||||
.\configure_label_size.ps1
|
||||
```
|
||||
|
||||
**Pros:**
|
||||
- ✅ One-time setup
|
||||
- ✅ Works with any PDF viewer
|
||||
- ✅ Simplest solution
|
||||
|
||||
**Cons:**
|
||||
- ❌ Needs manual configuration per computer
|
||||
- ❌ Settings can be reset by driver updates
|
||||
|
||||
---
|
||||
|
||||
### **Solution 2: Use Win32 Print API with Explicit Size (Best Control)**
|
||||
|
||||
Use `print_with_size.py` module that:
|
||||
- Opens printer with Win32 API
|
||||
- Sets DEVMODE structure with exact dimensions:
|
||||
```python
|
||||
devmode.PaperSize = 256 # Custom
|
||||
devmode.PaperLength = 250 # 25mm in 0.1mm units
|
||||
devmode.PaperWidth = 350 # 35mm in 0.1mm units
|
||||
devmode.Orientation = 2 # Landscape
|
||||
```
|
||||
- Prints with guaranteed size
|
||||
|
||||
**Implementation:**
|
||||
```python
|
||||
# In print_label.py, replace SumatraPDF call with:
|
||||
from print_with_size import set_printer_paper_size, print_with_custom_size
|
||||
|
||||
# Configure printer once
|
||||
set_printer_paper_size(printer_name, 35, 25)
|
||||
|
||||
# Then print normally
|
||||
print_to_printer(printer_name, pdf_file)
|
||||
```
|
||||
|
||||
**Pros:**
|
||||
- ✅ Programmatic control
|
||||
- ✅ Always sets correct size
|
||||
- ✅ No manual configuration needed
|
||||
|
||||
**Cons:**
|
||||
- ❌ More complex code
|
||||
- ❌ Windows-only
|
||||
- ❌ Requires pywin32
|
||||
|
||||
---
|
||||
|
||||
### **Solution 3: Use Label Template PDF (Most Reliable)**
|
||||
|
||||
Create a proper label template that printers recognize:
|
||||
|
||||
1. **Design in Label Software:**
|
||||
- Use manufacturer's label design software (e.g., Zebra Designer, BarTender)
|
||||
- Or use professional tool like Adobe Illustrator
|
||||
- Export as PDF with embedded printer settings
|
||||
|
||||
2. **Template Features:**
|
||||
- Embedded page size metadata
|
||||
- Printer-specific settings
|
||||
- Registration marks (optional)
|
||||
|
||||
3. **Dynamic Field Replacement:**
|
||||
- Template has placeholder text: `{COMANDA}`, `{ARTICLE}`, `{SERIAL}`
|
||||
- Python replaces placeholders before printing
|
||||
- Or use PDF form fields
|
||||
|
||||
**Implementation:**
|
||||
```python
|
||||
# Create template with proper settings
|
||||
from PyPDF2 import PdfReader, PdfWriter
|
||||
from reportlab.pdfgen import canvas
|
||||
from reportlab.lib.units import mm
|
||||
|
||||
def fill_label_template(template_path, data, output_path):
|
||||
"""
|
||||
Fill label template with data.
|
||||
Template has proper printer settings embedded.
|
||||
"""
|
||||
# Read template
|
||||
template = PdfReader(template_path)
|
||||
|
||||
# Create overlay with data
|
||||
packet = io.BytesIO()
|
||||
c = canvas.Canvas(packet, pagesize=(35*mm, 25*mm))
|
||||
|
||||
# Add text at specific coordinates
|
||||
c.setFont("Helvetica-Bold", 8)
|
||||
c.drawString(15*mm, 18*mm, f"Nr. Comanda: {data['comanda']}")
|
||||
c.drawString(15*mm, 12*mm, f"Nr. Art.: {data['article']}")
|
||||
c.drawString(15*mm, 6*mm, f"Serial No.: {data['serial']}")
|
||||
c.save()
|
||||
|
||||
# Merge with template
|
||||
overlay = PdfReader(packet)
|
||||
page = template.pages[0]
|
||||
page.merge_page(overlay.pages[0])
|
||||
|
||||
# Write output
|
||||
writer = PdfWriter()
|
||||
writer.add_page(page)
|
||||
|
||||
with open(output_path, 'wb') as f:
|
||||
writer.write(f)
|
||||
|
||||
return output_path
|
||||
```
|
||||
|
||||
**Pros:**
|
||||
- ✅ Most reliable across different systems
|
||||
- ✅ Printer recognizes format immediately
|
||||
- ✅ Professional appearance
|
||||
- ✅ Can include printer-specific optimizations
|
||||
|
||||
**Cons:**
|
||||
- ❌ Requires template creation/design
|
||||
- ❌ Changes need template update
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Recommended Approach
|
||||
|
||||
**Immediate Fix (5 minutes):**
|
||||
```powershell
|
||||
# 1. Configure printer paper size
|
||||
.\configure_label_size.ps1
|
||||
|
||||
# OR manually:
|
||||
# - Open Printer Preferences
|
||||
# - Set paper size to 35mm x 25mm
|
||||
# - Set orientation to Landscape
|
||||
```
|
||||
|
||||
**Long-term Solution (30 minutes):**
|
||||
1. Create proper label template in label design software
|
||||
2. Export as PDF with embedded settings
|
||||
3. Use template-based printing in application
|
||||
|
||||
**Alternative (if above doesn't work):**
|
||||
1. Integrate `print_with_size.py` module
|
||||
2. Modify `print_label.py` to use Win32 API printing
|
||||
3. Explicit paper size on every print job
|
||||
|
||||
---
|
||||
|
||||
## 📝 Implementation Priority
|
||||
|
||||
### Priority 1 (DO NOW):
|
||||
1. ✅ Configure printer manually
|
||||
2. ✅ Test with current code
|
||||
3. ✅ Verify label prints at correct size
|
||||
|
||||
### Priority 2 (THIS WEEK):
|
||||
1. 🔄 Create label template with proper settings
|
||||
2. 🔄 Test template-based printing
|
||||
3. 🔄 Update application to use template
|
||||
|
||||
### Priority 3 (IF NEEDED):
|
||||
1. ⏳ Implement Win32 API printing
|
||||
2. ⏳ Add automatic paper size detection
|
||||
3. ⏳ Create printer setup wizard
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Testing Steps
|
||||
|
||||
After implementing any solution:
|
||||
|
||||
1. **Test print:**
|
||||
```powershell
|
||||
python test_quality.py
|
||||
```
|
||||
|
||||
2. **Verify:**
|
||||
- ✓ Paper stops at 35mm (not 90cm)
|
||||
- ✓ Label fills entire label area
|
||||
- ✓ No blank space before/after label
|
||||
- ✓ Text is readable and properly positioned
|
||||
|
||||
3. **Check printer:**
|
||||
- ✓ Paper advance is correct
|
||||
- ✓ No paper waste
|
||||
- ✓ Multiple labels print consecutively
|
||||
|
||||
---
|
||||
|
||||
## 📞 Quick Fix Script
|
||||
|
||||
Create and run this PowerShell script to configure your printer now:
|
||||
|
||||
**File: `configure_label_size.ps1`**
|
||||
```powershell
|
||||
$printerName = "Labels"
|
||||
|
||||
Write-Host "Configuring printer for 35mm x 25mm labels..." -ForegroundColor Cyan
|
||||
|
||||
# Open printer preferences dialog for manual config
|
||||
rundll32 printui.dll,PrintUIEntry /e /n "$printerName"
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "In the printer preferences window:" -ForegroundColor Yellow
|
||||
Write-Host "1. Find 'Paper Size' or 'Media' settings" -ForegroundColor White
|
||||
Write-Host "2. Select 'Custom' or create new size: 35mm x 25mm" -ForegroundColor White
|
||||
Write-Host "3. Set orientation to: Landscape" -ForegroundColor White
|
||||
Write-Host "4. Click OK to save" -ForegroundColor White
|
||||
Write-Host ""
|
||||
Write-Host "After configuration, test with: python test_quality.py" -ForegroundColor Green
|
||||
```
|
||||
|
||||
Run: `.\configure_label_size.ps1`
|
||||
|
||||
---
|
||||
|
||||
## 🎓 Why This Happens
|
||||
|
||||
**Technical Explanation:**
|
||||
|
||||
Thermal label printers have two modes:
|
||||
1. **Label Mode:** Prints on predefined label sizes (35mm, 50mm, etc.)
|
||||
2. **Continuous Mode:** Prints on continuous roll (any length)
|
||||
|
||||
When you send a PDF:
|
||||
- PDF says: "I'm 35mm x 25mm"
|
||||
- Printer says: "I don't see a label size command, using default (continuous)"
|
||||
- Result: Prints on continuous roll
|
||||
|
||||
**Solution:** Tell printer explicitly to use Label Mode with 35mm x 25mm size.
|
||||
|
||||
---
|
||||
|
||||
**Last Updated:** February 13, 2026
|
||||
**Status:** Solution pending - user must configure printer paper size
|
||||
179
old_code/PRINTER_CONFIGURATION.md
Normal file
179
old_code/PRINTER_CONFIGURATION.md
Normal file
@@ -0,0 +1,179 @@
|
||||
# Thermal Printer Paper Size Configuration Guide
|
||||
|
||||
## Problem
|
||||
When printing labels, the PDF is generated correctly at 35mm x 25mm, but SumatraPDF prints them scaled to the printer's currently configured paper size. This results in incorrectly sized labels.
|
||||
|
||||
## Root Cause
|
||||
SumatraPDF's `noscale` mode preserves the PDF content but still uses the **Windows printer's configured paper size**. If the printer is set to A4, Letter, or continuous roll, the label will be scaled to that size.
|
||||
|
||||
## Solution
|
||||
Configure your thermal printer in Windows with the correct paper size (35mm x 25mm).
|
||||
|
||||
---
|
||||
|
||||
## Quick Setup
|
||||
|
||||
### Step 1: Run Configuration Helper
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File configure_printer_paper_size.ps1
|
||||
```
|
||||
|
||||
### Step 2: Manual Configuration
|
||||
|
||||
#### For Citizen CTS-310 Printers:
|
||||
1. Open **Control Panel** → **Devices and Printers**
|
||||
2. Right-click **Citizen CTS-310II** → **Printing Preferences**
|
||||
3. Under **Page Layout** or **Paper Settings**:
|
||||
- **Paper Size**: Custom
|
||||
- **Width**: 35mm (1.38 inches)
|
||||
- **Height**: 25mm (0.98 inches)
|
||||
- **Orientation**: Landscape
|
||||
4. Click **Apply** → **OK**
|
||||
|
||||
#### For Zebra ZD420/ZD421 Printers:
|
||||
1. Open **Zebra Setup Utility** (ZSU) or Settings
|
||||
2. Select your printer
|
||||
3. Configure **Media**:
|
||||
- **Media Type**: Label Stock (NOT Continuous)
|
||||
- **Label Width**: 35mm
|
||||
- **Label Height**: 25mm
|
||||
4. Configure **Print Quality**:
|
||||
- **Darkness**: 10-15
|
||||
- **Print Speed**: 4 ips
|
||||
5. **Send to Printer**
|
||||
|
||||
---
|
||||
|
||||
## Critical Settings
|
||||
|
||||
### ⚠️ Media Type MUST be "Labels" or "Label Stock"
|
||||
- **Correct**: Media Type = Labels (enables gap sensor)
|
||||
- **Wrong**: Media Type = Continuous (prints entire roll, ignores gaps)
|
||||
|
||||
### Paper Dimensions
|
||||
- **Width**: 35mm
|
||||
- **Height**: 25mm
|
||||
- **Orientation**: Landscape (35mm is width, 25mm is height)
|
||||
|
||||
### Print Quality (Thermal Printers)
|
||||
- **Darkness**: 10-15 (NOT DPI - thermal printers use darkness control)
|
||||
- **Speed**: Medium (4 ips recommended)
|
||||
- **Resolution**: 203-300 DPI (hardware fixed, not configurable)
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
### Test Your Configuration:
|
||||
1. Start the GUI:
|
||||
```bash
|
||||
python label_printer_gui.py
|
||||
```
|
||||
|
||||
2. Add test data to `C:\Users\Public\Documents\check.txt`:
|
||||
```
|
||||
COM-001;ART-123;SN-001;0;1
|
||||
```
|
||||
|
||||
3. Check the printed label:
|
||||
- ✅ Should be exactly 35mm x 25mm
|
||||
- ✅ Should fit the label perfectly (no scaling)
|
||||
- ✅ Should stop at label gap (not continue on roll)
|
||||
|
||||
### If Labels are Wrong Size:
|
||||
- Too large → Printer paper size is too big (check Windows printer settings)
|
||||
- Too small → PDF might be generated incorrectly (check pdf_backup/ folder)
|
||||
- Continuous printing → Media Type is set to "Continuous" instead of "Labels"
|
||||
|
||||
---
|
||||
|
||||
## Windows Custom Paper Size (Advanced)
|
||||
|
||||
If your printer driver doesn't have 35mm x 25mm preset:
|
||||
|
||||
### Create Custom Form:
|
||||
1. Open **Control Panel** → **Devices and Printers**
|
||||
2. Select any printer → **Print Server Properties** (top menu)
|
||||
3. Check **"Create a new form"**
|
||||
4. Form name: **Label35x25**
|
||||
5. Width: **3.50 cm** (35mm)
|
||||
6. Height: **2.50 cm** (25mm)
|
||||
7. Click **Save Form**
|
||||
8. Now this form will be available in all printer settings
|
||||
|
||||
### Assign Form to Printer:
|
||||
1. Right-click your thermal printer → **Printer Properties** (not Preferences)
|
||||
2. **Device Settings** tab
|
||||
3. **Form to Tray Assignment** → Select **Label35x25**
|
||||
4. Apply → OK
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Problem: Labels still wrong size after configuration
|
||||
**Solution**:
|
||||
- Restart the printer
|
||||
- Restart the print spooler: `net stop spooler && net start spooler`
|
||||
- Check if driver supports custom sizes (some old drivers don't)
|
||||
|
||||
### Problem: Printer prints continuously without stopping
|
||||
**Solution**:
|
||||
- Change Media Type from "Continuous" to "Labels"
|
||||
- Enable gap sensor in printer settings
|
||||
- Calibrate media (Zebra: hold feed button 2 seconds)
|
||||
|
||||
### Problem: Dotted or poor quality text
|
||||
**Solution**:
|
||||
- Increase darkness setting (10-15 recommended)
|
||||
- Clean printhead
|
||||
- Check ribbon (thermal transfer) or label quality
|
||||
|
||||
---
|
||||
|
||||
## File Format (check.txt)
|
||||
|
||||
```
|
||||
ARTICLE;NR_ART;SERIAL;TEMPLATE_TYPE;COUNT
|
||||
```
|
||||
|
||||
Examples:
|
||||
- `COM-001;ART-123;SN-001;0;1` = 1 OK label (green checkmark)
|
||||
- `COM-002;ART-456;SN-002;1;2` = 2 NOK labels (red text + "NOK")
|
||||
|
||||
Template Types:
|
||||
- **0** = OK template (green checkmark, "OK" text)
|
||||
- **1** = NOK template (red text, red checkmark, "NOK" text)
|
||||
|
||||
---
|
||||
|
||||
## Technical Details
|
||||
|
||||
### PDF Generation Pipeline:
|
||||
1. **SVG Template** (conf/label_template_*.svg)
|
||||
- Dimensions: `width="35mm" height="25mm"`
|
||||
- Variables: `{Article}`, `{NrArt}`, `{Serial}`
|
||||
|
||||
2. **CairoSVG Conversion**
|
||||
- Converts SVG → PDF at 300 DPI
|
||||
- Preserves SVG dimensions (35mm x 25mm)
|
||||
|
||||
3. **SumatraPDF Printing**
|
||||
- Uses `-print-settings noscale` (no scaling)
|
||||
- Sends PDF directly to printer
|
||||
- Uses printer's configured paper size
|
||||
|
||||
### Why Paper Size Configuration is Critical:
|
||||
SumatraPDF's `noscale` tells it "don't scale the PDF content", but the **printer driver** still needs to know what paper size to use. If the driver thinks it's printing on A4 paper, it will center the 35mm label on an A4 page.
|
||||
|
||||
By configuring the printer with 35mm x 25mm paper, the driver knows to feed labels of that size, and SumatraPDF will print the PDF content unscaled to match.
|
||||
|
||||
---
|
||||
|
||||
## Support
|
||||
|
||||
For issues:
|
||||
1. Check printer configuration: `configure_printer_paper_size.ps1`
|
||||
2. Verify PDF dimensions: Open file from `pdf_backup/` in Adobe Reader
|
||||
3. Check logs: `logs/print_log_YYYYMMDD.csv`
|
||||
4. Test with Microsoft Print to PDF first (configure it for 35mm x 25mm)
|
||||
175
old_code/PRINT_QUALITY_IMPROVEMENTS.md
Normal file
175
old_code/PRINT_QUALITY_IMPROVEMENTS.md
Normal file
@@ -0,0 +1,175 @@
|
||||
# Print Quality Improvements - Label Printer
|
||||
|
||||
## Summary of Changes
|
||||
|
||||
This document outlines the comprehensive print quality improvements made to enhance label output quality, particularly for thermal label printers.
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Key Improvements
|
||||
|
||||
### 1. **Increased DPI Resolution**
|
||||
- **Before:** 600 DPI
|
||||
- **After:** 1200 DPI
|
||||
- **Impact:** Significantly sharper text and images, especially on thermal printers
|
||||
- **Changed in:** `print_label_pdf.py` - PDFLabelGenerator class
|
||||
|
||||
### 2. **Enhanced Font Size**
|
||||
- **Before:** 6pt font (~2.1mm height)
|
||||
- **After:** 8pt font (~2.8mm height)
|
||||
- **Impact:** Better readability, especially for serial numbers and part numbers
|
||||
- **Changed in:** `print_label_pdf.py` - create_label_pdf() method
|
||||
|
||||
### 3. **Disabled PDF Compression**
|
||||
- **Before:** Compression enabled (level 1)
|
||||
- **After:** Compression disabled (level 0)
|
||||
- **Impact:** No quality loss from compression artifacts
|
||||
- **Changed in:** `print_label_pdf.py` - create_label_pdf() method
|
||||
|
||||
### 4. **Improved Image Quality**
|
||||
- **Before:** Converted images to grayscale ('L' mode)
|
||||
- **After:** Keep images in RGB mode with DPI metadata
|
||||
- **Impact:** Better image quality; thermal printers will handle color→BW conversion optimally
|
||||
- **Changed in:** `print_label_pdf.py` - load_image() and create_label_pdf() methods
|
||||
|
||||
### 5. **Fixed Image Resampling**
|
||||
- **Before:** Used deprecated `Image.LANCZOS`
|
||||
- **After:** Uses `Image.Resampling.LANCZOS` with fallback
|
||||
- **Impact:** Compatible with newer Pillow versions, maintains quality
|
||||
- **Changed in:** `print_label.py` - create_label_image() method
|
||||
|
||||
### 6. **Improved SumatraPDF Print Settings**
|
||||
- **Before:** `noscale,landscape`
|
||||
- **After:** `noscale,landscape,fit`
|
||||
- **Impact:** Ensures content fits page properly without clipping
|
||||
- **Changed in:** `print_label.py` - print_to_printer() method
|
||||
|
||||
---
|
||||
|
||||
## 📋 Additional Recommendations
|
||||
|
||||
### Printer Settings Configuration
|
||||
|
||||
For optimal print quality, ensure your thermal printer is configured with:
|
||||
|
||||
1. **Print Quality:** Highest/Best (600 DPI or higher)
|
||||
2. **Darkness/Intensity:** Medium to High (adjust based on label material)
|
||||
3. **Print Speed:** Medium to Slow (slower = better quality)
|
||||
4. **Dithering:** None/Off (for sharp text and barcodes)
|
||||
5. **Graphics Mode:** Vector or High Quality
|
||||
6. **Paper Type:** Label/Thermal (match your label stock)
|
||||
|
||||
### How to Configure Windows Printer Settings
|
||||
|
||||
1. Open **Windows Settings** → **Devices** → **Printers & scanners**
|
||||
2. Click on your **Labels** printer
|
||||
3. Click **Manage** → **Printing preferences**
|
||||
4. Look for these settings:
|
||||
- **Quality tab:** Set to highest DPI available
|
||||
- **Advanced tab:** Check for density/darkness settings
|
||||
- **Graphics tab:** Disable dithering, enable vector mode
|
||||
5. Click **Apply** and **OK**
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Troubleshooting
|
||||
|
||||
### If print quality is still poor:
|
||||
|
||||
1. **Run the printer quality check:**
|
||||
```powershell
|
||||
.\check_printer_quality.ps1
|
||||
```
|
||||
|
||||
2. **Check label material:**
|
||||
- Direct thermal labels need heat-sensitive coating
|
||||
- Thermal transfer labels need ribbon cartridge
|
||||
- Wrong label type = poor quality
|
||||
|
||||
3. **Verify printer driver:**
|
||||
- Update to latest driver from manufacturer's website
|
||||
- Some generic drivers don't support high-quality settings
|
||||
|
||||
4. **Test print from printer:**
|
||||
- Print a self-test page from the printer
|
||||
- This verifies printer hardware is functioning correctly
|
||||
|
||||
5. **Check printhead:**
|
||||
- Dirty printhead = streaky output
|
||||
- Clean printhead with isopropyl alcohol and cleaning cards
|
||||
|
||||
6. **Adjust print darkness:**
|
||||
- Too light: Increase darkness/temperature
|
||||
- Too dark: Decrease darkness/temperature
|
||||
- Adjust in printer preferences or physical dial
|
||||
|
||||
---
|
||||
|
||||
## 📊 Quality Comparison
|
||||
|
||||
| Aspect | Before | After | Improvement |
|
||||
|--------|--------|-------|-------------|
|
||||
| DPI | 600 | 1200 | +100% |
|
||||
| Font Size | 6pt | 8pt | +33% |
|
||||
| Image Mode | Grayscale | RGB | Better quality |
|
||||
| PDF Compression | Enabled | Disabled | No artifacts |
|
||||
| Image Resampling | Deprecated API | Modern API | Better compatibility |
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Testing
|
||||
|
||||
To verify improvements:
|
||||
|
||||
1. **Print a test label** with all three fields filled
|
||||
2. **Check text readability:** Should be crisp and clear
|
||||
3. **Inspect image:** Should have clean edges without jaggedness
|
||||
|
||||
Expected results:
|
||||
- ✅ Text is sharp and readable at arm's length
|
||||
- ✅ Images (accepted/refused checkmark) are crisp
|
||||
- ✅ No pixelation or compression artifacts visible
|
||||
|
||||
---
|
||||
|
||||
## 📝 Code Changes Summary
|
||||
|
||||
### Files Modified:
|
||||
1. `print_label_pdf.py` - 5 changes
|
||||
2. `print_label.py` - 2 changes (image resampling + print settings)
|
||||
|
||||
### Backward Compatibility:
|
||||
- ✅ All changes are backward compatible
|
||||
- ✅ No breaking changes to API
|
||||
- ✅ Fallback for older Pillow versions included
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Rollback Instructions
|
||||
|
||||
If you need to revert changes:
|
||||
|
||||
```bash
|
||||
git checkout HEAD~1 print_label_pdf.py print_label.py
|
||||
```
|
||||
|
||||
Or manually adjust these values back in the files:
|
||||
- DPI: 1200 → 600
|
||||
- Font size: 8 → 6
|
||||
- Compression: 0 → 1
|
||||
|
||||
---
|
||||
|
||||
## 📞 Support
|
||||
|
||||
If print quality issues persist after these changes:
|
||||
|
||||
1. Verify printer model and capabilities
|
||||
2. Check printer firmware version
|
||||
3. Test with different label stock
|
||||
4. Contact printer manufacturer support with sample outputs
|
||||
|
||||
---
|
||||
|
||||
**Last Updated:** February 13, 2026
|
||||
**Version:** 2.0 - Quality Enhancement Release
|
||||
153
old_code/README.md
Normal file
153
old_code/README.md
Normal file
@@ -0,0 +1,153 @@
|
||||
# Adaptronic Label Printer
|
||||
|
||||
Thermal label printing application with customizable SVG templates for 35mm x 25mm labels.
|
||||
|
||||
## Features
|
||||
|
||||
- 🎨 **Customizable Layouts** - SVG template system for flexible label design
|
||||
- 📄 **High-Quality PDFs** - 1200 DPI output with automatic backup
|
||||
- 🖨️ **Silent Printing** - SumatraPDF integration for automatic printing
|
||||
- 📊 **Variable Support** - Dynamic text replacement ({Article}, {NrArt}, {Serial})
|
||||
- 💾 **Automatic Backup** - All labels saved to pdf_backup/ with timestamps
|
||||
- 🔍 **File Monitoring** - Watches check.txt for automatic label generation
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Install Dependencies
|
||||
|
||||
```powershell
|
||||
# Activate virtual environment
|
||||
venv\Scripts\activate
|
||||
|
||||
# Install requirements
|
||||
pip install -r requirements_gui.txt
|
||||
```
|
||||
|
||||
### Run the Application
|
||||
|
||||
```powershell
|
||||
python label_printer_gui.py
|
||||
```
|
||||
|
||||
## Label Specifications
|
||||
|
||||
- **Size**: 35mm × 25mm (landscape)
|
||||
- **Format**: Thermal labels (Citizen CTS-310, Zebra ZD420/ZD421)
|
||||
- **Template**: `conf/label_template.svg`
|
||||
- **Data Format**: Semicolon-separated (COMANDA;NR_ART;SERIAL)
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
adaptronic_label-printer/
|
||||
├── label_printer_gui.py # Main GUI application
|
||||
├── print_label.py # Printing logic
|
||||
├── print_label_pdf.py # PDF generation with SVG support
|
||||
├── requirements_gui.txt # Dependencies
|
||||
├── conf/
|
||||
│ ├── label_template.svg # Customizable label layout
|
||||
│ └── app.conf # Application settings
|
||||
├── pdf_backup/ # Auto-saved label PDFs
|
||||
├── logs/ # Print logs
|
||||
└── old_code/ # Legacy scripts (archived)
|
||||
```
|
||||
|
||||
## Customizing Labels
|
||||
|
||||
Edit `conf/label_template.svg` to change the layout. Use these variables:
|
||||
- `{Article}` - Article/Command number
|
||||
- `{NrArt}` - Article number
|
||||
- `{Serial}` - Serial number
|
||||
|
||||
After editing the SVG, labels will automatically use the new layout.
|
||||
|
||||
## Printing
|
||||
|
||||
### Silent Printing (Recommended)
|
||||
|
||||
Labels print automatically using SumatraPDF. No dialogs or manual steps required.
|
||||
|
||||
**SumatraPDF Locations Checked:**
|
||||
1. Bundled with exe (for deployments)
|
||||
2. `SumatraPDF/` folder in project directory
|
||||
3. System installations (`C:\Program Files\SumatraPDF\`)
|
||||
|
||||
### PDF Printer Testing
|
||||
|
||||
Select "Microsoft Print to PDF" or similar PDF printer to test label generation without physical printing.
|
||||
|
||||
### Printer Configuration
|
||||
|
||||
For thermal printers, configure in Windows Printer Preferences:
|
||||
- **Media Type**: LABELS (enables gap sensor)
|
||||
- **Paper Size**: 35mm x 25mm or Custom
|
||||
- **Orientation**: Landscape
|
||||
- **Darkness**: 10-15 (medium)
|
||||
- **Speed**: Medium (4-6 in/sec)
|
||||
|
||||
## Dependencies
|
||||
|
||||
Core:
|
||||
- `reportlab` - PDF generation
|
||||
- `svglib` - SVG to PDF conversion
|
||||
- `cairosvg` - Alternative SVG renderer
|
||||
- `watchdog` - File monitoring
|
||||
|
||||
GUI:
|
||||
- `kivy` - Cross-platform interface
|
||||
|
||||
Optional:
|
||||
- `pywin32` - Windows printer enumeration
|
||||
- `pycups` - Linux printing support
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Labels Print on Continuous Roll
|
||||
|
||||
**Cause**: Printer Media Type set to "Continuous" instead of "LABELS"
|
||||
**Fix**: Change to "LABELS" in printer preferences
|
||||
|
||||
### Dotted or Pixelated Text
|
||||
|
||||
**Cause**: Low darkness setting or draft mode
|
||||
**Fix**: Increase darkness to 12-15, ensure quality mode enabled
|
||||
|
||||
### PDF Not Printing Automatically
|
||||
|
||||
**Cause**: SumatraPDF not found
|
||||
**Fix**: Install SumatraPDF or place in project folder
|
||||
|
||||
## Technical Details
|
||||
|
||||
### PDF Generation
|
||||
- **Resolution**: 1200 DPI
|
||||
- **Compression**: None (maximum quality)
|
||||
- **Font Size**: 8pt (optimized for 35mm labels)
|
||||
- **Format**: ReportLab with SVG embedding
|
||||
|
||||
### Print Workflow
|
||||
1. Monitor `C:\Users\Public\Documents\check.txt` for changes
|
||||
2. Parse semicolon-separated data
|
||||
3. Replace variables in SVG template
|
||||
4. Convert to high-quality PDF (35mm × 25mm)
|
||||
5. Auto-save to `pdf_backup/`
|
||||
6. Silent print via SumatraPDF
|
||||
|
||||
## Building Executable
|
||||
|
||||
```powershell
|
||||
python build_exe.py
|
||||
```
|
||||
|
||||
Output: `dist/LabelPrinter.exe`
|
||||
|
||||
## Support
|
||||
|
||||
- Tested on Windows 10/11
|
||||
- Compatible with Citizen CTS-310, Zebra ZD420/ZD421
|
||||
- Based on proven label printer architecture
|
||||
|
||||
---
|
||||
|
||||
**Status**: Production Ready ✅
|
||||
**Last Updated**: February 2026
|
||||
251
old_code/SIMPLE_SETUP_GUIDE.md
Normal file
251
old_code/SIMPLE_SETUP_GUIDE.md
Normal file
@@ -0,0 +1,251 @@
|
||||
# Simple Label Printer Setup Guide
|
||||
|
||||
## 🎯 The Correct Workflow
|
||||
|
||||
### How It Works:
|
||||
1. **GUI monitors** text file for changes (`C:\Users\Public\Documents\check.txt`)
|
||||
2. **When file changes**, reads data: `COMANDA;NR_ART;SERIAL`
|
||||
3. **Replaces variables** in SVG template (`conf/label_template.svg`):
|
||||
- `{Article}` → COMANDA value
|
||||
- `{NrArt}` → NR_ART value
|
||||
- `{Serial}` → SERIAL value
|
||||
4. **Converts SVG → PDF** at exact 35mm x 25mm size
|
||||
5. **Prints PDF** to configured printer
|
||||
6. **Saves backup** in `pdf_backup/` folder
|
||||
|
||||
### Template Customization:
|
||||
- Edit `conf/label_template.svg` to change label layout
|
||||
- Move text positions, add graphics, change fonts
|
||||
- Keep placeholders: `{Article}`, `{NrArt}`, `{Serial}`
|
||||
- No code changes needed!
|
||||
|
||||
---
|
||||
|
||||
## 🚀 ONE-TIME Setup (5 Minutes)
|
||||
|
||||
### Step 1: Configure Printer (REQUIRED)
|
||||
```powershell
|
||||
.\setup_printer.ps1
|
||||
```
|
||||
|
||||
**What this does:**
|
||||
- Opens printer preferences dialog
|
||||
- Guides you to set:
|
||||
- Paper Size: **35mm x 25mm** (custom)
|
||||
- Orientation: **Landscape**
|
||||
- Quality: **BEST/600 DPI**
|
||||
- Tests printing
|
||||
|
||||
**This is CRITICAL** - without correct paper size, you'll get:
|
||||
- ❌ 1 meter roll printing
|
||||
- ❌ Wrong label size
|
||||
- ❌ Portrait instead of landscape
|
||||
|
||||
---
|
||||
|
||||
## ✅ Daily Use
|
||||
|
||||
### Start the Application:
|
||||
```powershell
|
||||
python label_printer_gui.py
|
||||
```
|
||||
|
||||
### What You'll See:
|
||||
1. GUI opens with monitoring controls
|
||||
2. Select printer: "Labels"
|
||||
3. Click "Start Monitoring" (or auto-starts)
|
||||
4. GUI watches the file for changes
|
||||
|
||||
### Trigger Printing:
|
||||
- Application writes to `C:\Users\Public\Documents\check.txt`
|
||||
- Format: `COM-2024-002;ART-67890;SN-20260212`
|
||||
- GUI detects change → Prints label automatically
|
||||
- File is cleared after printing
|
||||
|
||||
---
|
||||
|
||||
## 📝 Data Format
|
||||
|
||||
### Input File: `check.txt`
|
||||
```
|
||||
COM-2024-002;ART-67890;SN-20260212
|
||||
```
|
||||
|
||||
### Separator: Semicolon (`;`)
|
||||
|
||||
### Breakdown:
|
||||
- **Field 1**: Nr. Comanda (Order Number)
|
||||
- **Field 2**: Nr. Art. (Article Number)
|
||||
- **Field 3**: Serial No. (Serial Number)
|
||||
|
||||
### Example Data:
|
||||
```
|
||||
ORDER-123;PART-456;SN-2026-001
|
||||
COM-2024-100;ART-55555;SERIAL-123456
|
||||
COMANDA-X;ARTICLE-Y;SN-Z
|
||||
```
|
||||
|
||||
All fields are printed on the label as entered.
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Troubleshooting
|
||||
|
||||
### Problem: 1 Meter Roll Printing
|
||||
**Cause**: Printer paper size not configured
|
||||
**Fix**:
|
||||
```powershell
|
||||
.\setup_printer.ps1
|
||||
```
|
||||
Set paper size to **35mm x 25mm custom**
|
||||
|
||||
### Problem: Dotted/Pixelated Text
|
||||
**Cause**: Print quality too low
|
||||
**Fix**:
|
||||
1. Open printer preferences
|
||||
2. Set quality to **BEST** or **600 DPI**
|
||||
3. Disable dithering
|
||||
4.Run `.\setup_printer.ps1` again
|
||||
|
||||
### Problem: Label Wrong Orientation
|
||||
**Cause**: Orientation not set to landscape
|
||||
**Fix**:
|
||||
1. Open printer preferences
|
||||
2. Set orientation to **LANDSCAPE**
|
||||
3. Save and test
|
||||
|
||||
### Problem: Template Not Working
|
||||
**Cause**: SVG template issues
|
||||
**Check**:
|
||||
```powershell
|
||||
# Verify template exists
|
||||
dir conf\label_template.svg
|
||||
|
||||
# Check console for errors when printing
|
||||
# Should see: "Using SVG template: conf\label_template.svg"
|
||||
```
|
||||
|
||||
### Problem: Variables Not Replaced
|
||||
**Cause**: Template placeholders wrong
|
||||
**Fix**:
|
||||
- Open `conf\label_template.svg`
|
||||
- Verify placeholders are exactly:
|
||||
- `{Article}`
|
||||
- `{NrArt}`
|
||||
- `{Serial}`
|
||||
- Case-sensitive!
|
||||
|
||||
---
|
||||
|
||||
## 📊 Quality Settings Summary
|
||||
|
||||
| Setting | Value | Why |
|
||||
|---------|-------|-----|
|
||||
| PDF DPI | 1200 | Sharp text & images |
|
||||
| Paper Size | 35mm x 25mm | Correct label size |
|
||||
| Orientation | Landscape | Horizontal layout |
|
||||
| Print Quality | 600+ DPI | No dotted text |
|
||||
| Font Size | 8pt | Readable at 35mm width |
|
||||
| Compression | Disabled | No quality loss |
|
||||
|
||||
---
|
||||
|
||||
## 📁 Important Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `label_printer_gui.py` | Main GUI application |
|
||||
| `conf/label_template.svg` | Label layout template |
|
||||
| `conf/accepted.png` | Checkmark image |
|
||||
| `pdf_backup/` | PDF backups of all labels |
|
||||
| `logs/` | Print history logs |
|
||||
| `C:\Users\Public\Documents\check.txt` | Monitored input file |
|
||||
|
||||
---
|
||||
|
||||
## 🎨 Customizing Label Layout
|
||||
|
||||
### Edit the Template:
|
||||
1. Open `conf\label_template.svg` in:
|
||||
- Inkscape (free SVG editor)
|
||||
- Adobe Illustrator
|
||||
- Any SVG editor
|
||||
|
||||
2. Modify:
|
||||
- Text positions
|
||||
- Font sizes/colors
|
||||
- Add graphics/logos
|
||||
- Change layout
|
||||
|
||||
3. Keep placeholders:
|
||||
```xml
|
||||
<text>{Article}</text>
|
||||
<text>{NrArt}</text>
|
||||
<text>{Serial}</text>
|
||||
```
|
||||
|
||||
4. Save as **35mm x 25mm** document
|
||||
|
||||
5. Test:
|
||||
```powershell
|
||||
python test_quality.py
|
||||
```
|
||||
|
||||
**No code changes needed!** Template is reloaded each time.
|
||||
|
||||
---
|
||||
|
||||
## ✅ Verification Checklist
|
||||
|
||||
After setup, verify:
|
||||
|
||||
- [ ] Printer configured (35mm x 25mm, landscape, high quality)
|
||||
- [ ] Test label prints correctly (one label, right size)
|
||||
- [ ] Text is sharp (not dotted)
|
||||
- [ ] GUI starts without errors
|
||||
- [ ] Monitoring detects file changes
|
||||
- [ ] Variables are replaced in output
|
||||
- [ ] PDF backup is created
|
||||
- [ ] Log entry is saved
|
||||
|
||||
If all checked ✅ → **System working correctly!**
|
||||
|
||||
---
|
||||
|
||||
## 🆘 Quick Reference Commands
|
||||
|
||||
```powershell
|
||||
# Initial setup
|
||||
.\setup_printer.ps1
|
||||
|
||||
# Start application
|
||||
python label_printer_gui.py
|
||||
|
||||
# Test print
|
||||
python test_quality.py
|
||||
|
||||
# Check printer config
|
||||
.\configure_printer_quality.ps1
|
||||
|
||||
# View latest PDF
|
||||
cd pdf_backup
|
||||
ls | sort LastWriteTime | select -last 1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📞 Support
|
||||
|
||||
If problems persist:
|
||||
|
||||
1. **Check printer driver**: Update from manufacturer website
|
||||
2. **Verify label stock**: Correct thermal labels loaded
|
||||
3. **Test printer**: Print self-test page
|
||||
4. **Review logs**: Check `logs/print_log_*.csv`
|
||||
5. **Check PDFs**: Open latest PDF in `pdf_backup/` to verify content
|
||||
|
||||
---
|
||||
|
||||
**Version**: 3.0 - Simplified & Fixed
|
||||
**Last Updated**: February 13, 2026
|
||||
**Status**: ✅ Ready for Production
|
||||
270
old_code/WORKFLOW_CORRECTED.md
Normal file
270
old_code/WORKFLOW_CORRECTED.md
Normal file
@@ -0,0 +1,270 @@
|
||||
# Label Printing Workflow - Corrected & Restored
|
||||
|
||||
## 📋 Complete Workflow
|
||||
|
||||
### ✅ Correct Process (Now Working)
|
||||
|
||||
```
|
||||
1. File Monitoring
|
||||
↓
|
||||
txt file changes detected (e.g., "COM-2024-002;ART-67890;SN-20260212")
|
||||
↓
|
||||
2. Parse Data
|
||||
↓
|
||||
Split by semicolon:
|
||||
- Value 1 (Article/Comanda): "COM-2024-002"
|
||||
- Value 2 (Nr. Art.): "ART-67890"
|
||||
- Value 3 (Serial No.): "SN-20260212"
|
||||
↓
|
||||
3. Load SVG Template
|
||||
↓
|
||||
Read: conf/label_template.svg
|
||||
↓
|
||||
4. Replace Variables in Template
|
||||
↓
|
||||
{Article} → "COM-2024-002"
|
||||
{NrArt} → "ART-67890"
|
||||
{Serial} → "SN-20260212"
|
||||
↓
|
||||
5. Convert SVG → PDF
|
||||
↓
|
||||
CairoSVG converts to high-quality PDF @ 1200 DPI
|
||||
Saves to: pdf_backup/final_label_TIMESTAMP.pdf
|
||||
↓
|
||||
6. Print PDF
|
||||
↓
|
||||
SumatraPDF sends to configured printer
|
||||
↓
|
||||
7. Done! ✓
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Key Features
|
||||
|
||||
### 1. **Customizable Layout** (SVG Template)
|
||||
- Location: `conf/label_template.svg`
|
||||
- Users can edit this file to change:
|
||||
- Position of text fields
|
||||
- Font size and style
|
||||
- Graphics/images
|
||||
- Label dimensions
|
||||
- **No code changes needed!**
|
||||
|
||||
### 2. **Variable Placeholders**
|
||||
The template uses curly braces for variables:
|
||||
- `{Article}` - First value (Nr. Comanda)
|
||||
- `{NrArt}` - Second value (Nr. Art.)
|
||||
- `{Serial}` - Third value (Serial No.)
|
||||
|
||||
User can move these anywhere in the SVG template.
|
||||
|
||||
### 3. **Automatic File Monitoring**
|
||||
- Watches: The configured txt file
|
||||
- On change: Automatically reads and prints
|
||||
- No manual intervention needed
|
||||
|
||||
---
|
||||
|
||||
## 🔧 What Was Fixed
|
||||
|
||||
### Problem 1: SVG Template Was Disabled ❌
|
||||
**Before:** Code was using fallback PDF generation (hardcoded layout)
|
||||
**Now:** SVG template is properly enabled and used
|
||||
|
||||
### Problem 2: Poor SVG Rendering ❌
|
||||
**Before:** svglib was failing with many errors, causing fragmentedoutput
|
||||
**Now:** CairoSVG is used first (better font/rendering support)
|
||||
|
||||
### Problem 3: Extra Conversion Steps ❌
|
||||
**Before:** GhostScript was re-converting already good PDFs
|
||||
**Now:** Direct SVG → PDF → Print (no extra conversions)
|
||||
|
||||
---
|
||||
|
||||
## 📝 Data Flow Example
|
||||
|
||||
### Input File Content:
|
||||
```
|
||||
COM-2024-002;ART-67890;SN-20260212
|
||||
```
|
||||
|
||||
### Parsing:
|
||||
```python
|
||||
parts = text.split(';')
|
||||
article = parts[0] # "COM-2024-002"
|
||||
nr_art = parts[1] # "ART-67890"
|
||||
serial = parts[2] # "SN-20260212"
|
||||
```
|
||||
|
||||
### Template Before Replacement:
|
||||
```xml
|
||||
<text>Nr. Comanda:{Article}</text>
|
||||
<text>Nr. Art.:{NrArt}</text>
|
||||
<text>Serial No.:{Serial}</text>
|
||||
```
|
||||
|
||||
### Template After Replacement:
|
||||
```xml
|
||||
<text>Nr. Comanda:COM-2024-002</text>
|
||||
<text>Nr. Art.:ART-67890</text>
|
||||
<text>Serial No.:SN-20260212</text>
|
||||
```
|
||||
|
||||
### Output:
|
||||
- PDF file: `pdf_backup/final_label_20260213_HHMMSS.pdf`
|
||||
- Print: Sent to configured printer
|
||||
- Log: Entry added to `logs/print_log_20260213.csv`
|
||||
|
||||
---
|
||||
|
||||
## 🎨 How to Customize the Label Layout
|
||||
|
||||
1. **Open the template:**
|
||||
```
|
||||
conf/label_template.svg
|
||||
```
|
||||
|
||||
2. **Edit in any SVG editor:**
|
||||
- Inkscape (free)
|
||||
- Adobe Illustrator
|
||||
- CorelDRAW
|
||||
- Or any text editor
|
||||
|
||||
3. **Keep the variable placeholders:**
|
||||
- `{Article}`
|
||||
- `{NrArt}`
|
||||
- `{Serial}`
|
||||
|
||||
4. **Save the file**
|
||||
|
||||
5. **Next print will use the new layout!**
|
||||
|
||||
### Example Changes:
|
||||
- Move text to different positions
|
||||
- Change font size in the SVG
|
||||
- Add company logo
|
||||
- Change colors
|
||||
- Adjust spacing
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Testing the Workflow
|
||||
|
||||
### Test 1: Verify Template is Used
|
||||
```powershell
|
||||
.\venv\Scripts\python.exe label_printer_gui.py
|
||||
```
|
||||
|
||||
Watch console output - should see:
|
||||
```
|
||||
Using SVG template: conf\label_template.svg
|
||||
Converting SVG to PDF using CairoSVG (high quality)...
|
||||
✅ PDF created from SVG template: pdf_backup\final_label_...pdf
|
||||
```
|
||||
|
||||
### Test 2: Check the Generated PDF
|
||||
```powershell
|
||||
# Open latest PDF to verify content
|
||||
$latest = Get-ChildItem pdf_backup\*.pdf | Sort-Object LastWriteTime -Desc | Select-Object -First 1
|
||||
Start-Process $latest.FullName
|
||||
```
|
||||
|
||||
Verify you see:
|
||||
- ✅ Three lines of text (Nr. Comanda, Nr. Art., Serial No.)
|
||||
- ✅ Values filled in correctly
|
||||
- ✅ Checkmark image (if template has it)
|
||||
|
||||
### Test 3: Print Test
|
||||
Put sample data in your monitored file:
|
||||
```
|
||||
COM-TEST-001;ART-7777;SN-20260213
|
||||
```
|
||||
|
||||
Should automatically print with correct values.
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Configuration Files
|
||||
|
||||
### 1. **Label Template** (conf/label_template.svg)
|
||||
- **Purpose:** Defines layout, positions, fonts
|
||||
- **Editable:** Yes - by user
|
||||
- **Format:** SVG (XML-based vector graphics)
|
||||
|
||||
### 2. **App Configuration** (conf/app.conf)
|
||||
- **Purpose:** Stores GUI settings
|
||||
- **Contains:**
|
||||
- File path to monitor
|
||||
- Selected printer
|
||||
- Preview settings
|
||||
|
||||
### 3. **Images** (conf/*.png)
|
||||
- **accepted.png:** Checkmark/approval image (embedded in template)
|
||||
- **refused.png:** Rejection image (if needed)
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Complete Print Quality Settings
|
||||
|
||||
The system now maintains quality through:
|
||||
|
||||
1. **SVG Template** → Vector graphics (scalable, sharp)
|
||||
2. **CairoSVG Conversion** → Renders @ 1200 DPI
|
||||
3. **PDF Output** → Uncompressed, high quality
|
||||
4. **Printer Configuration** → Set to 600 DPI minimum
|
||||
5. **Direct Printing** → No extra conversions
|
||||
|
||||
---
|
||||
|
||||
## 📊 Workflow States
|
||||
|
||||
| Step | Status | Output |
|
||||
|------|--------|--------|
|
||||
| File changed | ✅ Working | Triggers processing |
|
||||
| Parse data | ✅ Working | Splits by `;` |
|
||||
| Load template | ✅ Working | Reads SVG file |
|
||||
| Replace variables | ✅ Working | Substitutes `{...}` |
|
||||
| SVG→PDF | ✅ Working | CairoSVG @ 1200 DPI |
|
||||
| Print | ✅ Working | SumatraPDF direct |
|
||||
|
||||
---
|
||||
|
||||
## 🐛 Troubleshooting
|
||||
|
||||
### Issue: "SVG template not found"
|
||||
**Solution:** Check that `conf/label_template.svg` exists
|
||||
|
||||
### Issue: "CairoSVG conversion failed"
|
||||
**Solution:**
|
||||
```powershell
|
||||
.\venv\Scripts\pip.exe install --upgrade cairosvg
|
||||
```
|
||||
|
||||
### Issue: Wrong values printed
|
||||
**Solution:** Verify data format in txt file: `value1;value2;value3`
|
||||
|
||||
### Issue: Printer prints blank/partial
|
||||
**Solution:** Run printer configuration:
|
||||
```powershell
|
||||
.\configure_label_size.ps1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📖 Summary
|
||||
|
||||
The workflow is now **fully restored** and **working correctly**:
|
||||
|
||||
✅ SVG template enabled for customizable layouts
|
||||
✅ Variable replacement working ({Article}, {NrArt}, {Serial})
|
||||
✅ High-quality PDF generation via CairoSVG
|
||||
✅ Direct printing without extra conversions
|
||||
✅ User can modify template without code changes
|
||||
|
||||
**No more hardcoded layouts!**
|
||||
|
||||
---
|
||||
|
||||
**Last Updated:** February 13, 2026
|
||||
**Status:** ✅ Workflow Restored & Working
|
||||
67
old_code/check_printer_quality.ps1
Normal file
67
old_code/check_printer_quality.ps1
Normal file
@@ -0,0 +1,67 @@
|
||||
# Check and configure printer quality settings for Labels printer
|
||||
|
||||
$printerName = "Labels"
|
||||
|
||||
Write-Host "=== Checking Printer: $printerName ===" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
# Get printer object
|
||||
$printer = Get-Printer -Name $printerName -ErrorAction SilentlyContinue
|
||||
|
||||
if ($null -eq $printer) {
|
||||
Write-Host "ERROR: Printer '$printerName' not found!" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "Printer Name: $($printer.Name)" -ForegroundColor Green
|
||||
Write-Host "Driver Name: $($printer.DriverName)" -ForegroundColor Green
|
||||
Write-Host "Port Name: $($printer.PortName)" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
|
||||
# Get printer configuration
|
||||
try {
|
||||
$printerConfig = Get-PrintConfiguration -PrinterName $printerName
|
||||
Write-Host "=== Current Print Configuration ===" -ForegroundColor Cyan
|
||||
Write-Host "Print Quality: $($printerConfig.PrintQuality)"
|
||||
Write-Host "Color Mode: $($printerConfig.Color)"
|
||||
Write-Host "Duplex Mode: $($printerConfig.DuplexingMode)"
|
||||
Write-Host ""
|
||||
} catch {
|
||||
Write-Host "Could not retrieve print configuration: $_" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
# Get printer driver properties
|
||||
Write-Host "=== Checking Printer Properties ===" -ForegroundColor Cyan
|
||||
try {
|
||||
$printerProperties = Get-PrinterProperty -PrinterName $printerName
|
||||
foreach ($prop in $printerProperties) {
|
||||
Write-Host "$($prop.PropertyName): $($prop.Value)"
|
||||
}
|
||||
} catch {
|
||||
Write-Host "Could not retrieve printer properties: $_" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "=== Recommendations ===" -ForegroundColor Cyan
|
||||
Write-Host "1. Open Windows Settings > Devices > Printers & scanners"
|
||||
Write-Host "2. Click on 'Labels' printer"
|
||||
Write-Host "3. Click 'Manage' > 'Printing preferences'"
|
||||
Write-Host "4. Look for quality settings and set to:"
|
||||
Write-Host " - Print Quality: Best/Highest/600 DPI or higher"
|
||||
Write-Host " - Graphics Mode: Vector or High Quality"
|
||||
Write-Host " - Dithering: None (for sharp text)"
|
||||
Write-Host "5. Save settings and try printing again"
|
||||
Write-Host ""
|
||||
Write-Host "Would you like to try setting print quality to high? (Y/N)" -ForegroundColor Yellow
|
||||
$response = Read-Host
|
||||
|
||||
if ($response -eq 'Y' -or $response -eq 'y') {
|
||||
try {
|
||||
# Try to set print quality to high
|
||||
Set-PrintConfiguration -PrinterName $printerName -PrintQuality 4 # 4 = High quality
|
||||
Write-Host "Print quality set to HIGH" -ForegroundColor Green
|
||||
} catch {
|
||||
Write-Host "Could not set print quality automatically: $_" -ForegroundColor Yellow
|
||||
Write-Host "Please set manually through printer preferences" -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
129
old_code/configure_label_size.ps1
Normal file
129
old_code/configure_label_size.ps1
Normal file
@@ -0,0 +1,129 @@
|
||||
# Quick Printer Configuration for 35mm x 25mm Labels
|
||||
# This script opens printer preferences for manual configuration
|
||||
|
||||
param(
|
||||
[string]$PrinterName = "Labels"
|
||||
)
|
||||
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Label Printer Size Configuration" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
# Check if printer exists
|
||||
$printer = Get-Printer -Name $PrinterName -ErrorAction SilentlyContinue
|
||||
|
||||
if ($null -eq $printer) {
|
||||
Write-Host "❌ ERROR: Printer '$PrinterName' not found!" -ForegroundColor Red
|
||||
Write-Host ""
|
||||
Write-Host "Available printers:" -ForegroundColor Yellow
|
||||
Get-Printer | ForEach-Object { Write-Host " - $($_.Name)" }
|
||||
Write-Host ""
|
||||
|
||||
$newName = Read-Host "Enter the correct printer name"
|
||||
if ($newName) {
|
||||
$PrinterName = $newName
|
||||
$printer = Get-Printer -Name $PrinterName -ErrorAction SilentlyContinue
|
||||
if ($null -eq $printer) {
|
||||
Write-Host "❌ Printer still not found. Exiting." -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
} else {
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "✅ Found printer: $PrinterName" -ForegroundColor Green
|
||||
Write-Host " Driver: $($printer.DriverName)" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Configuration Required" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "You need to configure the printer for:" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
Write-Host " Paper Size: 35mm x 25mm (3.5cm x 2.5cm)" -ForegroundColor White
|
||||
Write-Host " Orientation: Landscape" -ForegroundColor White
|
||||
Write-Host " Quality: Highest/Best" -ForegroundColor White
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "Opening printer preferences dialog..." -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "In the dialog that opens:" -ForegroundColor Yellow
|
||||
Write-Host " 1. Find 'Paper Size', 'Media', or 'Page Setup' tab" -ForegroundColor White
|
||||
Write-Host " 2. Look for label size options:" -ForegroundColor White
|
||||
Write-Host " - If you see '35mm x 25mm' → Select it" -ForegroundColor Green
|
||||
Write-Host " - If not, look for 'Custom' option" -ForegroundColor Green
|
||||
Write-Host " 3. For custom size:" -ForegroundColor White
|
||||
Write-Host " - Width: 35mm (or 3.5cm / 1.38 inches)" -ForegroundColor Green
|
||||
Write-Host " - Height: 25mm (or 2.5cm / 0.98 inches)" -ForegroundColor Green
|
||||
Write-Host " 4. Set Orientation: Landscape" -ForegroundColor White
|
||||
Write-Host " 5. Set Quality: Best/Highest/600 DPI" -ForegroundColor White
|
||||
Write-Host " 6. Click 'Apply' then 'OK'" -ForegroundColor White
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "Press any key to open printer preferences..." -ForegroundColor Yellow
|
||||
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
|
||||
|
||||
try {
|
||||
# Method 1: Try printui.dll (more reliable for preferences)
|
||||
Start-Process "rundll32.exe" -ArgumentList "printui.dll,PrintUIEntry /e /n `"$PrinterName`"" -Wait:$false
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "✅ Printer preferences dialog opened" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
Write-Host "After configuring:" -ForegroundColor Cyan
|
||||
Write-Host " 1. Close the preferences dialog" -ForegroundColor White
|
||||
Write-Host " 2. Test by running: python test_quality.py" -ForegroundColor White
|
||||
Write-Host " 3. Verify label prints on single 35mm x 25mm label" -ForegroundColor White
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Troubleshooting" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "If you can't find label size option:" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
Write-Host "Option A - Check Printer Documentation:" -ForegroundColor White
|
||||
Write-Host " Your printer: $($printer.DriverName)" -ForegroundColor Gray
|
||||
Write-Host " Look for supported label sizes in manual" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host "Option B - Use Printer's Software:" -ForegroundColor White
|
||||
Write-Host " Many label printers come with design software" -ForegroundColor Gray
|
||||
Write-Host " (e.g., Zebra Designer, Brother P-touch Editor)" -ForegroundColor Gray
|
||||
Write-Host " Configure size there, then note the settings" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host "Option C - Driver Update:" -ForegroundColor White
|
||||
Write-Host " Download latest driver from manufacturer" -ForegroundColor Gray
|
||||
Write-Host " Newer drivers often have better size options" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host "Option D - Use Alternative Method:" -ForegroundColor White
|
||||
Write-Host " Run: python print_with_size.py" -ForegroundColor Gray
|
||||
Write-Host " This will attempt to set size programmatically" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Common Label Sizes (Reference)" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "If 35mm x 25mm is not available, try:" -ForegroundColor Yellow
|
||||
Write-Host " • 40mm x 30mm (close match)" -ForegroundColor Gray
|
||||
Write-Host " • 50mm x 30mm (slightly larger)" -ForegroundColor Gray
|
||||
Write-Host " • 38mm x 25mm (common label size)" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host "Note: Using different size will affect layout" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
|
||||
} catch {
|
||||
Write-Host "❌ Error opening preferences: $_" -ForegroundColor Red
|
||||
Write-Host ""
|
||||
Write-Host "Alternative: Open manually" -ForegroundColor Yellow
|
||||
Write-Host " 1. Open: Settings > Printers > $PrinterName" -ForegroundColor White
|
||||
Write-Host " 2. Click: Manage > Printing preferences" -ForegroundColor White
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
Write-Host "Configuration script completed." -ForegroundColor Green
|
||||
Write-Host "Press any key to exit..." -ForegroundColor DarkGray
|
||||
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
|
||||
225
old_code/configure_printer_quality.ps1
Normal file
225
old_code/configure_printer_quality.ps1
Normal file
@@ -0,0 +1,225 @@
|
||||
# Enhanced Printer Quality Configuration Script
|
||||
# This script checks and optimizes printer settings for high-quality label printing
|
||||
|
||||
$printerName = "Labels"
|
||||
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Label Printer Quality Configuration" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
# Check if running as Administrator
|
||||
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
|
||||
|
||||
if (-not $isAdmin) {
|
||||
Write-Host "⚠️ Warning: Not running as Administrator" -ForegroundColor Yellow
|
||||
Write-Host "Some settings may require Administrator privileges" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
# Get printer object
|
||||
$printer = Get-Printer -Name $printerName -ErrorAction SilentlyContinue
|
||||
|
||||
if ($null -eq $printer) {
|
||||
Write-Host "❌ ERROR: Printer '$printerName' not found!" -ForegroundColor Red
|
||||
Write-Host ""
|
||||
Write-Host "Available printers:" -ForegroundColor Yellow
|
||||
Get-Printer | ForEach-Object { Write-Host " - $($_.Name)" }
|
||||
Write-Host ""
|
||||
Write-Host "Please check printer name and try again." -ForegroundColor Yellow
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Display printer information
|
||||
Write-Host "✅ Printer Found" -ForegroundColor Green
|
||||
Write-Host "Name: $($printer.Name)" -ForegroundColor White
|
||||
Write-Host "Driver: $($printer.DriverName)" -ForegroundColor White
|
||||
Write-Host "Port: $($printer.PortName)" -ForegroundColor White
|
||||
Write-Host "Status: $($printer.PrinterStatus)" -ForegroundColor White
|
||||
Write-Host ""
|
||||
|
||||
# Get current print configuration
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Current Print Configuration" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
try {
|
||||
$printerConfig = Get-PrintConfiguration -PrinterName $printerName
|
||||
|
||||
$qualityText = switch ($printerConfig.PrintQuality) {
|
||||
1 { "Draft (Low)" }
|
||||
2 { "Normal" }
|
||||
3 { "Better" }
|
||||
4 { "Best (High)" }
|
||||
default { "Unknown ($($printerConfig.PrintQuality))" }
|
||||
}
|
||||
|
||||
Write-Host "Print Quality: $qualityText" -ForegroundColor $(if ($printerConfig.PrintQuality -eq 4) { "Green" } else { "Yellow" })
|
||||
Write-Host "Color Mode: $($printerConfig.Color)" -ForegroundColor White
|
||||
Write-Host "Duplex Mode: $($printerConfig.DuplexingMode)" -ForegroundColor White
|
||||
Write-Host "Collate: $($printerConfig.Collate)" -ForegroundColor White
|
||||
Write-Host ""
|
||||
} catch {
|
||||
Write-Host "⚠️ Could not retrieve print configuration: $_" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
# Get printer driver properties
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Printer Properties & Capabilities" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
try {
|
||||
$printerProperties = Get-PrinterProperty -PrinterName $printerName
|
||||
|
||||
if ($printerProperties.Count -gt 0) {
|
||||
$printerProperties | ForEach-Object {
|
||||
Write-Host "$($_.PropertyName): $($_.Value)" -ForegroundColor Gray
|
||||
}
|
||||
} else {
|
||||
Write-Host "No additional properties found" -ForegroundColor Gray
|
||||
}
|
||||
Write-Host ""
|
||||
} catch {
|
||||
Write-Host "⚠️ Could not retrieve printer properties: $_" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
# Recommendations
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Quality Recommendations" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "For optimal label printing quality:" -ForegroundColor White
|
||||
Write-Host ""
|
||||
Write-Host "✓ Print Quality: Set to BEST/HIGHEST (4)" -ForegroundColor Green
|
||||
Write-Host "✓ DPI: 600 DPI or higher" -ForegroundColor Green
|
||||
Write-Host "✓ Print Speed: Medium to Slow (quality over speed)" -ForegroundColor Green
|
||||
Write-Host "✓ Darkness/Density: Medium-High (adjust for label material)" -ForegroundColor Green
|
||||
Write-Host "✓ Dithering: Disabled (for sharp text/barcodes)" -ForegroundColor Green
|
||||
Write-Host "✓ Graphics Mode: Vector or High Quality" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Configuration Steps" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "To configure manually:" -ForegroundColor Yellow
|
||||
Write-Host "1. Open: Settings > Devices > Printers & scanners" -ForegroundColor White
|
||||
Write-Host "2. Click: '$printerName' > Manage" -ForegroundColor White
|
||||
Write-Host "3. Click: 'Printing preferences'" -ForegroundColor White
|
||||
Write-Host "4. Configure quality settings as recommended above" -ForegroundColor White
|
||||
Write-Host "5. Click: Apply > OK" -ForegroundColor White
|
||||
Write-Host ""
|
||||
|
||||
# Attempt automatic configuration
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Automatic Configuration" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "Would you like to apply recommended settings automatically? (Y/N)" -ForegroundColor Yellow
|
||||
$response = Read-Host
|
||||
|
||||
if ($response -eq 'Y' -or $response -eq 'y') {
|
||||
Write-Host ""
|
||||
Write-Host "Applying settings..." -ForegroundColor Cyan
|
||||
|
||||
$settingsApplied = $false
|
||||
$errors = @()
|
||||
|
||||
# Try to set print quality to high (4 = Best)
|
||||
try {
|
||||
Set-PrintConfiguration -PrinterName $printerName -PrintQuality 4 -ErrorAction Stop
|
||||
Write-Host "✅ Print quality set to BEST (4)" -ForegroundColor Green
|
||||
$settingsApplied = $true
|
||||
} catch {
|
||||
$errors += "Print Quality: $_"
|
||||
Write-Host "⚠️ Could not set print quality: $_" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
# Try to disable duplexing for labels
|
||||
try {
|
||||
Set-PrintConfiguration -PrinterName $printerName -DuplexingMode OneSided -ErrorAction Stop
|
||||
Write-Host "✅ Duplex mode set to One-Sided" -ForegroundColor Green
|
||||
$settingsApplied = $true
|
||||
} catch {
|
||||
$errors += "Duplex Mode: $_"
|
||||
Write-Host "⚠️ Could not set duplex mode: $_" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
# Try to enable collation
|
||||
try {
|
||||
Set-PrintConfiguration -PrinterName $printerName -Collate $true -ErrorAction Stop
|
||||
Write-Host "✅ Collation enabled" -ForegroundColor Green
|
||||
$settingsApplied = $true
|
||||
} catch {
|
||||
$errors += "Collation: $_"
|
||||
Write-Host "⚠️ Could not set collation: $_" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
|
||||
if ($settingsApplied) {
|
||||
Write-Host "✅ Settings applied successfully!" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
Write-Host "Note: Some printer-specific settings (DPI, darkness, etc.)" -ForegroundColor Yellow
|
||||
Write-Host "must be configured through the printer preferences dialog." -ForegroundColor Yellow
|
||||
} else {
|
||||
Write-Host "❌ Could not apply automatic settings" -ForegroundColor Red
|
||||
Write-Host ""
|
||||
Write-Host "Reasons:" -ForegroundColor Yellow
|
||||
foreach ($err in $errors) {
|
||||
Write-Host " - $err" -ForegroundColor Gray
|
||||
}
|
||||
Write-Host ""
|
||||
Write-Host "Please configure manually through printer preferences." -ForegroundColor Yellow
|
||||
}
|
||||
} else {
|
||||
Write-Host ""
|
||||
Write-Host "Automatic configuration skipped." -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Testing Recommendations" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "After configuration, test with:" -ForegroundColor White
|
||||
Write-Host "1. Print a test label from the application" -ForegroundColor White
|
||||
Write-Host "2. Check text clarity and barcode scanning" -ForegroundColor White
|
||||
Write-Host "3. Adjust darkness if needed:" -ForegroundColor White
|
||||
Write-Host " - Too light: Increase darkness/temperature" -ForegroundColor White
|
||||
Write-Host " - Too dark: Decrease darkness/temperature" -ForegroundColor White
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Additional Resources" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "📄 See: PRINT_QUALITY_IMPROVEMENTS.md" -ForegroundColor White
|
||||
Write-Host " For detailed quality enhancement information" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host "🔧 Printer Driver: $($printer.DriverName)" -ForegroundColor White
|
||||
Write-Host " Check manufacturer website for latest updates" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
|
||||
# Check for common thermal printer brands and provide specific guidance
|
||||
$driverLower = $printer.DriverName.ToLower()
|
||||
|
||||
if ($driverLower -match "zebra") {
|
||||
Write-Host "📌 Zebra Printer Detected" -ForegroundColor Cyan
|
||||
Write-Host " Recommended: Set darkness to 15-25 (0-30 scale)" -ForegroundColor Gray
|
||||
Write-Host " Access via: Preferences > Advanced > Darkness" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
} elseif ($driverLower -match "dymo") {
|
||||
Write-Host "📌 Dymo Printer Detected" -ForegroundColor Cyan
|
||||
Write-Host " Recommended: Set quality to 'High Quality'" -ForegroundColor Gray
|
||||
Write-Host " Access via: Preferences > Quality tab" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
} elseif ($driverLower -match "brother") {
|
||||
Write-Host "📌 Brother Printer Detected" -ForegroundColor Cyan
|
||||
Write-Host " Recommended: Set resolution to highest available" -ForegroundColor Gray
|
||||
Write-Host " Access via: Printing Preferences > Advanced" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
Write-Host "Press any key to exit..." -ForegroundColor DarkGray
|
||||
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
|
||||
135
old_code/print_pdf_ghostscript.py
Normal file
135
old_code/print_pdf_ghostscript.py
Normal file
@@ -0,0 +1,135 @@
|
||||
"""
|
||||
Alternative PDF printing using GhostScript for superior quality.
|
||||
GhostScript maintains vector quality better than SumatraPDF.
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import os
|
||||
import sys
|
||||
|
||||
def find_ghostscript():
|
||||
"""
|
||||
Find GhostScript installation on Windows.
|
||||
|
||||
Returns:
|
||||
str: Path to gswin64c.exe or gswin32c.exe, or None if not found
|
||||
"""
|
||||
possible_paths = [
|
||||
r"C:\Program Files\gs\gs10.04.0\bin\gswin64c.exe",
|
||||
r"C:\Program Files\gs\gs10.03.1\bin\gswin64c.exe",
|
||||
r"C:\Program Files\gs\gs10.03.0\bin\gswin64c.exe",
|
||||
r"C:\Program Files\gs\gs10.02.1\bin\gswin64c.exe",
|
||||
r"C:\Program Files\gs\gs10.02.0\bin\gswin64c.exe",
|
||||
r"C:\Program Files\gs\gs10.01.2\bin\gswin64c.exe",
|
||||
r"C:\Program Files\gs\gs10.01.1\bin\gswin64c.exe",
|
||||
r"C:\Program Files\gs\gs10.01.0\bin\gswin64c.exe",
|
||||
r"C:\Program Files (x86)\gs\gs10.04.0\bin\gswin32c.exe",
|
||||
r"C:\Program Files (x86)\gs\gs10.03.1\bin\gswin32c.exe",
|
||||
r"C:\Program Files (x86)\gs\gs10.03.0\bin\gswin32c.exe",
|
||||
]
|
||||
|
||||
# Check standard locations
|
||||
for path in possible_paths:
|
||||
if os.path.exists(path):
|
||||
return path
|
||||
|
||||
# Search in gs directory
|
||||
for program_files in [r"C:\Program Files", r"C:\Program Files (x86)"]:
|
||||
gs_base = os.path.join(program_files, "gs")
|
||||
if os.path.exists(gs_base):
|
||||
for version_dir in os.listdir(gs_base):
|
||||
for exe_name in ["gswin64c.exe", "gswin32c.exe"]:
|
||||
gs_path = os.path.join(gs_base, version_dir, "bin", exe_name)
|
||||
if os.path.exists(gs_path):
|
||||
return gs_path
|
||||
|
||||
return None
|
||||
|
||||
def print_pdf_with_ghostscript(pdf_path, printer_name):
|
||||
"""
|
||||
Print PDF using GhostScript for maximum quality.
|
||||
GhostScript renders PDF at high resolution and maintains vector quality.
|
||||
|
||||
Args:
|
||||
pdf_path (str): Path to PDF file
|
||||
printer_name (str): Name of the printer
|
||||
|
||||
Returns:
|
||||
bool: True if successful
|
||||
"""
|
||||
gs_path = find_ghostscript()
|
||||
|
||||
if not gs_path:
|
||||
print("GhostScript not found. Install from: https://ghostscript.com/releases/gsdnld.html")
|
||||
return False
|
||||
|
||||
try:
|
||||
# GhostScript command for high-quality printing
|
||||
# -dNOPAUSE: Don't pause between pages
|
||||
# -dBATCH: Exit after processing
|
||||
# -sDEVICE=mswinpr2: Windows printer device (high quality)
|
||||
# -dNOSAFER: Allow file operations
|
||||
# -r1200: 1200 DPI resolution
|
||||
# -sOutputFile: Printer name with %printer% syntax
|
||||
|
||||
cmd = [
|
||||
gs_path,
|
||||
'-dNOPAUSE',
|
||||
'-dBATCH',
|
||||
'-sDEVICE=mswinpr2', # Windows printer with high quality
|
||||
'-dNOSAFER',
|
||||
'-r1200', # 1200 DPI - matches our PDF quality
|
||||
'-dTextAlphaBits=4', # Anti-aliasing for text
|
||||
'-dGraphicsAlphaBits=4', # Anti-aliasing for graphics
|
||||
f'-sOutputFile=%printer%{printer_name}',
|
||||
pdf_path
|
||||
]
|
||||
|
||||
print(f"Printing with GhostScript at 1200 DPI...")
|
||||
result = subprocess.run(
|
||||
cmd,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0
|
||||
)
|
||||
|
||||
print(f"✅ Label sent to printer via GhostScript: {printer_name}")
|
||||
return True
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"GhostScript print failed: {e}")
|
||||
if e.stderr:
|
||||
print(f"Error details: {e.stderr}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"Error printing with GhostScript: {e}")
|
||||
return False
|
||||
|
||||
def check_ghostscript_available():
|
||||
"""
|
||||
Check if GhostScript is available.
|
||||
|
||||
Returns:
|
||||
tuple: (available: bool, path: str or None)
|
||||
"""
|
||||
gs_path = find_ghostscript()
|
||||
return (gs_path is not None, gs_path)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Test GhostScript availability
|
||||
available, gs_path = check_ghostscript_available()
|
||||
|
||||
if available:
|
||||
print(f"✅ GhostScript found at: {gs_path}")
|
||||
print("GhostScript is available for high-quality PDF printing")
|
||||
else:
|
||||
print("❌ GhostScript not found")
|
||||
print("\nTo install GhostScript:")
|
||||
print("1. Download from: https://ghostscript.com/releases/gsdnld.html")
|
||||
print("2. Install the Windows 64-bit version")
|
||||
print("3. Restart your application")
|
||||
print("\nGhostScript provides superior print quality by:")
|
||||
print(" • Maintaining vector graphics quality")
|
||||
print(" • Rendering at full 1200 DPI")
|
||||
print(" • Better text anti-aliasing")
|
||||
222
old_code/print_with_size.py
Normal file
222
old_code/print_with_size.py
Normal file
@@ -0,0 +1,222 @@
|
||||
"""
|
||||
Improved printing module that explicitly sets paper size for thermal label printers.
|
||||
This prevents the printer from using default paper size (continuous roll).
|
||||
"""
|
||||
|
||||
import win32print
|
||||
import win32ui
|
||||
import win32con
|
||||
from PIL import Image
|
||||
import os
|
||||
|
||||
def mm_to_inches(mm):
|
||||
"""Convert millimeters to inches"""
|
||||
return mm / 25.4
|
||||
|
||||
def mm_to_hundredths_inch(mm):
|
||||
"""Convert millimeters to hundredths of an inch (used by Windows print API)"""
|
||||
return int(mm_to_inches(mm) * 100)
|
||||
|
||||
def print_pdf_with_custom_size(pdf_path, printer_name, width_mm=35, height_mm=25):
|
||||
"""
|
||||
Print PDF with explicit paper size settings for thermal label printers.
|
||||
|
||||
Args:
|
||||
pdf_path (str): Path to PDF file
|
||||
printer_name (str): Name of the printer
|
||||
width_mm (int): Label width in millimeters (default 35mm)
|
||||
height_mm (int): Label height in millimeters (default 25mm)
|
||||
|
||||
Returns:
|
||||
bool: True if successful
|
||||
"""
|
||||
try:
|
||||
# Convert PDF to image first for better control
|
||||
from pdf2image import pdfimages
|
||||
print("Converting PDF to image for precise printing...")
|
||||
|
||||
# Use pdftoppm or pdf2image
|
||||
import subprocess
|
||||
|
||||
# Try using pdftoppm if available
|
||||
temp_image = pdf_path.replace('.pdf', '_temp.png')
|
||||
|
||||
try:
|
||||
# Try pdftoppm first (better quality)
|
||||
subprocess.run([
|
||||
'pdftoppm',
|
||||
'-png',
|
||||
'-singlefile',
|
||||
'-r', '1200', # High DPI
|
||||
pdf_path,
|
||||
pdf_path.replace('.pdf', '_temp')
|
||||
], check=True)
|
||||
except:
|
||||
# Fallback: convert using Pillow/reportlab
|
||||
from reportlab.pdfgen import canvas
|
||||
from PyPDF2 import PdfReader
|
||||
print("Using alternative PDF conversion method...")
|
||||
|
||||
if os.path.exists(temp_image):
|
||||
return print_image_with_custom_size(temp_image, printer_name, width_mm, height_mm)
|
||||
else:
|
||||
print("Could not convert PDF to image")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in advanced printing: {e}")
|
||||
return False
|
||||
|
||||
def print_image_with_custom_size(image_path, printer_name, width_mm=35, height_mm=25):
|
||||
"""
|
||||
Print image with explicit paper size for thermal label printers.
|
||||
|
||||
Args:
|
||||
image_path (str): Path to image file
|
||||
printer_name (str): Name of the printer
|
||||
width_mm (int): Label width in millimeters
|
||||
height_mm (int): Label height in millimeters
|
||||
|
||||
Returns:
|
||||
bool: True if successful
|
||||
"""
|
||||
try:
|
||||
# Open the printer
|
||||
hprinter = win32print.OpenPrinter(printer_name)
|
||||
|
||||
try:
|
||||
# Get printer device context
|
||||
hdc = win32ui.CreateDC()
|
||||
hdc.CreatePrinterDC(printer_name)
|
||||
|
||||
# Get printer properties
|
||||
props = win32print.GetPrinter(hprinter, 2)
|
||||
|
||||
# Get DEVMODE structure
|
||||
devmode = props["pDevMode"]
|
||||
|
||||
# Set custom paper size (DMPAPER_USER = 256)
|
||||
devmode.PaperSize = 256 # Custom paper size
|
||||
|
||||
# Set paper dimensions in tenths of millimeter
|
||||
devmode.PaperLength = height_mm * 10 # Height in 0.1mm units
|
||||
devmode.PaperWidth = width_mm * 10 # Width in 0.1mm units
|
||||
|
||||
# Set orientation to landscape (2) for 35x25mm
|
||||
devmode.Orientation = 2 # 2 = Landscape
|
||||
|
||||
# Set print quality to high
|
||||
devmode.PrintQuality = win32print.DMRES_HIGH
|
||||
|
||||
# Apply the devmode
|
||||
props["pDevMode"] = devmode
|
||||
win32print.SetPrinter(hprinter, 2, props, 0)
|
||||
|
||||
# Start document
|
||||
doc_info = ("Label Print", None, None, 0)
|
||||
hdc.StartDoc("Label Print")
|
||||
hdc.StartPage()
|
||||
|
||||
# Load image
|
||||
img = Image.open(image_path)
|
||||
|
||||
# Get printer DPI
|
||||
printer_dpi_x = hdc.GetDeviceCaps(win32con.LOGPIXELSX)
|
||||
printer_dpi_y = hdc.GetDeviceCaps(win32con.LOGPIXELSY)
|
||||
|
||||
# Calculate image size in pixels based on mm dimensions
|
||||
width_pixels = int(mm_to_inches(width_mm) * printer_dpi_x)
|
||||
height_pixels = int(mm_to_inches(height_mm) * printer_dpi_y)
|
||||
|
||||
# Resize image to exact label dimensions
|
||||
img_resized = img.resize((width_pixels, height_pixels), Image.Resampling.LANCZOS)
|
||||
|
||||
# Convert to bitmap
|
||||
dib = ImageWin.Dib(img_resized)
|
||||
|
||||
# Print at position (0,0) with exact size
|
||||
dib.draw(hdc.GetHandleOutput(), (0, 0, width_pixels, height_pixels))
|
||||
|
||||
# End document
|
||||
hdc.EndPage()
|
||||
hdc.EndDoc()
|
||||
|
||||
print(f"Label printed successfully with custom size: {width_mm}x{height_mm}mm")
|
||||
return True
|
||||
|
||||
finally:
|
||||
win32print.ClosePrinter(hprinter)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error printing with custom size: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
def set_printer_paper_size(printer_name, width_mm=35, height_mm=25):
|
||||
"""
|
||||
Configure printer to use custom paper size.
|
||||
This sets the printer default to the label size.
|
||||
|
||||
Args:
|
||||
printer_name (str): Name of the printer
|
||||
width_mm (int): Label width in millimeters
|
||||
height_mm (int): Label height in millimeters
|
||||
|
||||
Returns:
|
||||
bool: True if successful
|
||||
"""
|
||||
try:
|
||||
hprinter = win32print.OpenPrinter(printer_name)
|
||||
|
||||
try:
|
||||
# Get current printer properties
|
||||
props = win32print.GetPrinter(hprinter, 2)
|
||||
devmode = props["pDevMode"]
|
||||
|
||||
# Configure for custom label size
|
||||
devmode.PaperSize = 256 # DMPAPER_USER (custom)
|
||||
devmode.PaperLength = height_mm * 10 # in 0.1mm units
|
||||
devmode.PaperWidth = width_mm * 10 # in 0.1mm units
|
||||
devmode.Orientation = 2 # Landscape
|
||||
devmode.PrintQuality = win32print.DMRES_HIGH
|
||||
|
||||
# Update fields flags
|
||||
devmode.Fields = (
|
||||
win32print.DM_PAPERSIZE |
|
||||
win32print.DM_PAPERLENGTH |
|
||||
win32print.DM_PAPERWIDTH |
|
||||
win32print.DM_ORIENTATION |
|
||||
win32print.DM_PRINTQUALITY
|
||||
)
|
||||
|
||||
# Apply settings
|
||||
props["pDevMode"] = devmode
|
||||
win32print.SetPrinter(hprinter, 2, props, 0)
|
||||
|
||||
print(f"Printer '{printer_name}' configured for {width_mm}x{height_mm}mm labels")
|
||||
return True
|
||||
|
||||
finally:
|
||||
win32print.ClosePrinter(hprinter)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error configuring printer: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Test configuration
|
||||
printer_name = "Labels"
|
||||
|
||||
print("Testing printer configuration...")
|
||||
success = set_printer_paper_size(printer_name, 35, 25)
|
||||
|
||||
if success:
|
||||
print("\n✅ Printer configured successfully!")
|
||||
print("The printer should now use 35x25mm label size by default.")
|
||||
else:
|
||||
print("\n❌ Failed to configure printer")
|
||||
print("You may need to set the paper size manually in printer preferences.")
|
||||
128
old_code/setup_printer.ps1
Normal file
128
old_code/setup_printer.ps1
Normal file
@@ -0,0 +1,128 @@
|
||||
# Manual Label Printer Setup - 35mm x 25mm Labels
|
||||
# Optimized for: Citizen CTS-310, Zebra ZD420, Zebra ZD421
|
||||
# Run this script ONCE to configure your printer correctly
|
||||
|
||||
$printerName = "Labels"
|
||||
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " THERMAL LABEL PRINTER CONFIGURATION" -ForegroundColor Cyan
|
||||
Write-Host " Citizen CTS-310 / Zebra ZD420/ZD421" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
# Step 1: Open Printer Preferences
|
||||
Write-Host "STEP 1: Configure Label Size & Print Settings" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
Write-Host "We will open the printer preferences dialog." -ForegroundColor White
|
||||
Write-Host "You MUST configure these settings:" -ForegroundColor Red
|
||||
Write-Host ""
|
||||
Write-Host " [x] Media/Paper Type: LABELS (not continuous/receipt)" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
Write-Host " [x] Label Size: 35mm x 25mm" -ForegroundColor Green
|
||||
Write-Host " Common names in driver:" -ForegroundColor Gray
|
||||
Write-Host " - '35mm x 25mm'" -ForegroundColor Gray
|
||||
Write-Host " - '1.38in x 0.98in'" -ForegroundColor Gray
|
||||
Write-Host " - 'Custom' -> Width: 35mm, Height: 25mm" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host " [x] Orientation: LANDSCAPE (35mm wide, 25mm tall)" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
Write-Host " [x] Print Mode: THERMAL DIRECT or THERMAL TRANSFER" -ForegroundColor Green
|
||||
Write-Host " - Match your label stock type" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host " [x] Print Density/Darkness: 10-15 (medium)" -ForegroundColor Green
|
||||
Write-Host " - Zebra: 10-15 on scale of 0-30" -ForegroundColor Gray
|
||||
Write-Host " - Citizen: Medium darkness setting" -ForegroundColor Gray
|
||||
Write-Host " - Adjust if too light/dark after test" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host " [x] Print Speed: Medium (4-6 inches/sec)" -ForegroundColor Green
|
||||
Write-Host " - Slower = better quality" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host " [x] Print Quality/Resolution: 203 DPI or 300 DPI" -ForegroundColor Green
|
||||
Write-Host " - Use highest available (203 or 300)" -ForegroundColor Gray
|
||||
Write-Host " - NOT draft mode" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host "Press Enter to open printer preferences..." -ForegroundColor Yellow
|
||||
Read-Host
|
||||
|
||||
# Open Printer Preferences
|
||||
Write-Host "Opening printer preferences dialog..." -ForegroundColor Cyan
|
||||
Start-Process "rundll32" -ArgumentList "printui.dll,PrintUIEntry /e /n$printerName" -Wait:$false
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "After configuring the printer:" -ForegroundColor Yellow
|
||||
Write-Host "1. Click OK/Apply to save settings" -ForegroundColor White
|
||||
Write-Host "2. Close all printer dialogs" -ForegroundColor White
|
||||
Write-Host "3. Return here and press Enter" -ForegroundColor White
|
||||
Write-Host ""
|
||||
Read-Host "Press Enter when you've configured the printer"
|
||||
|
||||
# Step 2: Test Print
|
||||
Write-Host ""
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " STEP 2: Test Print" -ForegroundColor Yellow
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
$testPrint = Read-Host "Would you like to print a test label now? (Y/N)"
|
||||
|
||||
if ($testPrint -eq 'Y' -or $testPrint -eq 'y') {
|
||||
Write-Host ""
|
||||
Write-Host "Generating test label..." -ForegroundColor Cyan
|
||||
|
||||
# Check if test script exists
|
||||
if (Test-Path "test_quality.py") {
|
||||
& python test_quality.py
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Check the printed label:" -ForegroundColor Yellow
|
||||
Write-Host " [?] Is it 35mm x 25mm (about business card size)?" -ForegroundColor White
|
||||
Write-Host " [?] Is the text sharp and clear (not dotted)?" -ForegroundColor White
|
||||
Write-Host " [?] Is the orientation correct (landscape)?" -ForegroundColor White
|
||||
Write-Host ""
|
||||
|
||||
$result = Read-Host "Did the test print correctly? (Y/N)"
|
||||
|
||||
if ($result -eq 'Y' -or $result -eq 'y') {
|
||||
Write-Host ""
|
||||
Write-Host "SUCCESS! Printer is configured correctly." -ForegroundColor Green
|
||||
Write-Host "You can now use the label printer application." -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host ""
|
||||
Write-Host "Test failed. Common issues:" -ForegroundColor Red
|
||||
Write-Host " - Wrong size? Check Media Type is set to LABELS (not Continuous)" -ForegroundColor Yellow
|
||||
Write-Host " - Dotted text? Increase darkness to 12-15" -ForegroundColor Yellow
|
||||
Write-Host " - Too dark? Decrease darkness to 8-10" -ForegroundColor Yellow
|
||||
Write-Host " - Wrong orientation? Change to LANDSCAPE" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
Write-Host "Re-run this script to try again." -ForegroundColor White
|
||||
}
|
||||
} else {
|
||||
Write-Host ""
|
||||
Write-Host "test_quality.py not found. Creating simple test..." -ForegroundColor Yellow
|
||||
|
||||
# Create a simple test file
|
||||
$testData = "TEST;12345;SN001"
|
||||
Set-Content -Path "C:\Users\Public\Documents\check.txt" -Value $testData
|
||||
|
||||
Write-Host "Test data written to check.txt" -ForegroundColor Green
|
||||
Write-Host "Make sure the label printer GUI is running to process it." -ForegroundColor White
|
||||
}
|
||||
} else {
|
||||
Write-Host ""
|
||||
Write-Host "Setup complete!" -ForegroundColor Green
|
||||
Write-Host "Run the label printer GUI to start printing." -ForegroundColor White
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " Configuration Notes" -ForegroundColor Yellow
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "Remember:" -ForegroundColor White
|
||||
Write-Host " - Media Type MUST be 'LABELS' (enables gap sensor)" -ForegroundColor Yellow
|
||||
Write-Host " - This prevents continuous roll printing" -ForegroundColor Yellow
|
||||
Write-Host " - Adjust darkness if text is too light/dark" -ForegroundColor Yellow
|
||||
Write-Host " - These settings apply to all print jobs" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
Write-Host "Press any key to exit..." -ForegroundColor Gray
|
||||
Read-Host
|
||||
20
old_code/test_data_examples.txt
Normal file
20
old_code/test_data_examples.txt
Normal file
@@ -0,0 +1,20 @@
|
||||
# Test data for label printing with new features
|
||||
|
||||
# Format: ARTICLE;NR_ART;SERIAL;TEMPLATE_TYPE;COUNT
|
||||
# TEMPLATE_TYPE: 0 = OK template, 1 = NOK template
|
||||
# COUNT: Number of labels to print (1-100)
|
||||
|
||||
# Example 1: Print 1 OK label
|
||||
COM-2024-001;ART-12345;SN-001;0;1
|
||||
|
||||
# Example 2: Print 3 OK labels
|
||||
# COM-2024-002;ART-67890;SN-002;0;3
|
||||
|
||||
# Example 3: Print 1 NOK label
|
||||
# COM-2024-003;ART-11111;SN-003;1;1
|
||||
|
||||
# Example 4: Print 5 NOK labels
|
||||
# COM-2024-004;ART-22222;SN-004;1;5
|
||||
|
||||
# Backward compatibility: Old format still works (defaults to OK template, 1 copy)
|
||||
# COM-2024-005;ART-33333;SN-005
|
||||
BIN
old_code/test_label.pdf
Normal file
BIN
old_code/test_label.pdf
Normal file
Binary file not shown.
38
old_code/test_landscape.py
Normal file
38
old_code/test_landscape.py
Normal file
@@ -0,0 +1,38 @@
|
||||
"""
|
||||
Quick test script for label printing with landscape orientation
|
||||
"""
|
||||
import os
|
||||
from print_label import create_label_pdf, print_to_printer
|
||||
|
||||
print("=" * 60)
|
||||
print("Label Printer Test - Landscape Orientation")
|
||||
print("=" * 60)
|
||||
print()
|
||||
|
||||
# Test data
|
||||
test_data = "TEST-LAND;123456;SN-2026"
|
||||
|
||||
print("1. Generating PDF from SVG template...")
|
||||
pdf_file = create_label_pdf(test_data)
|
||||
print(f" ✓ PDF created: {pdf_file}")
|
||||
print()
|
||||
|
||||
# Check file size
|
||||
if os.path.exists(pdf_file):
|
||||
size = os.path.getsize(pdf_file)
|
||||
print(f"2. PDF file size: {size} bytes")
|
||||
print()
|
||||
|
||||
print("3. To print:")
|
||||
print(" a) Open the PDF and verify it's 35mm x 25mm landscape")
|
||||
print(" b) Print using your thermal printer (pre-configured for 35mm x 25mm)")
|
||||
print(" c) Or use SumatraPDF command:")
|
||||
print()
|
||||
print(f' .\\conf\\SumatraPDF.exe -print-to "YourPrinterName" "{pdf_file}" -print-settings noscale -silent -exit-when-done')
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("For Microsoft Print to PDF:")
|
||||
print(" - This printer uses standard page sizes (A4/Letter)")
|
||||
print(" - The label will be placed on a larger page")
|
||||
print(" - For actual label printing, use a thermal printer")
|
||||
print("=" * 60)
|
||||
147
old_code/test_quality.py
Normal file
147
old_code/test_quality.py
Normal file
@@ -0,0 +1,147 @@
|
||||
"""
|
||||
Test script to generate a quality test label
|
||||
This script creates a test label with all features to verify quality improvements
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add parent directory to path
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from print_label import create_label_pdf, get_available_printers, print_to_printer
|
||||
import datetime
|
||||
|
||||
def generate_quality_test_label():
|
||||
"""Generate a test label to verify quality improvements"""
|
||||
|
||||
print("=" * 60)
|
||||
print(" Label Quality Test - Verification Script")
|
||||
print("=" * 60)
|
||||
print()
|
||||
|
||||
# Test data with varied character types
|
||||
test_data = {
|
||||
'article': 'TEST-123-ABC', # Mixed alphanumeric
|
||||
'nr_art': '999988887777', # All numeric (barcode test)
|
||||
'serial': 'SN-2026-XY-001' # Complex serial number
|
||||
}
|
||||
|
||||
# Create test label string
|
||||
label_text = f"{test_data['article']};{test_data['nr_art']};{test_data['serial']}"
|
||||
|
||||
print("Test Label Data:")
|
||||
print(f" Nr. Comanda: {test_data['article']}")
|
||||
print(f" Nr. Art.: {test_data['nr_art']}")
|
||||
print(f" Serial No.: {test_data['serial']}")
|
||||
print()
|
||||
|
||||
# Generate PDF
|
||||
print("Generating high-quality test label PDF...")
|
||||
try:
|
||||
pdf_path = create_label_pdf(label_text)
|
||||
|
||||
if pdf_path and os.path.exists(pdf_path):
|
||||
print(f"✅ PDF generated successfully!")
|
||||
print(f" Location: {pdf_path}")
|
||||
print()
|
||||
|
||||
# Get file size
|
||||
file_size = os.path.getsize(pdf_path)
|
||||
print(f" File size: {file_size:,} bytes")
|
||||
|
||||
# Larger file size indicates uncompressed, higher quality
|
||||
if file_size > 50000: # > 50 KB suggests good quality
|
||||
print(" ✅ Good file size (uncompressed for quality)")
|
||||
else:
|
||||
print(" ⚠️ Small file size (may be compressed)")
|
||||
print()
|
||||
|
||||
# Ask if user wants to print
|
||||
print("Available printers:")
|
||||
printers = get_available_printers()
|
||||
for idx, printer in enumerate(printers, 1):
|
||||
print(f" {idx}. {printer}")
|
||||
print()
|
||||
|
||||
response = input("Print test label? (Y/N): ").strip().upper()
|
||||
|
||||
if response == 'Y':
|
||||
print()
|
||||
printer_idx = input(f"Select printer (1-{len(printers)}): ").strip()
|
||||
|
||||
try:
|
||||
printer_idx = int(printer_idx) - 1
|
||||
if 0 <= printer_idx < len(printers):
|
||||
selected_printer = printers[printer_idx]
|
||||
print(f"\nPrinting to: {selected_printer}")
|
||||
print("Please wait...")
|
||||
|
||||
success = print_to_printer(selected_printer, pdf_path)
|
||||
|
||||
if success:
|
||||
print("\n✅ Print job sent successfully!")
|
||||
print()
|
||||
print("Quality Check Checklist:")
|
||||
print(" □ Is text sharp and readable?")
|
||||
print(" □ Is the checkmark image crisp?")
|
||||
print(" □ Are there no pixelation artifacts?")
|
||||
print()
|
||||
print("If quality is still poor:")
|
||||
print(" 1. Run: .\\configure_printer_quality.ps1")
|
||||
print(" 2. Adjust printer darkness/density")
|
||||
print(" 3. Check printer driver is up to date")
|
||||
print(" 4. Verify correct label material is loaded")
|
||||
else:
|
||||
print("\n⚠️ Print job may have failed")
|
||||
else:
|
||||
print("Invalid printer selection")
|
||||
except ValueError:
|
||||
print("Invalid input")
|
||||
else:
|
||||
print("\nPrint skipped. You can print the PDF manually from:")
|
||||
print(f" {pdf_path}")
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("Quality Test Information:")
|
||||
print("=" * 60)
|
||||
print()
|
||||
print("This test label uses the following quality settings:")
|
||||
print(" • DPI: 1200 (increased from 600)")
|
||||
print(" • Font Size: 8pt (increased from 6pt)")
|
||||
print(" • PDF Compression: Disabled (was enabled)")
|
||||
print(" • Image Mode: RGB (was Grayscale)")
|
||||
print(" • Image Resampling: Modern API (fixed)")
|
||||
print()
|
||||
print("Expected improvements:")
|
||||
print(" ✓ Sharper, more legible text")
|
||||
print(" ✓ Crisper image rendering")
|
||||
print(" ✓ Better contrast and clarity")
|
||||
print()
|
||||
print("See PRINT_QUALITY_IMPROVEMENTS.md for full details")
|
||||
print()
|
||||
|
||||
else:
|
||||
print("❌ Failed to generate PDF")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error generating test label: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
if __name__ == "__main__":
|
||||
print()
|
||||
success = generate_quality_test_label()
|
||||
print()
|
||||
|
||||
if not success:
|
||||
print("Test failed. Please check error messages above.")
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("Test completed successfully!")
|
||||
sys.exit(0)
|
||||
159
old_code/test_svg_template.py
Normal file
159
old_code/test_svg_template.py
Normal file
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
Test SVG template functionality
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Import the PDF generator
|
||||
from print_label_pdf import PDFLabelGenerator
|
||||
|
||||
def test_svg_template():
|
||||
"""Test SVG template with sample data"""
|
||||
print("=== Testing SVG Template Functionality ===\n")
|
||||
|
||||
# Check if template exists
|
||||
template_path = os.path.join('conf', 'label_template.svg')
|
||||
if not os.path.exists(template_path):
|
||||
print(f"❌ Template not found: {template_path}")
|
||||
return False
|
||||
|
||||
print(f"✓ Template found: {template_path}")
|
||||
|
||||
# Sample data
|
||||
test_data = {
|
||||
'Article': 'COM-2024-001',
|
||||
'NrArt': 'ART-12345',
|
||||
'Serial': 'SN-20260212-001'
|
||||
}
|
||||
|
||||
print(f"✓ Test data: {test_data}")
|
||||
|
||||
# Create generator
|
||||
generator = PDFLabelGenerator()
|
||||
print("✓ PDF generator initialized")
|
||||
|
||||
# Test SVG template method
|
||||
print("\n--- Testing SVG Template Method ---")
|
||||
try:
|
||||
pdf_output = 'test_label_svg.pdf'
|
||||
result = generator.create_label_from_svg_template(
|
||||
template_path,
|
||||
test_data,
|
||||
filename=pdf_output
|
||||
)
|
||||
|
||||
if result and os.path.exists(pdf_output):
|
||||
file_size = os.path.getsize(pdf_output)
|
||||
print(f"✓ SVG template PDF created: {pdf_output} ({file_size} bytes)")
|
||||
return True
|
||||
else:
|
||||
print("❌ SVG template PDF creation failed")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
def test_programmatic_layout():
|
||||
"""Test programmatic layout (fallback)"""
|
||||
print("\n--- Testing Programmatic Layout (Fallback) ---")
|
||||
|
||||
generator = PDFLabelGenerator()
|
||||
|
||||
try:
|
||||
pdf_output = 'test_label_programmatic.pdf'
|
||||
result = generator.create_label_pdf(
|
||||
comanda='COM-2024-001',
|
||||
article='ART-12345',
|
||||
serial='SN-20260212-001',
|
||||
filename=pdf_output,
|
||||
image_path=os.path.join('conf', 'accepted.png')
|
||||
)
|
||||
|
||||
if result and os.path.exists(pdf_output):
|
||||
file_size = os.path.getsize(pdf_output)
|
||||
print(f"✓ Programmatic layout PDF created: {pdf_output} ({file_size} bytes)")
|
||||
return True
|
||||
else:
|
||||
print("❌ Programmatic layout PDF creation failed")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
def test_wrapper_functions():
|
||||
"""Test convenience wrapper functions"""
|
||||
print("\n--- Testing Wrapper Functions ---")
|
||||
|
||||
from print_label_pdf import create_label_pdf_simple, create_label_pdf_file
|
||||
|
||||
# Test data string
|
||||
test_string = "COM-2024-001;ART-12345;SN-20260212-001"
|
||||
|
||||
try:
|
||||
# Test create_label_pdf_simple (returns bytes)
|
||||
print("Testing create_label_pdf_simple()...")
|
||||
pdf_bytes = create_label_pdf_simple(test_string)
|
||||
if pdf_bytes:
|
||||
print(f"✓ create_label_pdf_simple returned {len(pdf_bytes)} bytes")
|
||||
else:
|
||||
print("❌ create_label_pdf_simple failed")
|
||||
return False
|
||||
|
||||
# Test create_label_pdf_file (returns filename)
|
||||
print("Testing create_label_pdf_file()...")
|
||||
pdf_file = create_label_pdf_file(test_string, filename='test_label_wrapper.pdf')
|
||||
if pdf_file and os.path.exists(pdf_file):
|
||||
file_size = os.path.getsize(pdf_file)
|
||||
print(f"✓ create_label_pdf_file created: {pdf_file} ({file_size} bytes)")
|
||||
return True
|
||||
else:
|
||||
print("❌ create_label_pdf_file failed")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("SVG Template Test Suite\n")
|
||||
print("=" * 50)
|
||||
|
||||
results = []
|
||||
|
||||
# Test 1: SVG template
|
||||
results.append(("SVG Template", test_svg_template()))
|
||||
|
||||
# Test 2: Programmatic layout
|
||||
results.append(("Programmatic Layout", test_programmatic_layout()))
|
||||
|
||||
# Test 3: Wrapper functions
|
||||
results.append(("Wrapper Functions", test_wrapper_functions()))
|
||||
|
||||
# Summary
|
||||
print("\n" + "=" * 50)
|
||||
print("SUMMARY")
|
||||
print("=" * 50)
|
||||
|
||||
for test_name, passed in results:
|
||||
status = "✓ PASS" if passed else "❌ FAIL"
|
||||
print(f"{status}: {test_name}")
|
||||
|
||||
total = len(results)
|
||||
passed = sum(1 for _, p in results if p)
|
||||
|
||||
print(f"\nTotal: {passed}/{total} tests passed")
|
||||
|
||||
if passed == total:
|
||||
print("\n🎉 All tests passed!")
|
||||
sys.exit(0)
|
||||
else:
|
||||
print("\n⚠ Some tests failed")
|
||||
sys.exit(1)
|
||||
Reference in New Issue
Block a user