Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
35028 amit 1
package com.spice.profitmandi.common.util;// package com.spice.profitmandi.print; // <- uncomment and adjust if you want this in a package
2
 
3
import com.itextpdf.text.Document;
4
import com.itextpdf.text.DocumentException;
5
import com.itextpdf.text.Paragraph;
6
import com.itextpdf.text.pdf.PdfWriter;
7
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
8
import com.spice.profitmandi.common.model.CustomCustomer;
9
import com.spice.profitmandi.common.model.CustomOrderItem;
10
import com.spice.profitmandi.common.model.InvoicePdfModel;
11
 
12
import javax.print.*;
13
import java.io.ByteArrayOutputStream;
14
import java.nio.charset.Charset;
15
import java.util.ArrayList;
16
import java.util.List;
17
 
18
/**
19
 * Utility to format and print an InvoicePdfModel to a thermal printer width (58mm/80mm).
20
 * Compatible with Java 8.
21
 */
22
public class InvoiceFormatter {
23
 
24
    public static final int WIDTH_58MM = 32; // typical ~32 chars/line
25
    public static final int WIDTH_80MM = 48; // typical ~48 chars/line
26
 
27
    /**
28
     * Build printable lines for a thermal printer.
29
     */
30
    public static void getInvoice(InvoicePdfModel invoice, ByteArrayOutputStream baos, int lineWidth) throws ProfitMandiBusinessException {
31
        List<String> lines = new ArrayList<>();
32
 
33
        // ===== HEADER =====
34
        addIfNotEmpty(lines, center(safe(invoice.getTitle()), lineWidth));
35
        if (invoice.isCancelled()) {
36
            lines.add(center("*** INVOICE CANCELLED ***", lineWidth));
37
        }
38
        addIfNotEmpty(lines, center("Invoice No: " + safe(invoice.getInvoiceNumber()), lineWidth));
39
        addIfNotEmpty(lines, center("Date: " + safe(invoice.getInvoiceDate()), lineWidth));
40
        lines.add(repeat('-', lineWidth));
41
 
42
        // ===== CUSTOMER =====
43
        CustomCustomer c = invoice.getCustomer();
44
        if (c != null) {
45
            String fullName = (safe(c.getFirstName()) + " " + safe(c.getLastName())).trim();
46
            addIfNotEmpty(lines, "Customer: " + fullName);
47
            addIfNotEmpty(lines, "Mobile  : " + safe(c.getMobileNumber()));
48
            addIfNotEmpty(lines, "GSTIN   : " + safe(c.getGstNumber()));
49
 
50
            if (c.getAddress() != null) {
51
                List<String> addrLines = wrapWords("Address: " + c.getAddress().getAddressString(), lineWidth);
52
                lines.addAll(addrLines);
53
            }
54
            if (safe(invoice.getCustomerAddressStateCode()).length() > 0) {
55
                lines.add("State   : " + invoice.getCustomerAddressStateCode());
56
            }
57
            lines.add(repeat('-', lineWidth));
58
        }
59
 
60
        // ===== ITEMS HEADER =====
61
        // We'll allocate fixed widths for columns: Qty(4) Rate(9) Amount(10) -> trailer length ~ 4 + 1 + 9 + 1 + 10 = 25
62
        // Thus, description width = lineWidth - 25
63
        final String hdrTrailer = rightPad("Qty", 4) + " " + rightPad("Rate", 9) + " " + rightPad("Amount", 10);
64
        int descWidthForHeader = Math.max(0, lineWidth - hdrTrailer.length());
65
        lines.add(rightPad("Item", descWidthForHeader) + hdrTrailer);
66
        lines.add(repeat('-', lineWidth));
67
 
68
        // ===== ITEMS =====
69
        if (invoice.getOrderItems() != null) {
70
            for (CustomOrderItem item : invoice.getOrderItems()) {
71
                lines.addAll(formatItem(item, lineWidth));
72
            }
73
        }
74
        lines.add(repeat('-', lineWidth));
75
 
76
        // ===== TOTALS =====
77
        lines.add(right("TOTAL: " + formatAmount(invoice.getTotalAmount()), lineWidth));
78
 
79
        // T&Cs
80
        if (invoice.getTncs() != null && !invoice.getTncs().isEmpty()) {
81
            lines.add(repeat('-', lineWidth));
82
            lines.add("Terms & Conditions:");
83
            for (String t : invoice.getTncs()) {
84
                lines.addAll(wrapWords(safe(t), lineWidth));
85
            }
86
        }
87
 
88
        lines.add(center("Thank you! Visit again", lineWidth));
89
        // Writer writes into the provided baos
90
        Document document = new Document();
91
 
92
        // Create PdfWriter that writes into baos
93
        try {
94
            PdfWriter.getInstance(document, baos);
95
        } catch (DocumentException e) {
96
            throw new ProfitMandiBusinessException("Could not Create instance", "Could not create instance", "Could not create instance");
97
        }
98
 
99
        document.open();
100
 
101
        // Add each string as a new line
102
        for (String line : lines) {
103
            try {
104
                document.add(new Paragraph(line));
105
            } catch (DocumentException e) {
106
                throw new RuntimeException(e);
107
            }
108
        }
109
 
110
        document.close(); // Very important: flushes to baos
111
 
112
    }
113
 
114
    public static void saveAsPdf(String filePath, List<String> lines) throws Exception {
115
        /*PdfWriter writer = new PdfWriter(filePath);
116
 
117
        // Create PDF document
118
        PdfDocument pdf = new PdfDocument(writer);
119
 
120
        // Add a document layout wrapper
121
        Document document = new Document(pdf);
122
 
123
        // Add each line as a paragraph
124
        for (String line : lines) {
125
            document.add(new Paragraph(line));
126
        }
127
 
128
        document.close();*/
129
    }
130
 
131
    /**
132
     * Format one item with word-wrapped description and aligned Qty/Rate/Amount.
133
     */
134
    public static List<String> formatItem(CustomOrderItem item, int lineWidth) {
135
        List<String> out = new ArrayList<String>();
136
        if (item == null) return out;
137
 
138
        // trailer columns: Qty(4), Rate(9 - incl. 2 decimals), Amount(10)
139
        String trailer = String.format("%4d %9.2f %10.2f",
140
                item.getQuantity(),
141
                item.getRate(),
142
                item.getNetAmount());
143
 
144
        int descWidth = Math.max(0, lineWidth - trailer.length());
145
        List<String> wrappedDesc = wrapWords(safe(item.getDescription()), descWidth);
146
        if (wrappedDesc.isEmpty()) wrappedDesc.add("");
147
 
148
        // First line: part of desc + trailer
149
        out.add(rightPad(wrappedDesc.get(0), descWidth) + trailer);
150
 
151
        // Remaining description lines
152
        for (int i = 1; i < wrappedDesc.size(); i++) {
153
            out.add(wrappedDesc.get(i));
154
        }
155
 
156
        // Optional meta lines under the item
157
        if (safe(item.getHsnCode()).length() > 0) {
158
            out.add("   HSN: " + item.getHsnCode());
159
        }
160
 
161
        float gstRate = safeFloat(item.getIgstRate()) + safeFloat(item.getCgstRate()) + safeFloat(item.getSgstRate());
162
        if (gstRate > 0.0f) {
163
            out.add(String.format("   GST: %.2f%% (IGST %.2f, CGST %.2f, SGST %.2f)",
164
                    gstRate, safeFloat(item.getIgstRate()), safeFloat(item.getCgstRate()), safeFloat(item.getSgstRate())));
165
        }
166
 
167
        if (safeFloat(item.getDiscount()) > 0.0f) {
168
            out.add("   Disc: " + formatAmount(item.getDiscount()));
169
        }
170
 
171
        return out;
172
    }
173
 
174
// ===== Printing =====
175
 
176
    /**
177
     * Send lines to the DEFAULT system printer. Works if your thermal printer has a Windows/Linux driver.
178
     * If you need ESC/POS raw, see sendRawWithCut.
179
     */
180
    public static void sendToDefaultPrinter(List<String> lines) throws PrintException {
181
        PrintService svc = PrintServiceLookup.lookupDefaultPrintService();
182
        if (svc == null) throw new PrintException("No default print service found");
183
        DocPrintJob job = svc.createPrintJob();
184
        StringBuilder sb = new StringBuilder();
185
        for (String line : lines) {
186
            sb.append(line == null ? "" : line).append('\n');
187
        }
188
        byte[] data = sb.toString().getBytes(Charset.forName("UTF-8"));
189
        Doc doc = new SimpleDoc(data, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
190
        job.print(doc, null);
191
    }
192
 
193
    /**
194
     * Attempt to send raw text + ESC/POS full cut to the default printer.
195
     * This only works if the printer driver accepts raw bytes. If you see junk, switch to a RAW queue or an ESC/POS lib.
196
     */
197
    public static void sendRawWithCut(List<String> lines) throws PrintException {
198
        PrintService svc = PrintServiceLookup.lookupDefaultPrintService();
199
        if (svc == null) throw new PrintException("No default print service found");
200
        DocPrintJob job = svc.createPrintJob();
201
 
202
        // Build payload: text + some feeds + ESC/POS cut
203
        byte[] newline = new byte[]{'\n'};
204
        byte[] feed = new byte[]{0x1B, 'd', 0x05}; // ESC d 5  -> feed 5 lines
205
        byte[] cut = new byte[]{0x1D, 0x56, 0x42, 0x00}; // GS V B 0 -> full cut
206
 
207
        // join
208
        List<byte[]> chunks = new ArrayList<byte[]>();
209
        StringBuilder sb = new StringBuilder();
210
        for (String line : lines) {
211
            sb.append(line == null ? "" : line).append('\n');
212
        }
213
        chunks.add(sb.toString().getBytes(Charset.forName("UTF-8")));
214
        chunks.add(feed);
215
        chunks.add(cut);
216
 
217
        int total = 0;
218
        for (byte[] ch : chunks) total += ch.length;
219
        byte[] payload = new byte[total];
220
        int pos = 0;
221
        for (byte[] ch : chunks) {
222
            System.arraycopy(ch, 0, payload, pos, ch.length);
223
            pos += ch.length;
224
        }
225
 
226
        Doc doc = new SimpleDoc(payload, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
227
        job.print(doc, null);
228
    }
229
 
230
// ===== Helpers =====
231
 
232
    private static void addIfNotEmpty(List<String> list, String s) {
233
        if (s == null) return;
234
        if (s.trim().length() == 0) return;
235
        list.add(s);
236
    }
237
 
238
    private static String safe(String s) {
239
        return s == null ? "" : s;
240
    }
241
 
242
    private static float safeFloat(Float f) {
243
        return f == null ? 0.0f : f.floatValue();
244
    }
245
 
246
    private static String formatAmount(float v) {
247
        return String.format("%.2f", v);
248
    }
249
 
250
    private static String rightPad(String s, int width) {
251
        if (s == null) s = "";
252
        if (s.length() >= width) return s.substring(0, width);
253
        StringBuilder sb = new StringBuilder(s);
254
        while (sb.length() < width) sb.append(' ');
255
        return sb.toString();
256
    }
257
 
258
    private static String leftPad(String s, int width) {
259
        if (s == null) s = "";
260
        if (s.length() >= width) return s.substring(s.length() - width);
261
        StringBuilder sb = new StringBuilder();
262
        while (sb.length() + s.length() < width) sb.append(' ');
263
        sb.append(s);
264
        return sb.toString();
265
    }
266
 
267
    private static String center(String text, int width) {
268
        if (text == null) return "";
269
        if (text.length() >= width) return text;
270
        int pad = (width - text.length()) / 2;
271
        StringBuilder sb = new StringBuilder();
272
        for (int i = 0; i < pad; i++) sb.append(' ');
273
        sb.append(text);
274
        return sb.toString();
275
    }
276
 
277
    private static String right(String text, int width) {
278
        if (text == null) return "";
279
        if (text.length() >= width) return text;
280
        StringBuilder sb = new StringBuilder();
281
        for (int i = 0; i < width - text.length(); i++) sb.append(' ');
282
        sb.append(text);
283
        return sb.toString();
284
    }
285
 
286
    private static String repeat(char ch, int count) {
287
        StringBuilder sb = new StringBuilder();
288
        for (int i = 0; i < count; i++) sb.append(ch);
289
        return sb.toString();
290
    }
291
 
292
    private static String repeat(char ch, int count, boolean withNewline) {
293
        String s = repeat(ch, count);
294
        return withNewline ? s + "\n" : s;
295
    }
296
 
297
    private static String repeat(char ch1, char ch2, int count) {
298
        StringBuilder sb = new StringBuilder();
299
        for (int i = 0; i < count; i++) {
300
            sb.append(ch1).append(ch2);
301
        }
302
        return sb.toString();
303
    }
304
 
305
    private static String repeat(String s, int count) {
306
        StringBuilder sb = new StringBuilder();
307
        for (int i = 0; i < count; i++) sb.append(s);
308
        return sb.toString();
309
    }
310
 
311
    private static String repeat(char ch, int count, String trailer) {
312
        StringBuilder sb = new StringBuilder();
313
        for (int i = 0; i < count; i++) sb.append(ch);
314
        sb.append(trailer);
315
        return sb.toString();
316
    }
317
 
318
    private static String repeat(char ch, int count, String trailer, boolean newline) {
319
        String s = repeat(ch, count, trailer);
320
        return newline ? s + "\n" : s;
321
    }
322
 
323
    /**
324
     * Word wrap that prefers breaking at spaces; falls back to hard breaks for very long tokens.
325
     */
326
    public static List<String> wrapWords(String text, int width) {
327
        List<String> out = new ArrayList<String>();
328
        if (text == null) return out;
329
        text = text.trim();
330
        if (width <= 0) {
331
            out.add(text);
332
            return out;
333
        }
334
 
335
        String[] words = text.split("\\s+");
336
        StringBuilder line = new StringBuilder();
337
        int i;
338
        for (i = 0; i < words.length; i++) {
339
            String w = words[i];
340
            if (w.length() > width) {
341
                // Flush current line
342
                if (line.length() > 0) {
343
                    out.add(line.toString());
344
                    line.setLength(0);
345
                }
346
                // Hard wrap the long word
347
                int idx = 0;
348
                while (idx < w.length()) {
349
                    int end = Math.min(idx + width, w.length());
350
                    out.add(w.substring(idx, end));
351
                    idx = end;
352
                }
353
                continue;
354
            }
355
            if (line.length() == 0) {
356
                line.append(w);
357
            } else if (line.length() + 1 + w.length() <= width) {
358
                line.append(' ').append(w);
359
            } else {
360
                out.add(line.toString());
361
                line.setLength(0);
362
                line.append(w);
363
            }
364
        }
365
        if (line.length() > 0) out.add(line.toString());
366
        return out;
367
    }
368
}