| | | 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 iText.IO.Image; |
| | | 7 | | using System.IO; |
| | | 8 | | using iText.IO.Font.Constants; |
| | | 9 | | using iText.Layout.Properties; |
| | | 10 | | using iText.Kernel.Colors; |
| | | 11 | | using OzonDomains; |
| | | 12 | | using OzonDomains.Models; |
| | | 13 | | using OzonDomains.Models.BitrixModels; |
| | | 14 | | |
| | | 15 | | namespace Services.Builders.PdfBuilder.Builders; |
| | | 16 | | |
| | | 17 | | public class ShippedBySupplierPdfBuilder: IPdfBuilder |
| | | 18 | | { |
| | | 19 | | private MemoryStream _memoryStream = null!; |
| | | 20 | | private PdfWriter _writer = null!; |
| | | 21 | | private PdfDocument _pdf = null!; |
| | | 22 | | private Document _document = null!; |
| | | 23 | | private PdfFont _font = null!; |
| | | 24 | | private PdfFont _boldFont = null!; |
| | | 25 | | private Transaction _transaction = null!; |
| | | 26 | | private ICollection<Order> _orders = null!; |
| | | 27 | | private Dictionary<int, List<StockInfo>> _stocks = null!; |
| | | 28 | | |
| | 0 | 29 | | public ShippedBySupplierPdfBuilder() |
| | | 30 | | { |
| | 0 | 31 | | _memoryStream = new MemoryStream(); |
| | 0 | 32 | | _writer = new PdfWriter(_memoryStream); |
| | 0 | 33 | | _pdf = new PdfDocument(_writer); |
| | 0 | 34 | | _document = new Document(_pdf); |
| | 0 | 35 | | _document.SetMargins(40, 40, 40, 40); |
| | | 36 | | |
| | | 37 | | try |
| | | 38 | | { |
| | | 39 | | // Попробуем использовать шрифты, которые точно поддерживают кириллицу |
| | 0 | 40 | | string[] knownCyrillicFonts = { |
| | 0 | 41 | | "times.ttf", "timesbd.ttf", // Times New Roman |
| | 0 | 42 | | "dejavu-sans.ttf", "dejavu-sans-bold.ttf", // DejaVu Sans |
| | 0 | 43 | | "liberation-sans.ttf", "liberation-sans-bold.ttf", // Liberation Sans |
| | 0 | 44 | | "freesans.ttf", "freesansbold.ttf", // FreeSans |
| | 0 | 45 | | "arial.ttf", "arialbd.ttf" // Arial |
| | 0 | 46 | | }; |
| | | 47 | | |
| | 0 | 48 | | string? regularFontPath = null; |
| | 0 | 49 | | string? boldFontPath = null; |
| | | 50 | | |
| | | 51 | | // Ищем папку со шрифтами |
| | 0 | 52 | | string[] possibleFontFolders = { |
| | 0 | 53 | | Path.Combine(Directory.GetCurrentDirectory(), "Fonts"), |
| | 0 | 54 | | Path.Combine(Directory.GetCurrentDirectory(), "fonts"), |
| | 0 | 55 | | Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "fonts"), |
| | 0 | 56 | | Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Fonts"), |
| | 0 | 57 | | Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fonts") |
| | 0 | 58 | | }; |
| | | 59 | | |
| | 0 | 60 | | foreach (var folder in possibleFontFolders) |
| | | 61 | | { |
| | 0 | 62 | | if (Directory.Exists(folder)) |
| | | 63 | | { |
| | 0 | 64 | | foreach (var fontFile in knownCyrillicFonts) |
| | | 65 | | { |
| | 0 | 66 | | string path = Path.Combine(folder, fontFile); |
| | 0 | 67 | | if (File.Exists(path)) |
| | | 68 | | { |
| | 0 | 69 | | if (fontFile.Contains("bold") || fontFile.Contains("bd")) |
| | | 70 | | { |
| | 0 | 71 | | boldFontPath = path; |
| | | 72 | | } |
| | 0 | 73 | | else if (!fontFile.Contains("bold") && !fontFile.Contains("bd")) |
| | | 74 | | { |
| | 0 | 75 | | regularFontPath = path; |
| | | 76 | | } |
| | | 77 | | } |
| | | 78 | | } |
| | | 79 | | |
| | 0 | 80 | | if (regularFontPath != null) break; |
| | | 81 | | } |
| | | 82 | | } |
| | | 83 | | |
| | 0 | 84 | | if (regularFontPath != null) |
| | | 85 | | { |
| | 0 | 86 | | _font = PdfFontFactory.CreateFont(regularFontPath, PdfEncodings.IDENTITY_H); |
| | 0 | 87 | | _boldFont = boldFontPath != null |
| | 0 | 88 | | ? PdfFontFactory.CreateFont(boldFontPath, PdfEncodings.IDENTITY_H) |
| | 0 | 89 | | : PdfFontFactory.CreateFont(regularFontPath, PdfEncodings.IDENTITY_H); |
| | | 90 | | |
| | 0 | 91 | | Console.WriteLine($"Успешно загружены шрифты: {regularFontPath}"); |
| | | 92 | | } |
| | | 93 | | else |
| | | 94 | | { |
| | 0 | 95 | | TryLoadSystemFonts(); |
| | | 96 | | } |
| | 0 | 97 | | } |
| | 0 | 98 | | catch (Exception ex) |
| | | 99 | | { |
| | 0 | 100 | | TryLoadSystemFonts(); |
| | 0 | 101 | | Console.WriteLine($"Ошибка загрузки шрифтов: {ex.Message}"); |
| | 0 | 102 | | } |
| | 0 | 103 | | } |
| | | 104 | | |
| | | 105 | | private void TryLoadSystemFonts() |
| | | 106 | | { |
| | | 107 | | try |
| | | 108 | | { |
| | | 109 | | // Пути к шрифтам в Linux |
| | 0 | 110 | | string[] linuxFontPaths = { |
| | 0 | 111 | | "/usr/share/fonts/truetype/freefont/FreeSans.ttf", |
| | 0 | 112 | | "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", |
| | 0 | 113 | | "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", |
| | 0 | 114 | | "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf" |
| | 0 | 115 | | }; |
| | | 116 | | |
| | 0 | 117 | | foreach (var path in linuxFontPaths) |
| | | 118 | | { |
| | 0 | 119 | | if (File.Exists(path)) |
| | | 120 | | { |
| | 0 | 121 | | _font = PdfFontFactory.CreateFont(path, PdfEncodings.IDENTITY_H); |
| | 0 | 122 | | _boldFont = PdfFontFactory.CreateFont(path, PdfEncodings.IDENTITY_H); |
| | 0 | 123 | | Console.WriteLine($"Используем системный шрифт: {path}"); |
| | 0 | 124 | | return; |
| | | 125 | | } |
| | | 126 | | } |
| | | 127 | | |
| | | 128 | | // Если ничего не найдено, используем стандартные шрифты |
| | 0 | 129 | | _font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA); |
| | 0 | 130 | | _boldFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD); |
| | 0 | 131 | | Console.WriteLine("Используются стандартные шрифты Helvetica (кириллица не поддерживается)"); |
| | 0 | 132 | | } |
| | 0 | 133 | | catch |
| | | 134 | | { |
| | 0 | 135 | | _font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA); |
| | 0 | 136 | | _boldFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD); |
| | 0 | 137 | | } |
| | 0 | 138 | | } |
| | | 139 | | public void BuildHeader(Transaction transaction) |
| | | 140 | | { |
| | 0 | 141 | | _transaction = transaction; |
| | 0 | 142 | | } |
| | | 143 | | |
| | | 144 | | public void BuildOrdersTable(ICollection<Order> orders) |
| | | 145 | | { |
| | 0 | 146 | | _orders = orders; |
| | 0 | 147 | | } |
| | | 148 | | |
| | | 149 | | public void SetOrdersStock(Dictionary<int, List<StockInfo>> stocks) |
| | | 150 | | { |
| | 0 | 151 | | _stocks = stocks; |
| | 0 | 152 | | } |
| | | 153 | | |
| | | 154 | | public byte[] GetPdf() |
| | | 155 | | { |
| | | 156 | | try |
| | | 157 | | { |
| | | 158 | | // Заголовок документа |
| | 0 | 159 | | _document.Add(new Paragraph($"{_transaction.Type?.GetDisplayName()} № {_transaction.Id} от {_transaction.For |
| | 0 | 160 | | .SetFont(_boldFont) |
| | 0 | 161 | | .SetFontSize(14) |
| | 0 | 162 | | .SetTextAlignment(TextAlignment.LEFT)); |
| | | 163 | | |
| | | 164 | | // Информация об отправителе (остается одна для всех заказов) |
| | 0 | 165 | | var sender = _orders?.FirstOrDefault()?.ShipmentWarehouse?.Name ?? "Не указан"; |
| | 0 | 166 | | _document.Add(new Paragraph($"Отправитель: {sender}") |
| | 0 | 167 | | .SetFont(_font) |
| | 0 | 168 | | .SetFontSize(11)); |
| | | 169 | | |
| | | 170 | | // Информация об поставщике |
| | 0 | 171 | | var supplier = _orders?.FirstOrDefault()?.Supplier; |
| | 0 | 172 | | var supplierName = supplier?.Name ?? "Не указан"; |
| | 0 | 173 | | string ndsData = string.Empty; |
| | 0 | 174 | | if (supplier != null && supplier.IsVatApplicable) |
| | | 175 | | { |
| | 0 | 176 | | ndsData = "C налогом (НДС)"; |
| | | 177 | | } |
| | | 178 | | else |
| | | 179 | | { |
| | 0 | 180 | | ndsData = "Без налога (НДС)"; |
| | | 181 | | } |
| | 0 | 182 | | _document.Add(new Paragraph($"Поставщик: {supplierName}") |
| | 0 | 183 | | .SetFont(_font) |
| | 0 | 184 | | .SetFontSize(11)); |
| | | 185 | | |
| | | 186 | | |
| | | 187 | | |
| | | 188 | | // Группируем заказы по клиентам |
| | 0 | 189 | | var ordersByClient = _orders? |
| | 0 | 190 | | .Where(o => o.OzonClient != null) |
| | 0 | 191 | | .GroupBy(o => o.OzonClient) |
| | 0 | 192 | | .ToList(); |
| | 0 | 193 | | decimal? total = 0; |
| | 0 | 194 | | if (ordersByClient != null && ordersByClient.Any()) |
| | | 195 | | { |
| | 0 | 196 | | foreach (var clientGroup in ordersByClient) |
| | | 197 | | { |
| | 0 | 198 | | var client = clientGroup.Key; |
| | 0 | 199 | | var clientOrders = clientGroup.ToList(); |
| | 0 | 200 | | var receiver = client?.WarehouseName ?? "Не указан"; |
| | | 201 | | |
| | | 202 | | // Добавляем заголовок для клиента |
| | 0 | 203 | | _document.Add(new Paragraph($"Покупатель: {receiver} ({client?.Name ?? "—"})") |
| | 0 | 204 | | .SetFont(_font) |
| | 0 | 205 | | .SetFontSize(11) |
| | 0 | 206 | | .SetMarginTop(15) |
| | 0 | 207 | | .SetMarginBottom(5)); |
| | | 208 | | |
| | | 209 | | // Таблица с товарами для текущего клиента |
| | 0 | 210 | | Table table = new Table(UnitValue.CreatePercentArray(new float[] { 4, 10, 12, 28, 8, 12, 12, 10 })) |
| | 0 | 211 | | .UseAllAvailableWidth(); |
| | | 212 | | |
| | | 213 | | |
| | | 214 | | // Стиль для заголовков таблицы |
| | 0 | 215 | | var headerStyle = new Style() |
| | 0 | 216 | | .SetBackgroundColor(ColorConstants.LIGHT_GRAY) |
| | 0 | 217 | | .SetPadding(5) |
| | 0 | 218 | | .SetTextAlignment(TextAlignment.CENTER) |
| | 0 | 219 | | .SetFont(_boldFont) |
| | 0 | 220 | | .SetFontSize(8); |
| | | 221 | | |
| | | 222 | | // Стиль для ячеек с данными |
| | 0 | 223 | | var cellStyle = new Style() |
| | 0 | 224 | | .SetPadding(5) |
| | 0 | 225 | | .SetTextAlignment(TextAlignment.LEFT) |
| | 0 | 226 | | .SetFont(_font) |
| | 0 | 227 | | .SetFontSize(7); |
| | | 228 | | |
| | | 229 | | // Заголовки таблицы |
| | 0 | 230 | | table.AddHeaderCell(new Cell().Add(new Paragraph("№")).AddStyle(headerStyle)); |
| | 0 | 231 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Код")).AddStyle(headerStyle)); |
| | 0 | 232 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Производитель")).AddStyle(headerStyle)); |
| | 0 | 233 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Товары")).AddStyle(headerStyle)); |
| | 0 | 234 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Количество")).AddStyle(headerStyle)); |
| | 0 | 235 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Остаток")).AddStyle(headerStyle)); |
| | 0 | 236 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Цена")).AddStyle(headerStyle)); |
| | 0 | 237 | | table.AddHeaderCell(new Cell().Add(new Paragraph("Сумма")).AddStyle(headerStyle)); |
| | | 238 | | |
| | | 239 | | // Данные таблицы для текущего клиента |
| | 0 | 240 | | int rowNumber = 1; |
| | 0 | 241 | | foreach (var order in clientOrders) |
| | | 242 | | { |
| | | 243 | | // № |
| | 0 | 244 | | table.AddCell(new Cell() |
| | 0 | 245 | | .Add(new Paragraph(rowNumber.ToString()).SetTextAlignment(TextAlignment.CENTER)) |
| | 0 | 246 | | .AddStyle(cellStyle)); |
| | | 247 | | |
| | | 248 | | // Код товара |
| | 0 | 249 | | table.AddCell(new Cell() |
| | 0 | 250 | | .Add(new Paragraph(order.ProductKey ?? "")) |
| | 0 | 251 | | .AddStyle(cellStyle)); |
| | | 252 | | |
| | | 253 | | // Производитель |
| | 0 | 254 | | var producerName = order.EtProducer?.Name ?? ""; |
| | 0 | 255 | | table.AddCell(new Cell() |
| | 0 | 256 | | .Add(new Paragraph(producerName)) |
| | 0 | 257 | | .AddStyle(cellStyle)); |
| | | 258 | | |
| | | 259 | | // Название товара |
| | 0 | 260 | | var productName = string.IsNullOrEmpty(order.ProductName) ? "" : order.ProductName; |
| | 0 | 261 | | table.AddCell(new Cell() |
| | 0 | 262 | | .Add(new Paragraph(productName)) |
| | 0 | 263 | | .AddStyle(cellStyle)); |
| | | 264 | | |
| | | 265 | | // Количество |
| | 0 | 266 | | table.AddCell(new Cell() |
| | 0 | 267 | | .Add(new Paragraph($"{order.Quantity} шт").SetTextAlignment(TextAlignment.CENTER)) |
| | 0 | 268 | | .AddStyle(cellStyle)); |
| | | 269 | | |
| | | 270 | | // Остаток на складе |
| | 0 | 271 | | var stockCell = new Cell().AddStyle(cellStyle); |
| | | 272 | | |
| | 0 | 273 | | if (_stocks != null && _stocks.TryGetValue(order.Id, out var stockInfos) && stockInfos != null & |
| | | 274 | | { |
| | | 275 | | // Создаем список остатков для этого заказа |
| | 0 | 276 | | foreach (var stock in stockInfos) |
| | | 277 | | { |
| | 0 | 278 | | stockCell.Add(new Paragraph($"{stock.StoreTitle}: {stock.Amount} шт") |
| | 0 | 279 | | .SetFontSize(6) |
| | 0 | 280 | | .SetMargin(0) |
| | 0 | 281 | | .SetPadding(0)); |
| | | 282 | | } |
| | | 283 | | } |
| | | 284 | | else |
| | | 285 | | { |
| | 0 | 286 | | stockCell.Add(new Paragraph("Нет данных").SetFontSize(6)); |
| | | 287 | | } |
| | | 288 | | |
| | 0 | 289 | | table.AddCell(stockCell); |
| | | 290 | | |
| | 0 | 291 | | var purchasePrice = order.PurchasePrice ?? 0m; |
| | 0 | 292 | | var sum = (order.Quantity ?? 0) * purchasePrice; |
| | 0 | 293 | | total += sum; |
| | 0 | 294 | | table.AddCell(new Cell().Add( |
| | 0 | 295 | | new Paragraph(purchasePrice.ToString("N2")) |
| | 0 | 296 | | .SetFontSize(7) |
| | 0 | 297 | | .SetTextAlignment(TextAlignment.RIGHT) |
| | 0 | 298 | | .SetFont(_font) |
| | 0 | 299 | | )); |
| | | 300 | | |
| | 0 | 301 | | table.AddCell(new Cell().Add( |
| | 0 | 302 | | new Paragraph(((decimal)sum).ToString("N2")) |
| | 0 | 303 | | .SetFontSize(7) |
| | 0 | 304 | | .SetTextAlignment(TextAlignment.RIGHT) |
| | 0 | 305 | | .SetFont(_font) |
| | 0 | 306 | | )); |
| | | 307 | | |
| | | 308 | | |
| | 0 | 309 | | rowNumber++; |
| | | 310 | | } |
| | | 311 | | |
| | 0 | 312 | | _document.Add(table); |
| | | 313 | | |
| | | 314 | | // Добавляем отступ между таблицами клиентов |
| | 0 | 315 | | _document.Add(new Paragraph(" ").SetMarginBottom(10)); |
| | | 316 | | } |
| | | 317 | | } |
| | | 318 | | else |
| | | 319 | | { |
| | 0 | 320 | | _document.Add(new Paragraph("Получатель: Не указан") |
| | 0 | 321 | | .SetFont(_font) |
| | 0 | 322 | | .SetFontSize(11) |
| | 0 | 323 | | .SetMarginBottom(10)); |
| | | 324 | | |
| | 0 | 325 | | _document.Add(new Paragraph("Нет данных о заказах") |
| | 0 | 326 | | .SetFont(_font) |
| | 0 | 327 | | .SetFontSize(10) |
| | 0 | 328 | | .SetFontColor(ColorConstants.RED)); |
| | | 329 | | } |
| | | 330 | | |
| | 0 | 331 | | _document.Add(new Paragraph($"Итого: {total:N2} руб. {ndsData}.") |
| | 0 | 332 | | .SetFont(_boldFont) |
| | 0 | 333 | | .SetTextAlignment(TextAlignment.RIGHT)); |
| | | 334 | | |
| | 0 | 335 | | _document.Add(new Paragraph($"Всего наименований {_orders?.Count ?? 0}, на сумму {total:N2} руб.") |
| | 0 | 336 | | .SetFont(_font)); |
| | | 337 | | |
| | | 338 | | // Добавляем комментарий если есть |
| | 0 | 339 | | if (!string.IsNullOrEmpty(_transaction.Comment)) |
| | | 340 | | { |
| | 0 | 341 | | _document.Add(new Paragraph($"Примечание: {_transaction.Comment}") |
| | 0 | 342 | | .SetFont(_font) |
| | 0 | 343 | | .SetFontSize(10) |
| | 0 | 344 | | .SetMarginTop(10)); |
| | | 345 | | } |
| | | 346 | | |
| | 0 | 347 | | _document.Close(); |
| | 0 | 348 | | return _memoryStream.ToArray(); |
| | | 349 | | } |
| | 0 | 350 | | catch (Exception ex) |
| | | 351 | | { |
| | 0 | 352 | | return CreateFallbackPdf(ex.Message); |
| | | 353 | | } |
| | 0 | 354 | | } |
| | | 355 | | |
| | | 356 | | private byte[] CreateFallbackPdf(string? errorMessage = null) |
| | | 357 | | { |
| | 0 | 358 | | var fallbackStream = new MemoryStream(); |
| | 0 | 359 | | var fallbackWriter = new PdfWriter(fallbackStream); |
| | 0 | 360 | | var fallbackPdf = new PdfDocument(fallbackWriter); |
| | 0 | 361 | | var fallbackDoc = new Document(fallbackPdf); |
| | | 362 | | |
| | 0 | 363 | | fallbackDoc.Add(new Paragraph("Перемещение запасов").SetFontSize(16)); |
| | | 364 | | |
| | 0 | 365 | | if (!string.IsNullOrEmpty(errorMessage)) |
| | | 366 | | { |
| | 0 | 367 | | fallbackDoc.Add(new Paragraph($"Ошибка: {errorMessage}").SetFontColor(ColorConstants.RED)); |
| | | 368 | | } |
| | | 369 | | |
| | 0 | 370 | | fallbackDoc.Add(new Paragraph($"№ {_transaction.Id}")); |
| | 0 | 371 | | fallbackDoc.Add(new Paragraph($"Дата: {_transaction.FormattedCreatedTimeDateTime}")); |
| | | 372 | | |
| | 0 | 373 | | fallbackDoc.Close(); |
| | 0 | 374 | | return fallbackStream.ToArray(); |
| | | 375 | | } |
| | | 376 | | } |