| | | 1 | | using iText.IO.Font; |
| | | 2 | | using iText.Kernel.Font; |
| | | 3 | | using iText.Kernel.Pdf; |
| | | 4 | | using iText.Layout; |
| | | 5 | | using iText.Layout.Element; |
| | | 6 | | using System.IO; |
| | | 7 | | using iText.IO.Font.Constants; |
| | | 8 | | using iText.Layout.Properties; |
| | | 9 | | using iText.Kernel.Colors; |
| | | 10 | | using OzonDomains.Models; |
| | | 11 | | |
| | | 12 | | namespace Services.Builders.PdfBuilder.Builders; |
| | | 13 | | |
| | | 14 | | public class TransactionTablePdfBuilder |
| | | 15 | | { |
| | | 16 | | private MemoryStream _memoryStream = null!; |
| | | 17 | | private PdfWriter _writer = null!; |
| | | 18 | | private PdfDocument _pdf = null!; |
| | | 19 | | private Document _document = null!; |
| | | 20 | | private PdfFont _font = null!; |
| | | 21 | | private PdfFont _boldFont = null!; |
| | | 22 | | private ICollection<Order> _orders = null!; |
| | | 23 | | |
| | 0 | 24 | | public TransactionTablePdfBuilder() |
| | | 25 | | { |
| | 0 | 26 | | _memoryStream = new MemoryStream(); |
| | 0 | 27 | | _writer = new PdfWriter(_memoryStream); |
| | 0 | 28 | | _pdf = new PdfDocument(_writer); |
| | 0 | 29 | | _document = new Document(_pdf); |
| | 0 | 30 | | _document.SetMargins(20, 20, 20, 20); |
| | | 31 | | |
| | | 32 | | try |
| | | 33 | | { |
| | | 34 | | // Попробуем использовать шрифты, которые точно поддерживают кириллицу |
| | 0 | 35 | | string[] knownCyrillicFonts = { |
| | 0 | 36 | | "times.ttf", "timesbd.ttf", |
| | 0 | 37 | | "dejavu-sans.ttf", "dejavu-sans-bold.ttf", |
| | 0 | 38 | | "liberation-sans.ttf", "liberation-sans-bold.ttf", |
| | 0 | 39 | | "freesans.ttf", "freesansbold.ttf", |
| | 0 | 40 | | "arial.ttf", "arialbd.ttf" |
| | 0 | 41 | | }; |
| | | 42 | | |
| | 0 | 43 | | string? regularFontPath = null; |
| | 0 | 44 | | string? boldFontPath = null; |
| | | 45 | | |
| | | 46 | | // Ищем папку со шрифтами |
| | 0 | 47 | | string[] possibleFontFolders = { |
| | 0 | 48 | | Path.Combine(Directory.GetCurrentDirectory(), "Fonts"), |
| | 0 | 49 | | Path.Combine(Directory.GetCurrentDirectory(), "fonts"), |
| | 0 | 50 | | Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "fonts"), |
| | 0 | 51 | | Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Fonts"), |
| | 0 | 52 | | Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fonts") |
| | 0 | 53 | | }; |
| | | 54 | | |
| | 0 | 55 | | foreach (var folder in possibleFontFolders) |
| | | 56 | | { |
| | 0 | 57 | | if (Directory.Exists(folder)) |
| | | 58 | | { |
| | 0 | 59 | | foreach (var fontFile in knownCyrillicFonts) |
| | | 60 | | { |
| | 0 | 61 | | string path = Path.Combine(folder, fontFile); |
| | 0 | 62 | | if (File.Exists(path)) |
| | | 63 | | { |
| | 0 | 64 | | if (fontFile.Contains("bold") || fontFile.Contains("bd")) |
| | | 65 | | { |
| | 0 | 66 | | boldFontPath = path; |
| | | 67 | | } |
| | 0 | 68 | | else if (!fontFile.Contains("bold") && !fontFile.Contains("bd")) |
| | | 69 | | { |
| | 0 | 70 | | regularFontPath = path; |
| | | 71 | | } |
| | | 72 | | } |
| | | 73 | | } |
| | | 74 | | |
| | 0 | 75 | | if (regularFontPath != null) break; |
| | | 76 | | } |
| | | 77 | | } |
| | | 78 | | |
| | 0 | 79 | | if (regularFontPath != null) |
| | | 80 | | { |
| | 0 | 81 | | _font = PdfFontFactory.CreateFont(regularFontPath, PdfEncodings.IDENTITY_H); |
| | 0 | 82 | | _boldFont = boldFontPath != null |
| | 0 | 83 | | ? PdfFontFactory.CreateFont(boldFontPath, PdfEncodings.IDENTITY_H) |
| | 0 | 84 | | : PdfFontFactory.CreateFont(regularFontPath, PdfEncodings.IDENTITY_H); |
| | | 85 | | } |
| | | 86 | | else |
| | | 87 | | { |
| | 0 | 88 | | TryLoadSystemFonts(); |
| | | 89 | | } |
| | 0 | 90 | | } |
| | 0 | 91 | | catch (Exception ex) |
| | | 92 | | { |
| | 0 | 93 | | TryLoadSystemFonts(); |
| | 0 | 94 | | Console.WriteLine($"Ошибка загрузки шрифтов: {ex.Message}"); |
| | 0 | 95 | | } |
| | 0 | 96 | | } |
| | | 97 | | |
| | | 98 | | private void TryLoadSystemFonts() |
| | | 99 | | { |
| | | 100 | | try |
| | | 101 | | { |
| | 0 | 102 | | string[] linuxFontPaths = { |
| | 0 | 103 | | "/usr/share/fonts/truetype/freefont/FreeSans.ttf", |
| | 0 | 104 | | "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", |
| | 0 | 105 | | "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", |
| | 0 | 106 | | "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf" |
| | 0 | 107 | | }; |
| | | 108 | | |
| | 0 | 109 | | foreach (var path in linuxFontPaths) |
| | | 110 | | { |
| | 0 | 111 | | if (File.Exists(path)) |
| | | 112 | | { |
| | 0 | 113 | | _font = PdfFontFactory.CreateFont(path, PdfEncodings.IDENTITY_H); |
| | 0 | 114 | | _boldFont = PdfFontFactory.CreateFont(path, PdfEncodings.IDENTITY_H); |
| | 0 | 115 | | return; |
| | | 116 | | } |
| | | 117 | | } |
| | | 118 | | |
| | 0 | 119 | | _font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA); |
| | 0 | 120 | | _boldFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD); |
| | 0 | 121 | | } |
| | 0 | 122 | | catch |
| | | 123 | | { |
| | 0 | 124 | | _font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA); |
| | 0 | 125 | | _boldFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD); |
| | 0 | 126 | | } |
| | 0 | 127 | | } |
| | | 128 | | |
| | | 129 | | public byte[] GeneratePdfWithStocks(ICollection<Order> orders, Dictionary<string, int> articleToStock) |
| | | 130 | | { |
| | | 131 | | try |
| | | 132 | | { |
| | 0 | 133 | | _orders = orders ?? new List<Order>(); |
| | | 134 | | |
| | | 135 | | // Заголовок документа |
| | 0 | 136 | | _document.Add(new Paragraph("Таблица заказов") |
| | 0 | 137 | | .SetFont(_boldFont) |
| | 0 | 138 | | .SetFontSize(16) |
| | 0 | 139 | | .SetTextAlignment(TextAlignment.CENTER) |
| | 0 | 140 | | .SetMarginBottom(10)); |
| | | 141 | | |
| | | 142 | | // Сортируем заказы: сначала по производителю, затем по артикулу |
| | 0 | 143 | | var sortedOrders = _orders |
| | 0 | 144 | | .OrderBy(o => o.EtProducer?.Name ?? "") |
| | 0 | 145 | | .ThenBy(o => o.Article ?? "") |
| | 0 | 146 | | .ToList(); |
| | | 147 | | |
| | | 148 | | // Создаем таблицу с колонками: Номер заказа, Клиент, Наименование товара, Артикул, Производитель, Количеств |
| | | 149 | | // Уменьшаем ширину столбцов "Количество" и "Сумма отправления" |
| | 0 | 150 | | Table table = new Table(UnitValue.CreatePercentArray(new float[] { 12, 12, 30, 10, 12, 5, 5, 7 })) |
| | 0 | 151 | | .UseAllAvailableWidth(); |
| | | 152 | | |
| | | 153 | | // Стиль для заголовков таблицы |
| | 0 | 154 | | var headerStyle = new Style() |
| | 0 | 155 | | .SetBackgroundColor(ColorConstants.LIGHT_GRAY) |
| | 0 | 156 | | .SetPadding(6) |
| | 0 | 157 | | .SetTextAlignment(TextAlignment.CENTER) |
| | 0 | 158 | | .SetFont(_boldFont) |
| | 0 | 159 | | .SetFontSize(9); |
| | | 160 | | |
| | | 161 | | // Стиль для ячеек с данными |
| | 0 | 162 | | var cellStyle = new Style() |
| | 0 | 163 | | .SetPadding(5) |
| | 0 | 164 | | .SetTextAlignment(TextAlignment.LEFT) |
| | 0 | 165 | | .SetFont(_font) |
| | 0 | 166 | | .SetFontSize(8); |
| | | 167 | | |
| | | 168 | | // Заголовки таблицы |
| | 0 | 169 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Номер заказа")).AddStyle(headerStyle)); |
| | 0 | 170 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Клиент")).AddStyle(headerStyle)); |
| | 0 | 171 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Наименование товара")).AddStyle(headerStyle)); |
| | 0 | 172 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Артикул")).AddStyle(headerStyle)); |
| | 0 | 173 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Производитель")).AddStyle(headerStyle)); |
| | 0 | 174 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Кол.")).AddStyle(headerStyle)); |
| | 0 | 175 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Остаток")).AddStyle(headerStyle)); |
| | 0 | 176 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Сумма")).AddStyle(headerStyle)); |
| | | 177 | | |
| | | 178 | | // Данные таблицы |
| | 0 | 179 | | decimal totalAmount = 0; |
| | 0 | 180 | | int totalQuantity = 0; |
| | | 181 | | |
| | 0 | 182 | | foreach (var order in sortedOrders) |
| | | 183 | | { |
| | | 184 | | // Номер заказа |
| | 0 | 185 | | table.AddCell(new Cell() |
| | 0 | 186 | | .Add(new Paragraph(order.ShipmentNumber ?? "")) |
| | 0 | 187 | | .AddStyle(cellStyle)); |
| | | 188 | | |
| | | 189 | | // Клиент |
| | 0 | 190 | | var clientName = order.OzonClient?.Name ?? ""; |
| | 0 | 191 | | table.AddCell(new Cell() |
| | 0 | 192 | | .Add(new Paragraph(clientName)) |
| | 0 | 193 | | .AddStyle(cellStyle)); |
| | | 194 | | |
| | | 195 | | // Наименование товара (ограничить двумя строками) |
| | 0 | 196 | | var productName = order.ProductName ?? ""; |
| | 0 | 197 | | int maxSymbolsPerLine = 32; |
| | 0 | 198 | | int maxLines = 2; |
| | 0 | 199 | | string[] words = productName.Split(' '); |
| | 0 | 200 | | List<string> lines = new List<string>(); |
| | 0 | 201 | | string currentLine = ""; |
| | 0 | 202 | | foreach (var word in words) |
| | | 203 | | { |
| | 0 | 204 | | if ((currentLine + (currentLine.Length > 0 ? " " : "") + word).Length > maxSymbolsPerLine) |
| | | 205 | | { |
| | 0 | 206 | | if (!string.IsNullOrWhiteSpace(currentLine)) |
| | | 207 | | { |
| | 0 | 208 | | lines.Add(currentLine); |
| | 0 | 209 | | currentLine = word; |
| | 0 | 210 | | if (lines.Count == maxLines - 1) break; |
| | | 211 | | } |
| | | 212 | | } |
| | | 213 | | else |
| | | 214 | | { |
| | 0 | 215 | | currentLine += (currentLine.Length > 0 ? " " : "") + word; |
| | | 216 | | } |
| | | 217 | | } |
| | 0 | 218 | | if (lines.Count < maxLines && !string.IsNullOrWhiteSpace(currentLine)) |
| | 0 | 219 | | lines.Add(currentLine); |
| | 0 | 220 | | string resultProductName = string.Join("\n", lines); |
| | 0 | 221 | | if (lines.Count == maxLines && words.Length > 0 && (lines[0] + lines[1]).Length < productName.Length) |
| | 0 | 222 | | resultProductName = resultProductName.TrimEnd() + "..."; |
| | 0 | 223 | | table.AddCell(new Cell() |
| | 0 | 224 | | .Add(new Paragraph(resultProductName)) |
| | 0 | 225 | | .AddStyle(cellStyle)); |
| | | 226 | | |
| | | 227 | | // Артикул |
| | 0 | 228 | | var article = order.Article ?? ""; |
| | 0 | 229 | | table.AddCell(new Cell() |
| | 0 | 230 | | .Add(new Paragraph(article)) |
| | 0 | 231 | | .AddStyle(cellStyle)); |
| | | 232 | | |
| | | 233 | | // Производитель |
| | 0 | 234 | | var producerName = order.EtProducer?.Name ?? ""; |
| | 0 | 235 | | table.AddCell(new Cell() |
| | 0 | 236 | | .Add(new Paragraph(producerName)) |
| | 0 | 237 | | .AddStyle(cellStyle)); |
| | | 238 | | |
| | | 239 | | // Количество |
| | 0 | 240 | | var quantity = order.Quantity ?? 0; |
| | 0 | 241 | | totalQuantity += quantity; |
| | 0 | 242 | | table.AddCell(new Cell() |
| | 0 | 243 | | .Add(new Paragraph(quantity.ToString()).SetTextAlignment(TextAlignment.CENTER)) |
| | 0 | 244 | | .AddStyle(cellStyle)); |
| | | 245 | | |
| | | 246 | | // Остаток Bitrix |
| | 0 | 247 | | var stock = 0; |
| | 0 | 248 | | if (!string.IsNullOrWhiteSpace(order.ProductKey)) |
| | | 249 | | { |
| | 0 | 250 | | var articleKey = order.ProductKey.Split('=')[0].Trim(); |
| | 0 | 251 | | if (articleToStock.TryGetValue(articleKey, out var s)) |
| | 0 | 252 | | stock = s; |
| | | 253 | | } |
| | 0 | 254 | | table.AddCell(new Cell() |
| | 0 | 255 | | .Add(new Paragraph(stock.ToString()).SetTextAlignment(TextAlignment.CENTER)) |
| | 0 | 256 | | .AddStyle(cellStyle)); |
| | | 257 | | |
| | | 258 | | // Сумма отправления |
| | 0 | 259 | | var shipmentAmount = order.ShipmentAmount ?? 0; |
| | 0 | 260 | | totalAmount += shipmentAmount; |
| | 0 | 261 | | table.AddCell(new Cell() |
| | 0 | 262 | | .Add(new Paragraph(shipmentAmount.ToString("N0")).SetTextAlignment(TextAlignment.RIGHT)) |
| | 0 | 263 | | .AddStyle(cellStyle)); |
| | | 264 | | } |
| | | 265 | | |
| | 0 | 266 | | _document.Add(table); |
| | | 267 | | |
| | | 268 | | // Итоговая строка |
| | 0 | 269 | | _document.Add(new Paragraph(" ") |
| | 0 | 270 | | .SetMarginTop(10)); |
| | | 271 | | |
| | 0 | 272 | | var totalStyle = new Style() |
| | 0 | 273 | | .SetFont(_boldFont) |
| | 0 | 274 | | .SetFontSize(10) |
| | 0 | 275 | | .SetTextAlignment(TextAlignment.RIGHT); |
| | | 276 | | |
| | 0 | 277 | | _document.Add(new Paragraph($"Итого:") |
| | 0 | 278 | | .SetFont(_boldFont) |
| | 0 | 279 | | .SetFontSize(10) |
| | 0 | 280 | | .SetMarginTop(5)); |
| | | 281 | | |
| | 0 | 282 | | _document.Add(new Paragraph($"Количество: {totalQuantity}") |
| | 0 | 283 | | .AddStyle(totalStyle)); |
| | | 284 | | |
| | 0 | 285 | | _document.Add(new Paragraph($"Сумма отправления: {totalAmount:N0}") |
| | 0 | 286 | | .AddStyle(totalStyle)); |
| | | 287 | | |
| | 0 | 288 | | _document.Close(); |
| | 0 | 289 | | return _memoryStream.ToArray(); |
| | | 290 | | } |
| | 0 | 291 | | catch (Exception ex) |
| | | 292 | | { |
| | 0 | 293 | | return CreateFallbackPdf(ex.Message); |
| | | 294 | | } |
| | 0 | 295 | | } |
| | | 296 | | |
| | | 297 | | private byte[] CreateFallbackPdf(string? errorMessage = null) |
| | | 298 | | { |
| | 0 | 299 | | var fallbackStream = new MemoryStream(); |
| | 0 | 300 | | var fallbackWriter = new PdfWriter(fallbackStream); |
| | 0 | 301 | | var fallbackPdf = new PdfDocument(fallbackWriter); |
| | 0 | 302 | | var fallbackDoc = new Document(fallbackPdf); |
| | | 303 | | |
| | 0 | 304 | | fallbackDoc.Add(new Paragraph("Таблица заказов").SetFontSize(16)); |
| | | 305 | | |
| | 0 | 306 | | if (!string.IsNullOrEmpty(errorMessage)) |
| | | 307 | | { |
| | 0 | 308 | | fallbackDoc.Add(new Paragraph($"Ошибка: {errorMessage}").SetFontColor(ColorConstants.RED)); |
| | | 309 | | } |
| | | 310 | | |
| | 0 | 311 | | fallbackDoc.Close(); |
| | 0 | 312 | | return fallbackStream.ToArray(); |
| | | 313 | | } |
| | | 314 | | } |
| | | 315 | | |