Subversion Repositories SmartDukaan

Rev

Rev 35028 | Details | Compare with Previous | 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) {
35799 amit 70
            boolean marginSeparatorAdded = false;
35028 amit 71
            for (CustomOrderItem item : invoice.getOrderItems()) {
35799 amit 72
                if (item != null && item.isMarginScheme() && !marginSeparatorAdded) {
73
                    lines.add(repeat('-', lineWidth));
74
                    lines.add(center("Margin Scheme - Rule 32(5)", lineWidth));
75
                    lines.add(repeat('-', lineWidth));
76
                    marginSeparatorAdded = true;
77
                }
35028 amit 78
                lines.addAll(formatItem(item, lineWidth));
79
            }
80
        }
81
        lines.add(repeat('-', lineWidth));
82
 
83
        // ===== TOTALS =====
84
        lines.add(right("TOTAL: " + formatAmount(invoice.getTotalAmount()), lineWidth));
85
 
86
        // T&Cs
87
        if (invoice.getTncs() != null && !invoice.getTncs().isEmpty()) {
88
            lines.add(repeat('-', lineWidth));
89
            lines.add("Terms & Conditions:");
90
            for (String t : invoice.getTncs()) {
91
                lines.addAll(wrapWords(safe(t), lineWidth));
92
            }
93
        }
94
 
35799 amit 95
        // ===== MARGIN SCHEME DECLARATION =====
96
        if (invoice.isHasMarginSchemeItems() && invoice.getMarginSchemeDeclarations() != null
97
                && !invoice.getMarginSchemeDeclarations().isEmpty()) {
98
            lines.add(repeat('-', lineWidth));
99
            lines.add("Margin Scheme Declaration:");
100
            for (String decl : invoice.getMarginSchemeDeclarations()) {
101
                lines.addAll(wrapWords("- " + safe(decl), lineWidth));
102
            }
103
        }
104
 
35028 amit 105
        lines.add(center("Thank you! Visit again", lineWidth));
106
        // Writer writes into the provided baos
107
        Document document = new Document();
108
 
109
        // Create PdfWriter that writes into baos
110
        try {
111
            PdfWriter.getInstance(document, baos);
112
        } catch (DocumentException e) {
113
            throw new ProfitMandiBusinessException("Could not Create instance", "Could not create instance", "Could not create instance");
114
        }
115
 
116
        document.open();
117
 
118
        // Add each string as a new line
119
        for (String line : lines) {
120
            try {
121
                document.add(new Paragraph(line));
122
            } catch (DocumentException e) {
123
                throw new RuntimeException(e);
124
            }
125
        }
126
 
127
        document.close(); // Very important: flushes to baos
128
 
129
    }
130
 
131
    public static void saveAsPdf(String filePath, List<String> lines) throws Exception {
132
        /*PdfWriter writer = new PdfWriter(filePath);
133
 
134
        // Create PDF document
135
        PdfDocument pdf = new PdfDocument(writer);
136
 
137
        // Add a document layout wrapper
138
        Document document = new Document(pdf);
139
 
140
        // Add each line as a paragraph
141
        for (String line : lines) {
142
            document.add(new Paragraph(line));
143
        }
144
 
145
        document.close();*/
146
    }
147
 
148
    /**
149
     * Format one item with word-wrapped description and aligned Qty/Rate/Amount.
150
     */
151
    public static List<String> formatItem(CustomOrderItem item, int lineWidth) {
152
        List<String> out = new ArrayList<String>();
153
        if (item == null) return out;
154
 
155
        // trailer columns: Qty(4), Rate(9 - incl. 2 decimals), Amount(10)
156
        String trailer = String.format("%4d %9.2f %10.2f",
157
                item.getQuantity(),
158
                item.getRate(),
159
                item.getNetAmount());
160
 
161
        int descWidth = Math.max(0, lineWidth - trailer.length());
162
        List<String> wrappedDesc = wrapWords(safe(item.getDescription()), descWidth);
163
        if (wrappedDesc.isEmpty()) wrappedDesc.add("");
164
 
165
        // First line: part of desc + trailer
166
        out.add(rightPad(wrappedDesc.get(0), descWidth) + trailer);
167
 
168
        // Remaining description lines
169
        for (int i = 1; i < wrappedDesc.size(); i++) {
170
            out.add(wrappedDesc.get(i));
171
        }
172
 
173
        // Optional meta lines under the item
174
        if (safe(item.getHsnCode()).length() > 0) {
175
            out.add("   HSN: " + item.getHsnCode());
176
        }
177
 
178
        float gstRate = safeFloat(item.getIgstRate()) + safeFloat(item.getCgstRate()) + safeFloat(item.getSgstRate());
179
        if (gstRate > 0.0f) {
180
            out.add(String.format("   GST: %.2f%% (IGST %.2f, CGST %.2f, SGST %.2f)",
181
                    gstRate, safeFloat(item.getIgstRate()), safeFloat(item.getCgstRate()), safeFloat(item.getSgstRate())));
182
        }
183
 
184
        if (safeFloat(item.getDiscount()) > 0.0f) {
185
            out.add("   Disc: " + formatAmount(item.getDiscount()));
186
        }
187
 
35799 amit 188
        if (item.isMarginScheme()) {
189
            out.add("   Purchase Price: " + formatAmount(item.getPurchasePrice()));
190
            out.add("   Selling Price : " + formatAmount(item.getSellingPrice()));
191
            out.add("   Margin (Taxable): " + formatAmount(item.getMargin()));
192
        }
193
 
35028 amit 194
        return out;
195
    }
196
 
197
// ===== Printing =====
198
 
199
    /**
200
     * Send lines to the DEFAULT system printer. Works if your thermal printer has a Windows/Linux driver.
201
     * If you need ESC/POS raw, see sendRawWithCut.
202
     */
203
    public static void sendToDefaultPrinter(List<String> lines) throws PrintException {
204
        PrintService svc = PrintServiceLookup.lookupDefaultPrintService();
205
        if (svc == null) throw new PrintException("No default print service found");
206
        DocPrintJob job = svc.createPrintJob();
207
        StringBuilder sb = new StringBuilder();
208
        for (String line : lines) {
209
            sb.append(line == null ? "" : line).append('\n');
210
        }
211
        byte[] data = sb.toString().getBytes(Charset.forName("UTF-8"));
212
        Doc doc = new SimpleDoc(data, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
213
        job.print(doc, null);
214
    }
215
 
216
    /**
217
     * Attempt to send raw text + ESC/POS full cut to the default printer.
218
     * This only works if the printer driver accepts raw bytes. If you see junk, switch to a RAW queue or an ESC/POS lib.
219
     */
220
    public static void sendRawWithCut(List<String> lines) throws PrintException {
221
        PrintService svc = PrintServiceLookup.lookupDefaultPrintService();
222
        if (svc == null) throw new PrintException("No default print service found");
223
        DocPrintJob job = svc.createPrintJob();
224
 
225
        // Build payload: text + some feeds + ESC/POS cut
226
        byte[] newline = new byte[]{'\n'};
227
        byte[] feed = new byte[]{0x1B, 'd', 0x05}; // ESC d 5  -> feed 5 lines
228
        byte[] cut = new byte[]{0x1D, 0x56, 0x42, 0x00}; // GS V B 0 -> full cut
229
 
230
        // join
231
        List<byte[]> chunks = new ArrayList<byte[]>();
232
        StringBuilder sb = new StringBuilder();
233
        for (String line : lines) {
234
            sb.append(line == null ? "" : line).append('\n');
235
        }
236
        chunks.add(sb.toString().getBytes(Charset.forName("UTF-8")));
237
        chunks.add(feed);
238
        chunks.add(cut);
239
 
240
        int total = 0;
241
        for (byte[] ch : chunks) total += ch.length;
242
        byte[] payload = new byte[total];
243
        int pos = 0;
244
        for (byte[] ch : chunks) {
245
            System.arraycopy(ch, 0, payload, pos, ch.length);
246
            pos += ch.length;
247
        }
248
 
249
        Doc doc = new SimpleDoc(payload, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
250
        job.print(doc, null);
251
    }
252
 
253
// ===== Helpers =====
254
 
255
    private static void addIfNotEmpty(List<String> list, String s) {
256
        if (s == null) return;
257
        if (s.trim().length() == 0) return;
258
        list.add(s);
259
    }
260
 
261
    private static String safe(String s) {
262
        return s == null ? "" : s;
263
    }
264
 
265
    private static float safeFloat(Float f) {
266
        return f == null ? 0.0f : f.floatValue();
267
    }
268
 
269
    private static String formatAmount(float v) {
270
        return String.format("%.2f", v);
271
    }
272
 
273
    private static String rightPad(String s, int width) {
274
        if (s == null) s = "";
275
        if (s.length() >= width) return s.substring(0, width);
276
        StringBuilder sb = new StringBuilder(s);
277
        while (sb.length() < width) sb.append(' ');
278
        return sb.toString();
279
    }
280
 
281
    private static String leftPad(String s, int width) {
282
        if (s == null) s = "";
283
        if (s.length() >= width) return s.substring(s.length() - width);
284
        StringBuilder sb = new StringBuilder();
285
        while (sb.length() + s.length() < width) sb.append(' ');
286
        sb.append(s);
287
        return sb.toString();
288
    }
289
 
290
    private static String center(String text, int width) {
291
        if (text == null) return "";
292
        if (text.length() >= width) return text;
293
        int pad = (width - text.length()) / 2;
294
        StringBuilder sb = new StringBuilder();
295
        for (int i = 0; i < pad; i++) sb.append(' ');
296
        sb.append(text);
297
        return sb.toString();
298
    }
299
 
300
    private static String right(String text, int width) {
301
        if (text == null) return "";
302
        if (text.length() >= width) return text;
303
        StringBuilder sb = new StringBuilder();
304
        for (int i = 0; i < width - text.length(); i++) sb.append(' ');
305
        sb.append(text);
306
        return sb.toString();
307
    }
308
 
309
    private static String repeat(char ch, int count) {
310
        StringBuilder sb = new StringBuilder();
311
        for (int i = 0; i < count; i++) sb.append(ch);
312
        return sb.toString();
313
    }
314
 
315
    private static String repeat(char ch, int count, boolean withNewline) {
316
        String s = repeat(ch, count);
317
        return withNewline ? s + "\n" : s;
318
    }
319
 
320
    private static String repeat(char ch1, char ch2, int count) {
321
        StringBuilder sb = new StringBuilder();
322
        for (int i = 0; i < count; i++) {
323
            sb.append(ch1).append(ch2);
324
        }
325
        return sb.toString();
326
    }
327
 
328
    private static String repeat(String s, int count) {
329
        StringBuilder sb = new StringBuilder();
330
        for (int i = 0; i < count; i++) sb.append(s);
331
        return sb.toString();
332
    }
333
 
334
    private static String repeat(char ch, int count, String trailer) {
335
        StringBuilder sb = new StringBuilder();
336
        for (int i = 0; i < count; i++) sb.append(ch);
337
        sb.append(trailer);
338
        return sb.toString();
339
    }
340
 
341
    private static String repeat(char ch, int count, String trailer, boolean newline) {
342
        String s = repeat(ch, count, trailer);
343
        return newline ? s + "\n" : s;
344
    }
345
 
346
    /**
347
     * Word wrap that prefers breaking at spaces; falls back to hard breaks for very long tokens.
348
     */
349
    public static List<String> wrapWords(String text, int width) {
350
        List<String> out = new ArrayList<String>();
351
        if (text == null) return out;
352
        text = text.trim();
353
        if (width <= 0) {
354
            out.add(text);
355
            return out;
356
        }
357
 
358
        String[] words = text.split("\\s+");
359
        StringBuilder line = new StringBuilder();
360
        int i;
361
        for (i = 0; i < words.length; i++) {
362
            String w = words[i];
363
            if (w.length() > width) {
364
                // Flush current line
365
                if (line.length() > 0) {
366
                    out.add(line.toString());
367
                    line.setLength(0);
368
                }
369
                // Hard wrap the long word
370
                int idx = 0;
371
                while (idx < w.length()) {
372
                    int end = Math.min(idx + width, w.length());
373
                    out.add(w.substring(idx, end));
374
                    idx = end;
375
                }
376
                continue;
377
            }
378
            if (line.length() == 0) {
379
                line.append(w);
380
            } else if (line.length() + 1 + w.length() <= width) {
381
                line.append(' ').append(w);
382
            } else {
383
                out.add(line.toString());
384
                line.setLength(0);
385
                line.append(w);
386
            }
387
        }
388
        if (line.length() > 0) out.add(line.toString());
389
        return out;
390
    }
391
}