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