C#控制台应用打印发票:解决Notes行溢出换行问题
解决发票“Notes”行内容溢出自动换行问题
当客户添加的添加剂过多时,发票里的“Notes”行会出现内容溢出,破坏整体格式。我们可以通过添加文本拆分的辅助方法,让长内容自动换行,并保持发票的格式对齐。
修改后的完整代码
private static void PrintInvoice(Drink drink) { Console.ForegroundColor = ConsoleColor.Green; // 定义每行最大宽度 const int lineWidth = 46; // Notes行前缀的格式 const string notesPrefix = "/ Notes: Added "; // 后续换行的缩进前缀,保证格式对齐 const string notesIndentPrefix = "/ "; // 计算每行可容纳的内容宽度 int availableWidth = lineWidth - notesPrefix.Length; // 打印表头 Console.WriteLine($"\t\t\t\t\t/{new string('=', lineWidth)}/"); Console.WriteLine($"\t\t\t\t\t/{new string(' ', lineWidth / 2 - 3)}INVOICE{new string(' ', lineWidth / 2 - 4)}/"); Console.WriteLine($"\t\t\t\t\t/{new string('=', lineWidth)}/"); // 打印其他字段 Console.WriteLine($"\t\t\t\t\t/ Date: {DateTime.Now.ToString("yyyy-MM-dd HH:mm")}"); Console.WriteLine($"\t\t\t\t\t/ Customer: {drink.CustomerName}"); Console.WriteLine($"\t\t\t\t\t/ Drink: {drink.Name}"); // 处理Notes内容换行 string notesContent = drink.GetCustomizations(); List<string> lines = SplitTextIntoLines(notesContent, availableWidth); // 打印第一行 Console.WriteLine($"\t\t\t\t\t{notesPrefix}{lines[0]}"); // 打印后续换行的内容 for (int i = 1; i < lines.Count; i++) { Console.WriteLine($"\t\t\t\t\t{notesIndentPrefix}{lines[i]}"); } Console.WriteLine($"\t\t\t\t\t/ Total Price: ${drink.Price}"); // 打印表尾 Console.WriteLine($"\t\t\t\t\t/{new string('=', lineWidth)}/"); } // 辅助方法:将长文本拆分为指定宽度的多行,优先在空格处拆分避免截断单词 private static List<string> SplitTextIntoLines(string text, int maxLineLength) { List<string> lines = new List<string>(); if (string.IsNullOrEmpty(text)) { lines.Add(""); return lines; } int currentIndex = 0; while (currentIndex < text.Length) { // 取当前行最大可容纳长度 int length = Math.Min(maxLineLength, text.Length - currentIndex); // 非末尾行时,尽量在空格处拆分 if (currentIndex + length < text.Length) { int lastSpaceIndex = text.LastIndexOf(' ', currentIndex + length, length); if (lastSpaceIndex > currentIndex) { length = lastSpaceIndex - currentIndex; } } // 截取当前行并去除末尾空格 lines.Add(text.Substring(currentIndex, length).TrimEnd()); currentIndex += length; // 跳过换行后的开头空格,避免多余缩进 while (currentIndex < text.Length && char.IsWhiteSpace(text[currentIndex])) { currentIndex++; } } return lines; }
关键说明
- 文本拆分逻辑:辅助方法
SplitTextIntoLines优先在空格处拆分长文本,避免截断单词;如果没有合适的空格,才按最大宽度截断,保证内容可读性。 - 格式对齐:第一行使用
/ Notes: Added作为前缀,后续换行的行用等长度的缩进前缀/,确保所有Notes行的内容左对齐,保持发票整体格式统一。 - 宽度控制:通过计算
availableWidth(总宽度减去前缀长度),确保每行内容不会超出设定的lineWidth,彻底解决溢出问题。
内容的提问来源于stack exchange,提问作者anonymous25
相关产品推荐
相关产品推荐

