Blame | Last modification | View Log | RSS feed
package com.spice.profitmandi.common.util;// package com.spice.profitmandi.print; // <- uncomment and adjust if you want this in a packageimport com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Paragraph;import com.itextpdf.text.pdf.PdfWriter;import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.model.CustomCustomer;import com.spice.profitmandi.common.model.CustomOrderItem;import com.spice.profitmandi.common.model.InvoicePdfModel;import javax.print.*;import java.io.ByteArrayOutputStream;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.List;/*** Utility to format and print an InvoicePdfModel to a thermal printer width (58mm/80mm).* Compatible with Java 8.*/public class InvoiceFormatter {public static final int WIDTH_58MM = 32; // typical ~32 chars/linepublic static final int WIDTH_80MM = 48; // typical ~48 chars/line/*** Build printable lines for a thermal printer.*/public static void getInvoice(InvoicePdfModel invoice, ByteArrayOutputStream baos, int lineWidth) throws ProfitMandiBusinessException {List<String> lines = new ArrayList<>();// ===== HEADER =====addIfNotEmpty(lines, center(safe(invoice.getTitle()), lineWidth));if (invoice.isCancelled()) {lines.add(center("*** INVOICE CANCELLED ***", lineWidth));}addIfNotEmpty(lines, center("Invoice No: " + safe(invoice.getInvoiceNumber()), lineWidth));addIfNotEmpty(lines, center("Date: " + safe(invoice.getInvoiceDate()), lineWidth));lines.add(repeat('-', lineWidth));// ===== CUSTOMER =====CustomCustomer c = invoice.getCustomer();if (c != null) {String fullName = (safe(c.getFirstName()) + " " + safe(c.getLastName())).trim();addIfNotEmpty(lines, "Customer: " + fullName);addIfNotEmpty(lines, "Mobile : " + safe(c.getMobileNumber()));addIfNotEmpty(lines, "GSTIN : " + safe(c.getGstNumber()));if (c.getAddress() != null) {List<String> addrLines = wrapWords("Address: " + c.getAddress().getAddressString(), lineWidth);lines.addAll(addrLines);}if (safe(invoice.getCustomerAddressStateCode()).length() > 0) {lines.add("State : " + invoice.getCustomerAddressStateCode());}lines.add(repeat('-', lineWidth));}// ===== ITEMS HEADER =====// We'll allocate fixed widths for columns: Qty(4) Rate(9) Amount(10) -> trailer length ~ 4 + 1 + 9 + 1 + 10 = 25// Thus, description width = lineWidth - 25final String hdrTrailer = rightPad("Qty", 4) + " " + rightPad("Rate", 9) + " " + rightPad("Amount", 10);int descWidthForHeader = Math.max(0, lineWidth - hdrTrailer.length());lines.add(rightPad("Item", descWidthForHeader) + hdrTrailer);lines.add(repeat('-', lineWidth));// ===== ITEMS =====if (invoice.getOrderItems() != null) {for (CustomOrderItem item : invoice.getOrderItems()) {lines.addAll(formatItem(item, lineWidth));}}lines.add(repeat('-', lineWidth));// ===== TOTALS =====lines.add(right("TOTAL: " + formatAmount(invoice.getTotalAmount()), lineWidth));// T&Csif (invoice.getTncs() != null && !invoice.getTncs().isEmpty()) {lines.add(repeat('-', lineWidth));lines.add("Terms & Conditions:");for (String t : invoice.getTncs()) {lines.addAll(wrapWords(safe(t), lineWidth));}}lines.add(center("Thank you! Visit again", lineWidth));// Writer writes into the provided baosDocument document = new Document();// Create PdfWriter that writes into baostry {PdfWriter.getInstance(document, baos);} catch (DocumentException e) {throw new ProfitMandiBusinessException("Could not Create instance", "Could not create instance", "Could not create instance");}document.open();// Add each string as a new linefor (String line : lines) {try {document.add(new Paragraph(line));} catch (DocumentException e) {throw new RuntimeException(e);}}document.close(); // Very important: flushes to baos}public static void saveAsPdf(String filePath, List<String> lines) throws Exception {/*PdfWriter writer = new PdfWriter(filePath);// Create PDF documentPdfDocument pdf = new PdfDocument(writer);// Add a document layout wrapperDocument document = new Document(pdf);// Add each line as a paragraphfor (String line : lines) {document.add(new Paragraph(line));}document.close();*/}/*** Format one item with word-wrapped description and aligned Qty/Rate/Amount.*/public static List<String> formatItem(CustomOrderItem item, int lineWidth) {List<String> out = new ArrayList<String>();if (item == null) return out;// trailer columns: Qty(4), Rate(9 - incl. 2 decimals), Amount(10)String trailer = String.format("%4d %9.2f %10.2f",item.getQuantity(),item.getRate(),item.getNetAmount());int descWidth = Math.max(0, lineWidth - trailer.length());List<String> wrappedDesc = wrapWords(safe(item.getDescription()), descWidth);if (wrappedDesc.isEmpty()) wrappedDesc.add("");// First line: part of desc + trailerout.add(rightPad(wrappedDesc.get(0), descWidth) + trailer);// Remaining description linesfor (int i = 1; i < wrappedDesc.size(); i++) {out.add(wrappedDesc.get(i));}// Optional meta lines under the itemif (safe(item.getHsnCode()).length() > 0) {out.add(" HSN: " + item.getHsnCode());}float gstRate = safeFloat(item.getIgstRate()) + safeFloat(item.getCgstRate()) + safeFloat(item.getSgstRate());if (gstRate > 0.0f) {out.add(String.format(" GST: %.2f%% (IGST %.2f, CGST %.2f, SGST %.2f)",gstRate, safeFloat(item.getIgstRate()), safeFloat(item.getCgstRate()), safeFloat(item.getSgstRate())));}if (safeFloat(item.getDiscount()) > 0.0f) {out.add(" Disc: " + formatAmount(item.getDiscount()));}return out;}// ===== Printing =====/*** Send lines to the DEFAULT system printer. Works if your thermal printer has a Windows/Linux driver.* If you need ESC/POS raw, see sendRawWithCut.*/public static void sendToDefaultPrinter(List<String> lines) throws PrintException {PrintService svc = PrintServiceLookup.lookupDefaultPrintService();if (svc == null) throw new PrintException("No default print service found");DocPrintJob job = svc.createPrintJob();StringBuilder sb = new StringBuilder();for (String line : lines) {sb.append(line == null ? "" : line).append('\n');}byte[] data = sb.toString().getBytes(Charset.forName("UTF-8"));Doc doc = new SimpleDoc(data, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);job.print(doc, null);}/*** Attempt to send raw text + ESC/POS full cut to the default printer.* This only works if the printer driver accepts raw bytes. If you see junk, switch to a RAW queue or an ESC/POS lib.*/public static void sendRawWithCut(List<String> lines) throws PrintException {PrintService svc = PrintServiceLookup.lookupDefaultPrintService();if (svc == null) throw new PrintException("No default print service found");DocPrintJob job = svc.createPrintJob();// Build payload: text + some feeds + ESC/POS cutbyte[] newline = new byte[]{'\n'};byte[] feed = new byte[]{0x1B, 'd', 0x05}; // ESC d 5 -> feed 5 linesbyte[] cut = new byte[]{0x1D, 0x56, 0x42, 0x00}; // GS V B 0 -> full cut// joinList<byte[]> chunks = new ArrayList<byte[]>();StringBuilder sb = new StringBuilder();for (String line : lines) {sb.append(line == null ? "" : line).append('\n');}chunks.add(sb.toString().getBytes(Charset.forName("UTF-8")));chunks.add(feed);chunks.add(cut);int total = 0;for (byte[] ch : chunks) total += ch.length;byte[] payload = new byte[total];int pos = 0;for (byte[] ch : chunks) {System.arraycopy(ch, 0, payload, pos, ch.length);pos += ch.length;}Doc doc = new SimpleDoc(payload, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);job.print(doc, null);}// ===== Helpers =====private static void addIfNotEmpty(List<String> list, String s) {if (s == null) return;if (s.trim().length() == 0) return;list.add(s);}private static String safe(String s) {return s == null ? "" : s;}private static float safeFloat(Float f) {return f == null ? 0.0f : f.floatValue();}private static String formatAmount(float v) {return String.format("%.2f", v);}private static String rightPad(String s, int width) {if (s == null) s = "";if (s.length() >= width) return s.substring(0, width);StringBuilder sb = new StringBuilder(s);while (sb.length() < width) sb.append(' ');return sb.toString();}private static String leftPad(String s, int width) {if (s == null) s = "";if (s.length() >= width) return s.substring(s.length() - width);StringBuilder sb = new StringBuilder();while (sb.length() + s.length() < width) sb.append(' ');sb.append(s);return sb.toString();}private static String center(String text, int width) {if (text == null) return "";if (text.length() >= width) return text;int pad = (width - text.length()) / 2;StringBuilder sb = new StringBuilder();for (int i = 0; i < pad; i++) sb.append(' ');sb.append(text);return sb.toString();}private static String right(String text, int width) {if (text == null) return "";if (text.length() >= width) return text;StringBuilder sb = new StringBuilder();for (int i = 0; i < width - text.length(); i++) sb.append(' ');sb.append(text);return sb.toString();}private static String repeat(char ch, int count) {StringBuilder sb = new StringBuilder();for (int i = 0; i < count; i++) sb.append(ch);return sb.toString();}private static String repeat(char ch, int count, boolean withNewline) {String s = repeat(ch, count);return withNewline ? s + "\n" : s;}private static String repeat(char ch1, char ch2, int count) {StringBuilder sb = new StringBuilder();for (int i = 0; i < count; i++) {sb.append(ch1).append(ch2);}return sb.toString();}private static String repeat(String s, int count) {StringBuilder sb = new StringBuilder();for (int i = 0; i < count; i++) sb.append(s);return sb.toString();}private static String repeat(char ch, int count, String trailer) {StringBuilder sb = new StringBuilder();for (int i = 0; i < count; i++) sb.append(ch);sb.append(trailer);return sb.toString();}private static String repeat(char ch, int count, String trailer, boolean newline) {String s = repeat(ch, count, trailer);return newline ? s + "\n" : s;}/*** Word wrap that prefers breaking at spaces; falls back to hard breaks for very long tokens.*/public static List<String> wrapWords(String text, int width) {List<String> out = new ArrayList<String>();if (text == null) return out;text = text.trim();if (width <= 0) {out.add(text);return out;}String[] words = text.split("\\s+");StringBuilder line = new StringBuilder();int i;for (i = 0; i < words.length; i++) {String w = words[i];if (w.length() > width) {// Flush current lineif (line.length() > 0) {out.add(line.toString());line.setLength(0);}// Hard wrap the long wordint idx = 0;while (idx < w.length()) {int end = Math.min(idx + width, w.length());out.add(w.substring(idx, end));idx = end;}continue;}if (line.length() == 0) {line.append(w);} else if (line.length() + 1 + w.length() <= width) {line.append(' ').append(w);} else {out.add(line.toString());line.setLength(0);line.append(w);}}if (line.length() > 0) out.add(line.toString());return out;}}