I am facing a string formatting issue during printing an invoice. The invoice is not properly aligned as I required.
My code is below.
public static String padRight(String s, int n) {
return String.format("%-" + n + "s", s);
}
public static String padRightInt(int s, int n) {
return String.format("%-" + n + "d", s);
}
public static void printIvoice(Node node){
Printer printer = Printer.getDefaultPrinter();
PrinterJob printerJob = PrinterJob.createPrinterJob(printer);
double scale = 0.791;
node.getTransforms().add(new Scale(scale, scale));
boolean success = printerJob.printPage(node);
if (success) {
printerJob.endJob();
}
}
public static Node getPrintableText(String[] products){
Label text = new Label();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" Company Name n");
stringBuilder.append("---------------------------------------------" + "n");
stringBuilder.append(String.format("%-40s %5s %10sn", "Item", "Qty", "Price"));
stringBuilder.append(String.format( "%-40s %5s %10sn", "----", "---", "-----"));
for(String product: products){
if(product.trim().length() > 25){
String firstLine = product.trim().substring(0, 25);
stringBuilder.append(firstLine).append(" ").append("n");
String lastLine = product.trim().substring(25);
int spaces = 50 - lastLine.length();
stringBuilder.append( String.format(padRight(lastLine, spaces), lastLine) + String.format(padRightInt(1, 10), 1) +" "+ String.format(padRightInt(1000, 10), 1000)).append("n");
}else{
String temp = product.trim();
int spaces = 50 - temp.length();
stringBuilder.append( String.format(padRight(temp, spaces), temp) + String.format(padRightInt(1, 10), 1) +" "+ String.format(padRightInt(1000, 10), 1000)).append("n");
}
}
stringBuilder.append("_____________________________________________" + "n");
stringBuilder.append("Net Amount 5000" + "n");
stringBuilder.append("_____________________________________________" + "n");
stringBuilder.append("Thank you so much!" + "n");
text.setText(stringBuilder.toString());
return text;
}
Here is the main method to call this code.
public static void main(String[] args) {
String[] productName = {
"Android",
"Mac OS",
"Windows 10 Operating System",
"Linux Operating System",
"Windows Server OS"
};
Node node = getPrintableText(productName);
printIvoice(node);
}
The code output is below
I want to align the output according to product name length.
I tried to format it through extra spaces, but it’s not working. I want to align the quantity and price columns properly. Please help. Thanks in advance.
2