diff --git a/PrintHTML/Helpers/AsyncPrintTask.cs b/PrintHTML/Helpers/AsyncPrintTask.cs
index f31c21d..4538ebc 100644
--- a/PrintHTML/Helpers/AsyncPrintTask.cs
+++ b/PrintHTML/Helpers/AsyncPrintTask.cs
@@ -22,12 +22,12 @@ public static void Exec(bool highPriority, Action action)
private static void InternalExec(Action action)
{
try
- {
+ {
action.Invoke();
}
- catch (Exception e)
+ catch (Exception exception)
{
- MessageBox.Show(e.Message);
+ MessageBox.Show($"There is a problem while printing.\n\nError Message: {exception.Message}");
}
}
}
diff --git a/PrintHTML/MainWindow.xaml b/PrintHTML/MainWindow.xaml
index 6cd8101..bab8cbe 100644
--- a/PrintHTML/MainWindow.xaml
+++ b/PrintHTML/MainWindow.xaml
@@ -1,7 +1,8 @@
+ Title="Flexible Print Application" Height="600" Width="800" WindowStartupLocation="CenterScreen">
+
@@ -9,31 +10,42 @@
-
+
+
+
+
+
+
-
-
+
+
+
-
+
-
+
-
-
+ Text="<div style="text-align: center; color: red;">PRINT TEMPLATE USER GUIDE</div>
<F>=
<T>Text Alignment Examples:
<L>This text is left-aligned
<C>This text is centered
<R>This text is right-aligned
<F>=
<T>Bold Text Examples:
<EB>
This text will be bold
<DB>
<F>=
<T>Table Example:
<J>Product | Stock
<J>Laptop | 25
<J>Mouse | 100
<J>Keyboard | 50
<F>=
<C>beratarpa.com"/>
+
+
+
+
-
-
+
+
diff --git a/PrintHTML/MainWindow.xaml.cs b/PrintHTML/MainWindow.xaml.cs
index 28edc71..9617f15 100644
--- a/PrintHTML/MainWindow.xaml.cs
+++ b/PrintHTML/MainWindow.xaml.cs
@@ -14,87 +14,100 @@ namespace PrintHTML
public partial class MainWindow : Window
{
private string _selectedPrinter;
- private readonly HtmlPrinterService _printerService;
+ private int _charactersPerLine;
+ private readonly PrinterService _printerService = new PrinterService();
public MainWindow()
{
InitializeComponent();
+
LoadPrinters();
- _printerService = new HtmlPrinterService();
}
private void LoadPrinters()
{
var printers = PrinterInfo.GetPrinterNames();
- cbPrinters.ItemsSource = printers;
+ ComboBoxPrinters.ItemsSource = printers;
if (printers.Any())
{
- cbPrinters.SelectedIndex = 0;
+ ComboBoxPrinters.SelectedIndex = 0;
}
}
- private void btnPrint_Click(object sender, RoutedEventArgs e)
+ private void ButtonPrint_Click(object sender, RoutedEventArgs e)
{
try
{
if (string.IsNullOrEmpty(_selectedPrinter))
{
- MessageBox.Show("Lütfen bir yazıcı seçin.", "Uyarı", MessageBoxButton.OK, MessageBoxImage.Warning);
+ MessageBox.Show("Please select a printer.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
- if (string.IsNullOrWhiteSpace(txtHtmlContent.Text))
+ if (string.IsNullOrWhiteSpace(TextBoxContent.Text))
{
- MessageBox.Show("Yazdırılacak HTML içeriği boş olamaz.", "Uyarı", MessageBoxButton.OK, MessageBoxImage.Warning);
+ MessageBox.Show("The content to be printed cannot be empty.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
- btnPrint.IsEnabled = false;
+ ButtonPrint.IsEnabled = false;
Mouse.OverrideCursor = Cursors.Wait;
- var content = txtHtmlContent.Text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
- AsyncPrintTask.Exec(true, () => _printerService.PrintAsync(content, _selectedPrinter));
+ var content = TextBoxContent.Text;
+
+ AsyncPrintTask.Exec(true, () => _printerService.DoPrint(content, _selectedPrinter, _charactersPerLine));
- MessageBox.Show("Yazdırma işlemi başarıyla tamamlandı.", "Bilgi", MessageBoxButton.OK, MessageBoxImage.Information);
+ MessageBox.Show("The printing process was completed successfully.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
}
- catch (Exception ex)
+ catch (Exception exception)
{
- MessageBox.Show($"Yazdırma işlemi sırasında bir hata oluştu: {ex.Message}", "Hata", MessageBoxButton.OK, MessageBoxImage.Error);
+ MessageBox.Show($"An error occurred during printing: {exception.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
- btnPrint.IsEnabled = true;
+ ButtonPrint.IsEnabled = true;
Mouse.OverrideCursor = null;
}
}
- private async void btnPreview_Click(object sender, RoutedEventArgs e)
+ private void ButtonPreview_Click(object sender, RoutedEventArgs e)
{
try
{
- var htmlContent = txtHtmlContent.Text;
+ var htmlContent = TextBoxContent.Text;
if (string.IsNullOrWhiteSpace(htmlContent))
{
- MessageBox.Show("Önizleme için HTML içeriği boş olamaz.", "Uyarı", MessageBoxButton.OK, MessageBoxImage.Warning);
+ MessageBox.Show("Content for preview cannot be empty.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
- flowDocumentScrollViewer.Document = await _printerService.GeneratePreview(htmlContent);
-
+ FlowDocumentScrollViewer.Document = _printerService.GeneratePreview(htmlContent, _charactersPerLine);
+
}
catch (Exception ex)
{
- MessageBox.Show($"Önizleme sırasında bir hata oluştu: {ex.Message}", "Hata", MessageBoxButton.OK, MessageBoxImage.Error);
+ MessageBox.Show($"An error occurred during preview: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
- private void cbPrinters_SelectionChanged(object sender, SelectionChangedEventArgs e)
+ private void ComboBoxPrinters_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
- if (cbPrinters.SelectedItem != null)
+ if (ComboBoxPrinters.SelectedItem != null)
{
- _selectedPrinter = cbPrinters.SelectedItem.ToString();
+ _selectedPrinter = ComboBoxPrinters.SelectedItem.ToString();
}
}
+
+ private void TextBoxMaxWidth_TextChanged(object sender, TextChangedEventArgs e)
+ {
+ _charactersPerLine = Convert.ToInt16(TextBoxMaxWidth.Text);
+ }
+
+ private void TextBoxMaxWidth_PreviewTextInput(object sender, TextCompositionEventArgs e)
+ {
+ // Yalnızca rakamlara izin ver
+ e.Handled = !e.Text.All(char.IsDigit);
+ }
}
}
diff --git a/PrintHTML/PrintHTML.csproj b/PrintHTML/PrintHTML.csproj
index 8f8352d..ecf6cd5 100644
--- a/PrintHTML/PrintHTML.csproj
+++ b/PrintHTML/PrintHTML.csproj
@@ -78,8 +78,8 @@
MainWindow.xaml
-
-
+
+
diff --git a/PrintHTML/Services/DocumentFormatter.cs b/PrintHTML/Services/HtmlFormattedDocument.cs
similarity index 50%
rename from PrintHTML/Services/DocumentFormatter.cs
rename to PrintHTML/Services/HtmlFormattedDocument.cs
index 127d938..e4f31a4 100644
--- a/PrintHTML/Services/DocumentFormatter.cs
+++ b/PrintHTML/Services/HtmlFormattedDocument.cs
@@ -1,84 +1,54 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
+using System.Text.RegularExpressions;
namespace PrintHTML.Services
{
- public class DocumentFormatter
+ public class HtmlFormattedDocument
{
- public static string FormatLine(string line)
+ private static int _charactersPerLine;
+
+ private static void SetCharactersPerLine(int charactersPerLine)
{
- if (string.IsNullOrEmpty(line)) return string.Empty;
+ _charactersPerLine = charactersPerLine;
+ }
- // Özel etiketleri HTML'e dönüştür
- if (line.StartsWith("") && line.Length > 3)
- return FormatFillLine(line) + "
";
+ public static string FormatLine(string line, int charactersPerLine)
+ {
+ if (string.IsNullOrEmpty(line)) return string.Empty;
- if (line.StartsWith(""))
- return FormatBoldLine(line) + "
";
+ SetCharactersPerLine(charactersPerLine);
- if (line.StartsWith("";
+ // Etiketleri tanımlamak için bir regex oluştur
+ var regex = new Regex(@"<(?:(c|l|r|j|t|f|eb|db))>", RegexOptions.IgnoreCase);
- if (line.StartsWith(""))
- return line.Replace("", "");
+ // Etiketleri sırayla işle
+ var match = regex.Match(line);
+ var content = regex.Replace(line, "").Trim(); // Etiketlerden arındırılmış içerik
- if (line.StartsWith(""))
+ var tag = match.Groups[1].Value.ToLower(); // Etiketin adı (örneğin, "C", "T")
+ switch (tag)
{
- var end = line.Replace("", "");
- return end + "
";
- }
-
- #region Tables
- if (line.StartsWith(" 3 && (line[2] == '>' || char.IsDigit(line[2])))
- {
- var tables = new Dictionary>();
- var lastLine = "";
- var tableCount = 0;
- var tableLines = new List();
-
- if (!lastLine.StartsWith("());
- tables[tableName].Add(RemoveTag(line));
-
- if (!line.Contains("<") && !string.IsNullOrEmpty(line.Trim()))
- tableLines.Add(line);
-
- lastLine = line;
-
- foreach (var table in tables)
- {
- tableLines.InsertRange(tableLines.IndexOf(table.Key), GetTableLines(table.Value, GetMaxWidth()));
- tableLines.Remove(table.Key);
- }
-
- for (int i = 0; i < tableLines.Count; i++)
- {
- tableLines[i] = tableLines[i].TrimEnd();
- if ((!tableLines[i].ToLower().EndsWith("
") && RemoveTag(tableLines[i]).Trim().Length > 0) || tableLines[i].Trim().Length == 0)
- tableLines[i] += "
";
- tableLines[i] = tableLines[i].Replace(" ", " ");
- }
-
- var htmlBuilder = new StringBuilder();
- foreach (var tableLine in tableLines)
- {
- htmlBuilder.AppendLine(tableLine);
- }
-
- return htmlBuilder.ToString();
+ case "c":
+ return FormatAlignedLine($"<{tag}>" + content) + "
";
+ case "t":
+ return FormatBoldLine($"<{tag}>" + content) + "
";
+ case "f":
+ return FormatFillLine($"<{tag}>" + content) + "
";
+ case "l":
+ return FormatAlignedLine($"<{tag}>" + content) + "
";
+ case "r":
+ return FormatAlignedLine($"<{tag}>" + content) + "
";
+ case "eb":
+ return line.ToLower().Replace($"<{tag}>", "");
+ case "db":
+ return line.ToLower().Replace($"<{tag}>", "") + "
";
+ case "j":
+ return CreateTable(line);
+ default:
+ return line.Replace($"<{tag}>", "");
}
- #endregion
-
- // Normal metin satırı
- return FormatTextLine(line);
}
private static string FormatFillLine(string line)
@@ -88,7 +58,7 @@ private static string FormatFillLine(string line)
private static string FormatBoldLine(string line)
{
- return $"{RemoveTag(line)}";
+ return $"{RemoveTag(line)}";
}
private static string FormatAlignedLine(string line)
@@ -96,11 +66,11 @@ private static string FormatAlignedLine(string line)
var content = RemoveTag(line);
var alignment = "left";
- if (line.StartsWith(">();
+ var lastLine = "";
+ var tableCount = 0;
+ var tableLines = new List();
+
+ if (!lastLine.ToLower().StartsWith("());
+ tables[tableName].Add(RemoveTag(line));
+ if (!line.Contains("<") && !string.IsNullOrEmpty(line.Trim()))
+ tableLines.Add(line);
+
+ lastLine = line;
+
+ foreach (var table in tables)
+ {
+ tableLines.InsertRange(tableLines.IndexOf(table.Key), GetTableLines(table.Value, GetMaxWidth()));
+ tableLines.Remove(table.Key);
+ }
+
+ for (int i = 0; i < tableLines.Count; i++)
+ {
+ tableLines[i] = tableLines[i].TrimEnd();
+ if ((!tableLines[i].ToLower().EndsWith("
") && RemoveTag(tableLines[i]).Trim().Length > 0) || tableLines[i].Trim().Length == 0)
+ tableLines[i] += "
";
+ tableLines[i] = tableLines[i].Replace(" ", " ");
+ }
+
+ var htmlBuilder = new StringBuilder();
+ foreach (var tableLine in tableLines)
+ {
+ htmlBuilder.AppendLine(tableLine);
+ }
+
+ return htmlBuilder.ToString();
+ }
+
private static IEnumerable GetTableLines(IList lines, int maxWidth)
{
int colCount = GetColumnCount(lines) + 1;
var colWidths = new int[colCount];
+ // Tüm satırları aynı sütun sayısına göre hizala
var maxCol = lines.Select(x => x.Split('|').Length).Max();
-
for (int i = 0; i < lines.Count; i++)
{
if (lines[i].Split('|').Length < maxCol)
+ {
lines[i] = lines[i].Replace("|", "| |");
+ }
}
+ // Her sütunun maksimum genişliğini hesapla
for (int i = 0; i < colCount; i++)
{
colWidths[i] = GetMaxLine(lines, i) + 1;
}
+ // Sütun genişliklerini, toplam genişliği aşmayacak şekilde ayarla
if (colWidths.Sum() < maxWidth)
- colWidths[colCount - 1] = (maxWidth - colWidths.Sum()) + colWidths[colCount - 1];
-
- if (colWidths[colCount - 1] < 1) colWidths[colCount - 1] = 1;
+ {
+ colWidths[colCount - 1] += maxWidth - colWidths.Sum();
+ }
+ if (colWidths[colCount - 1] < 1)
+ {
+ colWidths[colCount - 1] = 1;
+ }
+ // Satırları formatla
for (int i = 0; i < lines.Count; i++)
{
lines[i] = string.Format("{0}", GetFormattedLine(lines[i], colWidths));
@@ -167,42 +191,42 @@ private static IEnumerable GetTableLines(IList lines, int maxWid
return lines;
}
- private static int GetSize(string val, char sep, int index)
- {
- var parts = val.Split(sep);
- if (index > parts.Length - 1) return 0;
- return parts[index].Trim().Length;
- }
-
- private static int GetMaxLine(IEnumerable lines, int columnNo)
- {
- return lines.Select(x => GetSize(x, '|', columnNo)).Max() + 1;
- }
-
- private static int GetColumnCount(IEnumerable value)
- {
- return value.Select(item => item.Length - item.Replace("|", "").Length).Aggregate(0, (current, len) => len > current ? len : current);
- }
-
private static string GetFormattedLine(string s, IList colWidths)
{
var parts = s.Split('|');
for (int i = 0; i < parts.Length; i++)
{
if (i == 0)
+ {
parts[i] = parts[i].Trim().PadRight(colWidths[i]);
+ }
else
+ {
parts[i] = parts[i].Trim().PadLeft(colWidths[i]);
+ }
}
return string.Join("", parts);
}
- #endregion
- private static string FormatTextLine(string line)
+ private static int GetColumnCount(IEnumerable value)
{
- return $"{line}";
+ return value.Select(item => item.Length - item.Replace("|", "").Length)
+ .Aggregate(0, (current, len) => len > current ? len : current);
}
+ private static int GetMaxLine(IEnumerable lines, int columnNo)
+ {
+ return lines.Select(x => GetSize(x, '|', columnNo)).Max() + 1;
+ }
+
+ private static int GetSize(string val, char sep, int index)
+ {
+ var parts = val.Split(sep);
+ if (index > parts.Length - 1) return 0;
+ return parts[index].Trim().Length;
+ }
+ #endregion
+
private static string RemoveTag(string line)
{
var tagEnd = line.IndexOf('>');
@@ -212,7 +236,7 @@ private static string RemoveTag(string line)
private static int GetMaxWidth()
{
// Maksimum genişliği belirleyin
- return 42; // Örnek değer
+ return _charactersPerLine; // Örnek değer
}
}
}
diff --git a/PrintHTML/Services/HtmlPrinterService.cs b/PrintHTML/Services/PrinterService.cs
similarity index 61%
rename from PrintHTML/Services/HtmlPrinterService.cs
rename to PrintHTML/Services/PrinterService.cs
index 2ec814f..1a08ee8 100644
--- a/PrintHTML/Services/HtmlPrinterService.cs
+++ b/PrintHTML/Services/PrinterService.cs
@@ -3,86 +3,94 @@
using System;
using System.Printing;
using System.Text;
-using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Xps;
namespace PrintHTML.Services
{
- public class HtmlPrinterService
+ public class PrinterService
{
- public async Task PrintAsync(string[] content, string printerName)
+ private int _charactersPerLine;
+ public void SetCharactersPerLine(int charactersPerLine)
+ {
+ _charactersPerLine = charactersPerLine;
+ }
+
+ public void DoPrint(string content, string printerName, int charactersPerLine = 42)
{
try
{
- var formattedHtml = await FormatHtmlContentAsync(content);
+ SetCharactersPerLine(charactersPerLine);
+ string[] lines = content.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
+
+ var formattedHtml = FormatHtmlContentAsync(lines);
var xamlContent = ConvertHtmlToXaml(formattedHtml);
var flowDocument = CreateFlowDocument(xamlContent);
PrintDocument(flowDocument, printerName);
}
- catch (Exception ex)
+ catch (Exception exception)
{
- throw new Exception("Yazdırma işlemi başarısız", ex);
+ throw new Exception("Printing failed.", exception);
}
}
- public async Task GeneratePreview(string htmlContent)
+ private string FormatHtmlContentAsync(string[] content)
{
- try
- {
- var content = htmlContent.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
- var formattedHtml = await FormatHtmlContentAsync(content);
- var xamlContent = ConvertHtmlToXaml(formattedHtml);
- return CreateFlowDocument(xamlContent);
- }
- catch (Exception ex)
+ var htmlBuilder = new StringBuilder();
+
+ // Varsayılan stiller
+ htmlBuilder.AppendLine(@""
+ );
+
+ // İçeriği formatla
+ foreach (var line in content)
{
- throw new Exception("Önizleme oluşturulamadı", ex);
+ if (string.IsNullOrEmpty(line)) continue;
+
+ var formattedLine = HtmlFormattedDocument.FormatLine(line, _charactersPerLine);
+ htmlBuilder.AppendLine(formattedLine);
}
+
+ return htmlBuilder.ToString();
}
private string ConvertHtmlToXaml(string html)
{
return HtmlToXamlConverter.ConvertHtmlToXaml(html, false);
}
-
- private async Task FormatHtmlContentAsync(string[] content)
- {
- return await Task.Run(() =>
- {
- var htmlBuilder = new StringBuilder();
-
- // Varsayılan stiller
- htmlBuilder.AppendLine(@"");
-
- // İçeriği formatla
- foreach (var line in content)
- {
- if (string.IsNullOrEmpty(line)) continue;
-
- var formattedLine = DocumentFormatter.FormatLine(line);
- htmlBuilder.AppendLine(formattedLine);
- }
-
- return htmlBuilder.ToString();
- });
- }
private FlowDocument CreateFlowDocument(string xamlContent)
{
return PrinterTools.XamlToFlowDocument(xamlContent);
}
+ public FlowDocument GeneratePreview(string previewContent, int charactersPerLine = 42)
+ {
+ try
+ {
+ SetCharactersPerLine(charactersPerLine);
+ var content = previewContent.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
+
+ var formattedHtml = FormatHtmlContentAsync(content);
+ var xamlContent = ConvertHtmlToXaml(formattedHtml);
+ return CreateFlowDocument(xamlContent);
+ }
+ catch (Exception exception)
+ {
+ throw new Exception("Failed to create preview.", exception);
+ }
+ }
+
private void PrintDocument(FlowDocument document, string printerName)
{
var printer = PrinterInfo.GetPrinter(printerName);
if (printer == null)
- throw new Exception($"Yazıcı bulunamadı: {printerName}");
+ throw new Exception($"No printer found: {printerName}");
// Mevcut yazdırma metodunuzu burada kullanın
PrintFlowDocument(printer, document);
@@ -111,16 +119,16 @@ private void PrintFlowDocument(PrintQueue printer, FlowDocument document)
Math.Max((double)pt.PageMediaSize.Height - (ia.OriginHeight + ia.ExtentHeight), t.Bottom));
document.ColumnWidth = double.PositiveInfinity;
- document.FontFamily = new System.Windows.Media.FontFamily("Segoe UI Semibold");
+ document.FontFamily = new System.Windows.Media.FontFamily("Consolas");
//copy.PageWidth = 528; // allow the page to be the natural with of the output device
// Send content to the printer.
docWriter.Write(paginator);
}
}
- catch (Exception ex)
+ catch (Exception exception)
{
- throw new Exception($"Yazdırma işlemi sırasında hata: {ex.Message}", ex);
+ throw new Exception($"Error during printing process: {exception.Message}", exception);
}
}
}