Commit 066c9656 by Wyh

3-19 清機報表字體太小問題

parent f2fd9308
...@@ -7,11 +7,11 @@ import com.gingersoft.gsa.cloud.main.R; ...@@ -7,11 +7,11 @@ import com.gingersoft.gsa.cloud.main.R;
import com.gingersoft.gsa.cloud.main.mvp.contract.SettlementReportContract; import com.gingersoft.gsa.cloud.main.mvp.contract.SettlementReportContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SendSettlement; import com.gingersoft.gsa.cloud.main.mvp.model.bean.SendSettlement;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SettlementReport; import com.gingersoft.gsa.cloud.main.mvp.model.bean.SettlementReport;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem3;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem5;
import com.gingersoft.gsa.cloud.main.mvp.ui.activity.SettlementReportActivity; import com.gingersoft.gsa.cloud.main.mvp.ui.activity.SettlementReportActivity;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.SettlementReportItem5Adapter; import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.SettlementReportItem5Adapter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.SettlementReportItemAdapter; import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.SettlementReportItemAdapter;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem3;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem5;
import com.jess.arms.di.scope.ActivityScope; import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader; import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager; import com.jess.arms.integration.AppManager;
...@@ -65,6 +65,8 @@ public class SettlementReportPresenter extends BasePresenter<SettlementReportCon ...@@ -65,6 +65,8 @@ public class SettlementReportPresenter extends BasePresenter<SettlementReportCon
private SettlementReportItem5Adapter mSettlementReportItem5Adapter; private SettlementReportItem5Adapter mSettlementReportItem5Adapter;
private List<SectionTextItem5> mSettlementReportItem5List= new ArrayList<>(); private List<SectionTextItem5> mSettlementReportItem5List= new ArrayList<>();
public SettlementReportItem5Adapter mPrintAdapter;
@Inject @Inject
public SettlementReportPresenter(SettlementReportContract.Model model, SettlementReportContract.View rootView) { public SettlementReportPresenter(SettlementReportContract.Model model, SettlementReportContract.View rootView) {
super(model, rootView); super(model, rootView);
...@@ -89,6 +91,9 @@ public class SettlementReportPresenter extends BasePresenter<SettlementReportCon ...@@ -89,6 +91,9 @@ public class SettlementReportPresenter extends BasePresenter<SettlementReportCon
mSettlementReportItem5Adapter = new SettlementReportItem5Adapter(IActivity, mSettlementReportItem5List); mSettlementReportItem5Adapter = new SettlementReportItem5Adapter(IActivity, mSettlementReportItem5List);
mRootView.setSettlementReportItem5Adapter(mSettlementReportItem5Adapter); mRootView.setSettlementReportItem5Adapter(mSettlementReportItem5Adapter);
} }
if(mPrintAdapter == null){
mPrintAdapter = new SettlementReportItem5Adapter(IActivity, mSettlementReportItem5List, 24);
}
} }
public void notifyReportItemAdapter(List<SectionTextItem3> settlementReportItems) { public void notifyReportItemAdapter(List<SectionTextItem3> settlementReportItems) {
...@@ -101,6 +106,7 @@ public class SettlementReportPresenter extends BasePresenter<SettlementReportCon ...@@ -101,6 +106,7 @@ public class SettlementReportPresenter extends BasePresenter<SettlementReportCon
mSettlementReportItem5List.clear(); mSettlementReportItem5List.clear();
mSettlementReportItem5List.addAll(settlementReportItems); mSettlementReportItem5List.addAll(settlementReportItems);
mSettlementReportItem5Adapter.notifyDataSetChanged(); mSettlementReportItem5Adapter.notifyDataSetChanged();
mPrintAdapter.notifyDataSetChanged();
} }
public void sendSettlement() { public void sendSettlement() {
......
...@@ -9,6 +9,7 @@ import android.widget.TextView; ...@@ -9,6 +9,7 @@ import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
...@@ -16,6 +17,7 @@ import androidx.recyclerview.widget.RecyclerView; ...@@ -16,6 +17,7 @@ import androidx.recyclerview.widget.RecyclerView;
import com.billy.cc.core.component.CC; import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication; import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.LanguageUtils; import com.gingersoft.gsa.cloud.base.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.PrintTransitUtils; import com.gingersoft.gsa.cloud.base.utils.PrintTransitUtils;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtil; import com.gingersoft.gsa.cloud.base.utils.time.TimeUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils; import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
...@@ -24,9 +26,9 @@ import com.gingersoft.gsa.cloud.main.R2; ...@@ -24,9 +26,9 @@ import com.gingersoft.gsa.cloud.main.R2;
import com.gingersoft.gsa.cloud.main.di.component.DaggerSettlementReportComponent; import com.gingersoft.gsa.cloud.main.di.component.DaggerSettlementReportComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.SettlementReportContract; import com.gingersoft.gsa.cloud.main.mvp.contract.SettlementReportContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SettlementReport; import com.gingersoft.gsa.cloud.main.mvp.model.bean.SettlementReport;
import com.gingersoft.gsa.cloud.main.mvp.presenter.SettlementReportPresenter;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem3; import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem3;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem5; import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem5;
import com.gingersoft.gsa.cloud.main.mvp.presenter.SettlementReportPresenter;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog; import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseActivity; import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter; import com.jess.arms.base.DefaultAdapter;
...@@ -37,6 +39,8 @@ import com.qmuiteam.qmui.widget.QMUITopBar; ...@@ -37,6 +39,8 @@ import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog; import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction; import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import org.jetbrains.annotations.NotNull;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
...@@ -78,7 +82,7 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese ...@@ -78,7 +82,7 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese
TextView tv_end_time; TextView tv_end_time;
@BindView(R2.id.scrollView) @BindView(R2.id.scrollView)
ScrollView scrollView; NestedScrollView scrollView;
// @BindView(R2.id.rv_settlement_report_item) // @BindView(R2.id.rv_settlement_report_item)
// RecyclerView rv_settlement_report_item; // RecyclerView rv_settlement_report_item;
...@@ -89,7 +93,6 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese ...@@ -89,7 +93,6 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese
protected String dfformat = "#0.00"; protected String dfformat = "#0.00";
protected DecimalFormat df; protected DecimalFormat df;
private SettlementReport.DataBean mSettlementReportBean; private SettlementReport.DataBean mSettlementReportBean;
private static SettlementReportActivity settlementReportActivity; private static SettlementReportActivity settlementReportActivity;
...@@ -97,7 +100,6 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese ...@@ -97,7 +100,6 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese
return settlementReportActivity; return settlementReportActivity;
} }
@Override @Override
public void setupActivityComponent(@NonNull AppComponent appComponent) { public void setupActivityComponent(@NonNull AppComponent appComponent) {
DaggerSettlementReportComponent //如找不到该类,请编译一下项目 DaggerSettlementReportComponent //如找不到该类,请编译一下项目
...@@ -121,12 +123,11 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese ...@@ -121,12 +123,11 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese
public void initIntent() { public void initIntent() {
Intent intent = getIntent(); Intent intent = getIntent();
mSettlementReportBean = (SettlementReport.DataBean) intent.getSerializableExtra("settlementReportBean"); mSettlementReportBean = (SettlementReport.DataBean) intent.getSerializableExtra("settlementReportBean");
if (mSettlementReportBean != null) {
df = new DecimalFormat(dfformat); df = new DecimalFormat(dfformat);
if (mSettlementReportBean != null) {
mPresenter.initAdapter(); mPresenter.initAdapter();
returnSettlementData(mSettlementReportBean); returnSettlementData(mSettlementReportBean);
} else { } else {
df = new DecimalFormat(dfformat);
mPresenter.initAdapter(); mPresenter.initAdapter();
mPresenter.getSettlementReport(); mPresenter.getSettlementReport();
} }
...@@ -135,12 +136,9 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese ...@@ -135,12 +136,9 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese
@Override @Override
public void initTopBar() { public void initTopBar() {
mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color)); mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color));
mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() { mTopBar.addLeftBackImageButton().setOnClickListener(v -> {
@Override
public void onClick(View v) {
killMyself(); killMyself();
// overridePendingTransition(R.anim.slide_still, R.anim.slide_out_right); // overridePendingTransition(R.anim.slide_still, R.anim.slide_out_right);
}
}); });
mTopBar.setTitle(LanguageUtils.get_language_system(this, "function.order.detail2", "清機報表")).setTextColor(ArmsUtils.getColor(this, R.color.theme_white_color)); mTopBar.setTitle(LanguageUtils.get_language_system(this, "function.order.detail2", "清機報表")).setTextColor(ArmsUtils.getColor(this, R.color.theme_white_color));
} }
...@@ -234,7 +232,7 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese ...@@ -234,7 +232,7 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese
String byBusinessDateText = LanguageUtils.get_language_system(this, "", "由營業日期:"); String byBusinessDateText = LanguageUtils.get_language_system(this, "", "由營業日期:");
String toBusinessDateText = LanguageUtils.get_language_system(this, "", "到營業日期:"); String toBusinessDateText = LanguageUtils.get_language_system(this, "", "到營業日期:");
String headcountOrAverageConsumptionText = LanguageUtils.get_language_system(this, "", "統計:"); String headcountOrAverageConsumptionText = LanguageUtils.get_language_system(this, "", "統計:");
String totalText = LanguageUtils.get_language_system(this, "", "總計:"); String totalText = LanguageUtils.get_language_system(this, "", "總計");
String projectTotalSalesText = LanguageUtils.get_language_system(this, "total.project.sales", "項目銷售總額"); String projectTotalSalesText = LanguageUtils.get_language_system(this, "total.project.sales", "項目銷售總額");
String orderCountallText = LanguageUtils.get_language_system(this, "order.countall_litter", "賬單小數"); String orderCountallText = LanguageUtils.get_language_system(this, "order.countall_litter", "賬單小數");
String netTurnoverText = LanguageUtils.get_language_system(this, "net.turnover", "營業金額淨值"); String netTurnoverText = LanguageUtils.get_language_system(this, "net.turnover", "營業金額淨值");
...@@ -266,21 +264,21 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese ...@@ -266,21 +264,21 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese
SettlementReport.DataBean.VoBean voBean = datasBean.getVo(); SettlementReport.DataBean.VoBean voBean = datasBean.getVo();
if (voBean != null) { if (voBean != null) {
settlementReportItem5s.add(new SectionTextItem5(projectTotalSalesText, " ", " ", " ", "$" + df.format(voBean.getPrices()))); settlementReportItem5s.add(new SectionTextItem5(projectTotalSalesText, null, null, null, "$" + df.format(voBean.getPrices())));
settlementReportItem5s.add(new SectionTextItem5(netTurnoverText, " ", " ", " ", "$" + df.format(voBean.getTotamount()))); settlementReportItem5s.add(new SectionTextItem5(netTurnoverText, null, null, null, "$" + df.format(voBean.getTotamount())));
// if (voBean.getPayNum() > 0) { // if (voBean.getPayNum() > 0) {
// String creditCardText = LanguageUtils.get_language_system(this, "credit.card", "信用卡"); // String creditCardText = LanguageUtils.get_language_system(this, "credit.card", "信用卡");
// SectionTextItem5 printItem = new SectionTextItem5(creditCardText, String.valueOf(voBean.getPayNum()), " "," ","$" + df.format(voBean.getPayamount())); // SectionTextItem5 printItem = new SectionTextItem5(creditCardText, String.valueOf(voBean.getPayNum()), null,null,"$" + df.format(voBean.getPayamount()));
// settlementReportItem5s.add(printItem); // settlementReportItem5s.add(printItem);
// } // }
settlementReportItem5s.add(new SectionTextItem5(" ", " ", " ", " ", " ")); settlementReportItem5s.add(new SectionTextItem5(null, null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5(cashAuditText, " ", " ", " ", " ")); settlementReportItem5s.add(new SectionTextItem5(cashAuditText, null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5(netTurnoverText, " ", " ", " ", "$" + df.format(voBean.getPrices()))); settlementReportItem5s.add(new SectionTextItem5(netTurnoverText, null, null, null, "$" + df.format(voBean.getPrices())));
List<SettlementReport.DataBean.CashBean> cashList = datasBean.getCash(); List<SettlementReport.DataBean.CashBean> cashList = datasBean.getCash();
if (cashList != null && cashList.size() > 0) { if (cashList != null && cashList.size() > 0) {
for (int i = 0; i < cashList.size(); i++) { for (int i = 0; i < cashList.size(); i++) {
SettlementReport.DataBean.CashBean cashBean = cashList.get(i); SettlementReport.DataBean.CashBean cashBean = cashList.get(i);
settlementReportItem5s.add(new SectionTextItem5(cashBean.getPayName(), " ", String.valueOf(cashBean.getPayNum()), " ", "$" + df.format(cashBean.getPayAmount()))); settlementReportItem5s.add(new SectionTextItem5(cashBean.getPayName(), null, String.valueOf(cashBean.getPayNum()), null, "$" + df.format(cashBean.getPayAmount())));
} }
} }
} }
...@@ -291,34 +289,58 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese ...@@ -291,34 +289,58 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese
/**現金詳情*/ /**現金詳情*/
String cashDetailText = LanguageUtils.get_language_system(this, "credit.cash.detail", "現金詳情"); String cashDetailText = LanguageUtils.get_language_system(this, "credit.cash.detail", "現金詳情");
String cashText = LanguageUtils.get_language_system(this, "credit.cash", "現金"); String cashText = LanguageUtils.get_language_system(this, "credit.cash", "現金");
settlementReportItem5s.add(new SectionTextItem5("==============================================================", "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5("==============================================================", null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5(" ", " ", cashDetailText, " ", " ")); settlementReportItem5s.add(new SectionTextItem5(null, null, cashDetailText, null, null));
settlementReportItem5s.add(new SectionTextItem5(cashText, " ", String.valueOf(cashBean.getPayNum()), " ", "$" + df.format(cashBean.getPayAmount()))); settlementReportItem5s.add(new SectionTextItem5(cashText, null, String.valueOf(cashBean.getPayNum()), null, "$" + df.format(cashBean.getPayAmount())));
//統計 //統計
settlementReportItem5s.add(new SectionTextItem5(headcountOrAverageConsumptionText, " ", " ", " ", "$" + df.format(cashBean.getPayAmount()))); settlementReportItem5s.add(new SectionTextItem5(headcountOrAverageConsumptionText, null, null, null, "$" + df.format(cashBean.getPayAmount())));
} }
if (voBean != null) { if (voBean != null) {
/**分析統計*/ /**分析統計*/
settlementReportItem5s.add(new SectionTextItem5("==============================================================", "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5("==============================================================", null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5("", "", analysisStatisticsText, "", "")); settlementReportItem5s.add(new SectionTextItem5(null, null, analysisStatisticsText, null, null));
//帳單金額總數 //帳單金額總數
settlementReportItem5s.add(new SectionTextItem5(totalbillAmountText, " ", " ", " ", "$" + df.format(voBean.getTotamount()))); settlementReportItem5s.add(new SectionTextItem5(totalbillAmountText, null, null, null, "$" + df.format(voBean.getTotamount())));
//帳單數目 / 平均 //帳單數目 / 平均
String averagePrice = df.format(voBean.getPrices() / voBean.getNum()); String averagePrice = "0.00";
settlementReportItem5s.add(new SectionTextItem5(numberBillsOrAverageText, " ", String.valueOf(voBean.getNum()), " ", "$" + averagePrice)); if (voBean.getNum() != 0) {
double number = voBean.getPrices() / voBean.getNum();
averagePrice = df.format(Double.isNaN(number) ? 0 : number);
}
settlementReportItem5s.add(new SectionTextItem5(numberBillsOrAverageText, null, String.valueOf(voBean.getNum()), null, "$" + averagePrice));
//人數 / 平均消費 //人數 / 平均消費
String averageConsumption = df.format(voBean.getPrices() / voBean.getPerson()); String averageConsumption = "0.00";
settlementReportItem5s.add(new SectionTextItem5(headcountAndAverageConsumptionText, " ", String.valueOf(voBean.getPerson()), " ", "$" + averageConsumption)); if (voBean.getPerson() != 0) {
double number = voBean.getPrices() / voBean.getPerson();
averageConsumption = df.format(Double.isNaN(number) ? 0 : number);
}
settlementReportItem5s.add(new SectionTextItem5(headcountAndAverageConsumptionText, null, String.valueOf(voBean.getPerson()), null, "$" + averageConsumption));
/** 帳單統計*/ /** 帳單統計*/
settlementReportItem5s.add(new SectionTextItem5("==============================================================", "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5("==============================================================", null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5("", "", "帳單統計", "", "")); settlementReportItem5s.add(new SectionTextItem5(null, null, "帳單統計", null, null));
settlementReportItem5s.add(new SectionTextItem5("類別", "帳單", "金額", "平均", "金額%")); // settlementReportItem5s.add(new SectionTextItem5("類別", "帳單", "金額", "平均", "金額%"));
// settlementReportItem5s.add(new SectionTextItem5("--------------------------------------------------------------------------------", "", "", "", ""));
//總計 //總計
String averagePrice2 = df.format(voBean.getTotamount() / voBean.getNum()); //平均數
settlementReportItem5s.add(new SectionTextItem5(totalText, String.valueOf(voBean.getNum()), "$" + df.format(voBean.getTotamount()), "$" + averagePrice2, " ")); String averagePrice2 = "0.00";
if (voBean.getNum() != 0) {
double number = voBean.getTotamount() / voBean.getNum();
averagePrice2 = df.format(Double.isNaN(number) ? 0 : number);
}
//計算佔比
int percentage = 0;
if (voBean.getPrices() > 0) {
percentage = (int) (MoneyUtil.divide(voBean.getTotamount(), voBean.getPrices(), 2) * 100);
}
// settlementReportItem5s.add(new SectionTextItem5(totalText, String.valueOf(voBean.getNum()), "$" + df.format(voBean.getTotamount()), "$" + averagePrice2, percentage + "%"));
//new "外賣"
settlementReportItem5s.add(new SectionTextItem5("類別", null, null, null, totalText));
settlementReportItem5s.add(new SectionTextItem5("賬單", null, null, null, String.valueOf(voBean.getNum())));
settlementReportItem5s.add(new SectionTextItem5("金額", null, null, null, "$" + df.format(voBean.getTotamount())));
settlementReportItem5s.add(new SectionTextItem5("平均", null, null, null, "$" + averagePrice2));
settlementReportItem5s.add(new SectionTextItem5("金額%", null, null, null, percentage + "%"));
} }
List<SettlementReport.DataBean.AnalysisBean> analysisBeanList = datasBean.getAnalysis(); List<SettlementReport.DataBean.AnalysisBean> analysisBeanList = datasBean.getAnalysis();
...@@ -327,18 +349,18 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese ...@@ -327,18 +349,18 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese
Map<String, SettlementReport.DataBean.AnalysisBean> analysisBeanMap = getAnalysisBeanMap(analysisBeanList); Map<String, SettlementReport.DataBean.AnalysisBean> analysisBeanMap = getAnalysisBeanMap(analysisBeanList);
/**賬單現況*/ /**賬單現況*/
settlementReportItem5s.add(new SectionTextItem5("", "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5(null, null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5("==============================================================", "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5("==============================================================", null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5("", "", "賬單現況", "", "")); settlementReportItem5s.add(new SectionTextItem5(null, null, "賬單現況", null, null));
settlementReportItem5s.add(new SectionTextItem5("項目", "帳單", "人數", " ", "金額")); settlementReportItem5s.add(new SectionTextItem5("項目", "帳單", "人數", null, "金額"));
// settlementReportItem5s.add(new SectionTextItem5("--------------------------------------------------------------------------------", "", "", "", "")); // settlementReportItem5s.add(new SectionTextItem5("--------------------------------------------------------------------------------", null, null, null, null));
//未完成帳單 //未完成帳單
double item5Amount = 0.0; double item5Amount = 0.0;
int item5num = 0; int item5num = 0;
int item5PeopleNum = 0; int item5PeopleNum = 0;
if (analysisBeanMap.containsKey(outstandingBillText)) { if (analysisBeanMap.containsKey(outstandingBillText)) {
SettlementReport.DataBean.AnalysisBean analysisBean = analysisBeanMap.get(outstandingBillText); SettlementReport.DataBean.AnalysisBean analysisBean = analysisBeanMap.get(outstandingBillText);
settlementReportItem5s.add(new SectionTextItem5(analysisBean.getTypeName(), String.valueOf(analysisBean.getNum()), String.valueOf(analysisBean.getNum()), " ", "$" + df.format(analysisBean.getAmount()))); settlementReportItem5s.add(new SectionTextItem5(analysisBean.getTypeName(), String.valueOf(analysisBean.getNum()), String.valueOf(analysisBean.getNum()), null, "$" + df.format(analysisBean.getAmount())));
item5Amount += analysisBean.getAmount(); item5Amount += analysisBean.getAmount();
item5num += analysisBean.getNum(); item5num += analysisBean.getNum();
item5PeopleNum += analysisBean.getNum(); item5PeopleNum += analysisBean.getNum();
...@@ -346,52 +368,48 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese ...@@ -346,52 +368,48 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese
//已收款帳單 //已收款帳單
if (analysisBeanMap.containsKey(billsReceivedText)) { if (analysisBeanMap.containsKey(billsReceivedText)) {
SettlementReport.DataBean.AnalysisBean analysisBean = analysisBeanMap.get(billsReceivedText); SettlementReport.DataBean.AnalysisBean analysisBean = analysisBeanMap.get(billsReceivedText);
settlementReportItem5s.add(new SectionTextItem5(analysisBean.getTypeName(), String.valueOf(analysisBean.getNum()), String.valueOf(analysisBean.getNum()), " ", "$" + df.format(analysisBean.getAmount()))); settlementReportItem5s.add(new SectionTextItem5(analysisBean.getTypeName(), String.valueOf(analysisBean.getNum()), String.valueOf(analysisBean.getNum()), null, "$" + df.format(analysisBean.getAmount())));
item5Amount += analysisBean.getAmount(); item5Amount += analysisBean.getAmount();
item5num += analysisBean.getNum(); item5num += analysisBean.getNum();
item5PeopleNum += analysisBean.getNum(); item5PeopleNum += analysisBean.getNum();
} }
//總計 //總計
settlementReportItem5s.add(new SectionTextItem5(totalText, String.valueOf(item5PeopleNum), String.valueOf(item5num), " ", "$" + df.format(item5Amount))); settlementReportItem5s.add(new SectionTextItem5(totalText, String.valueOf(item5PeopleNum), String.valueOf(item5num), null, "$" + df.format(item5Amount)));
/**本月累計營業額*/ /**本月累計營業額*/
if (analysisBeanMap.containsKey(cumulativeTurnoverMonthText)) { if (analysisBeanMap.containsKey(cumulativeTurnoverMonthText)) {
SettlementReport.DataBean.AnalysisBean analysisBean = analysisBeanMap.get(cumulativeTurnoverMonthText); SettlementReport.DataBean.AnalysisBean analysisBean = analysisBeanMap.get(cumulativeTurnoverMonthText);
String firstDayOfMonth = TimeUtil.getFirstDayOfMonth(TimeUtil.dateFormatYMD) + "00:00:00"; String firstDayOfMonth = TimeUtil.getFirstDayOfMonth(TimeUtil.dateFormatYMD) + " 00:00:00";
String currentDate = TimeUtil.getCurrentDate(TimeUtil.dateFormatYMDHMS); String currentDate = TimeUtil.getCurrentDate(TimeUtil.dateFormatYMDHMS);
settlementReportItem5s.add(new SectionTextItem5("", "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5(null, null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5("==============================================================", "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5("==============================================================", null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5(cumulativeTurnoverMonthText, "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5(cumulativeTurnoverMonthText, null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5(byBusinessDateText + firstDayOfMonth, "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5(byBusinessDateText + firstDayOfMonth, null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5(toBusinessDateText + currentDate, "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5(toBusinessDateText + currentDate, null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5(netTurnoverText, " " + " ", " ", " ", "$" + df.format(analysisBean.getAmount()))); settlementReportItem5s.add(new SectionTextItem5(netTurnoverText, null, null, null, "$" + df.format(analysisBean.getAmount())));
} }
/**報表完結*/ /**報表完結*/
String memberName = GsaCloudApplication.getMemberName(this); String memberName = GsaCloudApplication.getMemberName(this);
String currentDate = TimeUtils.getCurrentDate(TimeUtils.dateFormatYMDHMS); String currentDate = TimeUtils.getCurrentDate(TimeUtils.dateFormatYMDHMS);
settlementReportItem5s.add(new SectionTextItem5("", "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5(null, null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5("==============================================================", "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5("==============================================================", null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5("報表完結", "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5("報表完結", null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5("讀取人員 " + memberName, "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5("讀取人員 " + memberName, null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5(currentDate + " v" + DeviceUtils.getVersionName(this), "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5(currentDate + " v" + DeviceUtils.getVersionName(this), null, null, null, null));
settlementReportItem5s.add(new SectionTextItem5("", "", "", "", "")); settlementReportItem5s.add(new SectionTextItem5(null, null, null, null, null));
} }
mPresenter.notifyReportItem5Adapter(settlementReportItem5s); mPresenter.notifyReportItem5Adapter(settlementReportItem5s);
scrollView.post(new Runnable() { scrollView.post(() -> scrollView.fullScroll(ScrollView.FOCUS_UP));
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_UP);
}
});
} }
@Override @Override
public void printRepore() { public void printRepore() {
View view = initPrintView();
//清機成功,打印 //清機成功,打印
PrintTransitUtils.getInstance().setPrintView(scrollView); PrintTransitUtils.getInstance().setPrintView(view);
CC.obtainBuilder("Component.Print") CC.obtainBuilder("Component.Print")
.addParam("type", 4)//清機打印 .addParam("type", 4)//清機打印
.setActionName("printActivity") .setActionName("printActivity")
...@@ -402,16 +420,35 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese ...@@ -402,16 +420,35 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese
if (mPresenter != null) { if (mPresenter != null) {
mPresenter.getSettlementReport(); mPresenter.getSettlementReport();
} }
// Log.e("error", "是否成功打印:" + result.isSuccess());
// if (result.isSuccess()) {
// //打印成功
// showMessage("打印成功!");
// } else {
// showMessage("打印失敗!");
// }
}); });
} }
@NotNull
private View initPrintView() {
View view = View.inflate(mContext, R.layout.layout_settlement_report, null);
TextView mTvLastTime = view.findViewById(R.id.tv_last_time);
TextView mTvBrandName = view.findViewById(R.id.tv_restaurant_name);
TextView mTvStoreName = view.findViewById(R.id.tv_business_area_title);
TextView mTvStartTime = view.findViewById(R.id.tv_start_time);
TextView mTvEndTime = view.findViewById(R.id.tv_end_time);
RecyclerView recyclerView = view.findViewById(R.id.rv_settlement_report_item2);
mTvBrandName.setText(tv_restaurant_name.getText());
mTvLastTime.setText(tv_last_time.getText());
mTvStoreName.setText(tv_business_area_title.getText());
mTvStartTime.setText(tv_start_time.getText());
mTvEndTime.setText(tv_end_time.getText());
int textSize = 24;
mTvLastTime.setTextSize(textSize);
mTvBrandName.setTextSize(textSize);
mTvStoreName.setTextSize(textSize);
mTvStartTime.setTextSize(textSize);
mTvEndTime.setTextSize(textSize);
recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
recyclerView.setAdapter(mPresenter.mPrintAdapter);
return view;
}
private Map<String, SettlementReport.DataBean.AnalysisBean> getAnalysisBeanMap(List<SettlementReport.DataBean.AnalysisBean> analysisBeanList) { private Map<String, SettlementReport.DataBean.AnalysisBean> getAnalysisBeanMap(List<SettlementReport.DataBean.AnalysisBean> analysisBeanList) {
Map<String, SettlementReport.DataBean.AnalysisBean> analysisBeanMap = new HashMap<>(); Map<String, SettlementReport.DataBean.AnalysisBean> analysisBeanMap = new HashMap<>();
for (int i = 0; i < analysisBeanList.size(); i++) { for (int i = 0; i < analysisBeanList.size(); i++) {
...@@ -428,8 +465,10 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese ...@@ -428,8 +465,10 @@ public class SettlementReportActivity extends BaseActivity<SettlementReportPrese
public void setSettlementReportItem5RecycleLayoutManager() { public void setSettlementReportItem5RecycleLayoutManager() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
if (rv_settlement_report_item2 != null) {
rv_settlement_report_item2.setLayoutManager(linearLayoutManager); rv_settlement_report_item2.setLayoutManager(linearLayoutManager);
rv_settlement_report_item2.setItemAnimator(new DefaultItemAnimator()); rv_settlement_report_item2.setItemAnimator(new DefaultItemAnimator());
} }
}
} }
...@@ -26,10 +26,17 @@ import butterknife.BindViews; ...@@ -26,10 +26,17 @@ import butterknife.BindViews;
public class SettlementReportItem5Adapter extends DefaultAdapter<SectionTextItem5> { public class SettlementReportItem5Adapter extends DefaultAdapter<SectionTextItem5> {
private Context mContext; private Context mContext;
private int textSize;
public SettlementReportItem5Adapter(Context context, List<SectionTextItem5> infos) { public SettlementReportItem5Adapter(Context context, List<SectionTextItem5> infos) {
super(infos); super(infos);
this.mContext = context; this.mContext = context;
textSize = 16;
}
public SettlementReportItem5Adapter(Context context, List<SectionTextItem5> infos, int textSize) {
super(infos);
this.mContext = context;
this.textSize = textSize;
} }
@Override @Override
...@@ -54,42 +61,45 @@ public class SettlementReportItem5Adapter extends DefaultAdapter<SectionTextItem ...@@ -54,42 +61,45 @@ public class SettlementReportItem5Adapter extends DefaultAdapter<SectionTextItem
public SettlementReportItemHolder(View itemView) { public SettlementReportItemHolder(View itemView) {
super(itemView); super(itemView);
for (int i = 0; i < tv_items.length; i++) {
tv_items[i].setTextSize(textSize);
}
} }
@Override @Override
public void setData(SectionTextItem5 reportItem, int position) { public void setData(SectionTextItem5 reportItem, int position) {
if(!TextUtils.isEmpty(reportItem.getItem1())){ if (!TextUtils.isEmpty(reportItem.getItem1())) {
tv_items[0].setText(reportItem.getItem1()); tv_items[0].setText(reportItem.getItem1());
tv_items[0].setVisibility(View.VISIBLE); tv_items[0].setVisibility(View.VISIBLE);
}else { } else {
tv_items[0].setVisibility(View.GONE); tv_items[0].setVisibility(View.GONE);
} }
if(!TextUtils.isEmpty(reportItem.getItem2())){ if (!TextUtils.isEmpty(reportItem.getItem2())) {
tv_items[1].setText(reportItem.getItem2()); tv_items[1].setText(reportItem.getItem2());
tv_items[1].setVisibility(View.VISIBLE); tv_items[1].setVisibility(View.VISIBLE);
}else { } else {
tv_items[1].setVisibility(View.GONE); tv_items[1].setVisibility(View.GONE);
} }
if(!TextUtils.isEmpty(reportItem.getItem3())){ if (!TextUtils.isEmpty(reportItem.getItem3())) {
tv_items[2].setText(reportItem.getItem3()); tv_items[2].setText(reportItem.getItem3());
tv_items[2].setVisibility(View.VISIBLE); tv_items[2].setVisibility(View.VISIBLE);
}else { } else {
tv_items[2].setVisibility(View.GONE); tv_items[2].setVisibility(View.GONE);
} }
if(!TextUtils.isEmpty(reportItem.getItem4())){ if (!TextUtils.isEmpty(reportItem.getItem4())) {
tv_items[3].setText(reportItem.getItem4()); tv_items[3].setText(reportItem.getItem4());
tv_items[3].setVisibility(View.VISIBLE); tv_items[3].setVisibility(View.VISIBLE);
}else { } else {
tv_items[3].setVisibility(View.GONE); tv_items[3].setVisibility(View.GONE);
} }
if(!TextUtils.isEmpty(reportItem.getItem5())){ if (!TextUtils.isEmpty(reportItem.getItem5())) {
tv_items[4].setText(reportItem.getItem5()); tv_items[4].setText(reportItem.getItem5());
tv_items[4].setVisibility(View.VISIBLE); tv_items[4].setVisibility(View.VISIBLE);
}else { } else {
tv_items[4].setVisibility(View.GONE); tv_items[4].setVisibility(View.GONE);
} }
} }
......
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<com.qmuiteam.qmui.widget.QMUIWindowInsetLayout xmlns:android="http://schemas.android.com/apk/res/android" <com.qmuiteam.qmui.widget.QMUIWindowInsetLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent"> android:layout_height="match_parent">
...@@ -9,94 +8,7 @@ ...@@ -9,94 +8,7 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="?attr/qmui_topbar_height" /> android:layout_height="?attr/qmui_topbar_height" />
<ScrollView <include layout="@layout/layout_settlement_report" />
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/qmui_topbar_height"
android:layout_marginBottom="@dimen/dp_45"
android:background="@color/theme_white_color"
android:descendantFocusability="beforeDescendants"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="@dimen/dp_10">
<TextView
android:id="@+id/tv_last_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingBottom="@dimen/dp_5"
android:text="上次清機時間:2020-3-1 21:59:18"
android:textColor="@color/red"
android:textSize="@dimen/dp_16" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_restaurant_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="店鋪名稱:gingersoft"
android:textColor="@color/black"
android:textSize="@dimen/dp_18" />
<TextView
android:id="@+id/tv_business_area_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="店鋪名稱:gingersoft"
android:textColor="@color/black"
android:textSize="@dimen/dp_18" />
<TextView
android:id="@+id/tv_start_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp_5"
android:text=""
android:textColor="@color/black"
android:textSize="@dimen/settlement_report_text_size" />
<TextView
android:id="@+id/tv_end_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp_5"
android:text=""
android:textColor="@color/black"
android:textSize="@dimen/settlement_report_text_size" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="@dimen/dp_0_5"
android:layout_marginTop="@dimen/dp_8"
android:background="@color/theme_grey_color" />
<!-- <com.gingersoft.gsa.cloud.base.widget.NoScrollRecyclerView-->
<!-- android:id="@+id/rv_settlement_report_item"-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:divider="@null"-->
<!-- android:fadeScrollbars="false" />-->
<com.gingersoft.gsa.cloud.base.widget.NoScrollRecyclerView
android:id="@+id/rv_settlement_report_item2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@null"
android:fadeScrollbars="false"
android:paddingTop="@dimen/dp_8" />
</LinearLayout>
</ScrollView>
<com.qmuiteam.qmui.alpha.QMUIAlphaButton <com.qmuiteam.qmui.alpha.QMUIAlphaButton
android:id="@+id/btn_send_settlement" android:id="@+id/btn_send_settlement"
......
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
android:id="@+id/tv_item2" android:id="@+id/tv_item2"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1" android:layout_weight="0.5"
android:gravity="center" android:gravity="center"
android:maxLines="1" android:maxLines="1"
android:text="item2" android:text="item2"
...@@ -42,7 +42,7 @@ ...@@ -42,7 +42,7 @@
android:id="@+id/tv_item4" android:id="@+id/tv_item4"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1" android:layout_weight="0.5"
android:gravity="center" android:gravity="center"
android:text="item4" android:text="item4"
android:maxLines="1" android:maxLines="1"
......
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/qmui_topbar_height"
android:layout_marginBottom="@dimen/dp_45"
android:background="@color/theme_white_color"
android:descendantFocusability="beforeDescendants"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="@dimen/dp_10">
<TextView
android:id="@+id/tv_last_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingBottom="@dimen/dp_5"
android:text="上次清機時間:2020-3-1 21:59:18"
android:textColor="@color/red"
android:textSize="@dimen/dp_16" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_restaurant_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="店鋪名稱:gingersoft"
android:textColor="@color/black"
android:textSize="@dimen/dp_18" />
<TextView
android:id="@+id/tv_business_area_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="店鋪名稱:gingersoft"
android:textColor="@color/black"
android:textSize="@dimen/dp_18" />
<TextView
android:id="@+id/tv_start_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp_5"
android:text=""
android:textColor="@color/black"
android:textSize="@dimen/settlement_report_text_size" />
<TextView
android:id="@+id/tv_end_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp_5"
android:text=""
android:textColor="@color/black"
android:textSize="@dimen/settlement_report_text_size" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="@dimen/dp_0_5"
android:layout_marginTop="@dimen/dp_8"
android:background="@color/theme_grey_color" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_settlement_report_item2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@null"
android:fadeScrollbars="false"
android:paddingTop="@dimen/dp_8" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
...@@ -344,6 +344,11 @@ public class PrintUtils { ...@@ -344,6 +344,11 @@ public class PrintUtils {
return viewToBitmap(context, view); return viewToBitmap(context, view);
} }
/**
* 獲取清機報表Bitmap
* @param mContext
* @return
*/
private static Bitmap getReportBitmap(Context mContext) { private static Bitmap getReportBitmap(Context mContext) {
View view = PrintTransitUtils.getInstance().getPrintView(); View view = PrintTransitUtils.getInstance().getPrintView();
if (view != null) { if (view != null) {
...@@ -356,6 +361,6 @@ public class PrintUtils { ...@@ -356,6 +361,6 @@ public class PrintUtils {
public static Bitmap viewToBitmap(Context context, View view) { public static Bitmap viewToBitmap(Context context, View view) {
LayoutToBitmapUtils.layoutView(context, view);//先测量view LayoutToBitmapUtils.layoutView(context, view);//先测量view
//580為程序支持的打印紙最大寬度 //580為程序支持的打印紙最大寬度
return ImageUtils.zoomDrawable(LayoutToBitmapUtils.loadBitmapFromView(view), paperWidth);//将view轉bitmap return ImageUtils.zoomDrawable(LayoutToBitmapUtils.loadBitmapFromView(view, paperWidth), paperWidth);//将view轉bitmap
} }
} }
/*
* Copyright (C) 2015 AlexMofer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gingersoft.gsa.cloud.print;
/**
* ESC-POS Commands
* Created by Alex on 2017/11/1.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class PrintCommands {
private static final byte DLE = 16;
private static final byte ESC = 27;
private static final byte FS = 28;
private static final byte GS = 29;
/**
* Moves the print position to the next tab position.
* HT
*
* @return command
*/
public static byte[] horizontalTab() {
return new byte[]{9};
}
/**
* Prints the data in the print buffer and feeds one line based on the current line spacing.
* LF
*
* @return command
*/
public static byte[] printLineFeed() {
return new byte[]{10};
}
/**
* When automatic line feed is enabled, this command functions the same as LF;
* when automatic line feed is disabled, this command is ignored.
* CR
*
* @return command
*/
public static byte[] printCarriageReturn() {
return new byte[]{13};
}
/**
* Prints the data in the print buffer and returns to standard mode.
* FF
*
* @return command
*/
public static byte[] printReturnStandardMode() {
return new byte[]{12};
}
/**
* In page mode, delete all the print data in the current printable area.
* CAN
*
* @return command
*/
public static byte[] cancelPrintData() {
return new byte[]{24};
}
/**
* Transmits the selected printer status specified by n in real-time,
* according to the following parameters:
* n=1 : Transmit printer status
* n=2 : Transmit off-line status
* n=3 : Transmit error status
* n=4 : Transmit paper roll sensor status
* DLE EOT n
*
* @param n 1≤n≤4
* @return command
*/
public static byte[] realTimeStatusTransmission(int n) {
return new byte[]{DLE, 4, (byte) n};
}
/**
* Responds to a request from the host computer.
* n specifies the requests as follows:
* n=1 : Recover from an error and restart printing from the line where the error occurred
* n=2 : Recover from an error aft clearing the receive and print buffers
* DLE ENQ n
*
* @param n 1≤n≤2
* @return command
*/
public static byte[] realTimeRequestToPrinter(int n) {
return new byte[]{DLE, 5, (byte) n};
}
/**
* Outputs the pulse specified by t to connector pin m as follows:
* m=0 : Drawer kick-out connector pin 2.
* m=1 : Drawer kick-out connector pin 5.
* The pulse ON time is [ t x 100 ms] and the OFF time is [ t x 100 ms].
* DLE DC4 n m t
*
* @param n n=1
* @param m m=0,1
* @param t 1≤t≤8
* @return command
*/
public static byte[] generatePulseAtRealTime(int n, int m, int t) {
return new byte[]{DLE, 20, (byte) n, (byte) m, (byte) t};
}
/**
* In page mode, prints all buffered data in the printable area collectively.
* ESC FF
*
* @return command
*/
public static byte[] printData() {
return new byte[]{ESC, 12};
}
/**
* Sets the character spacing for the right side of the character to
* [n x horizontal or vertical motion units].
* ESC SP n
*
* @param n 0≤n≤255 default 0
* @return command
*/
public static byte[] setRightSideCharacterSpacing(int n) {
return new byte[]{ESC, 32, (byte) n};
}
/**
* Selects print mode(s) using n as follows:
* n=0 : Character font A (12x24)
* Emphasized mode not selected.
* Double-height mode not selected.
* Double-width mode not selected.
* Underline mode not selected.
* n=1 : Character font B (9x24)
* n=8 : Emphasized mode selected.
* n=16 : Double-height mode selected.
* n=32 : Double-width mode selected.
* n=128 : Underline mode selected.
* ESC ! n
*
* @param n 0≤n≤255 default 0
* @return command
*/
public static byte[] selectPrintMode(int n) {
return new byte[]{ESC, 33, (byte) n};
}
/**
* Sets the distance from the beginning of the line to the position at which subsequent
* characters are to be printed.
* The distance from the beginning of the line to the print position is
* [(nL + nH x 256) x (vertical or horizontal motion unit)] inches.
* ESC $ nL nH
*
* @param nL 0≤nL≤255
* @param nH 0≤nH≤255
* @return command
*/
public static byte[] setAbsolutePrintPosition(int nL, int nH) {
return new byte[]{ESC, 36, (byte) nL, (byte) nH};
}
/**
* Cancels the user-defined character set.
* ESC % n
*
* @return command
*/
public static byte[] cancelUserDefinedCharacterSet() {
return new byte[]{ESC, 37, 0};
}
/**
* Selects the user-defined character set.
* ESC % n
*
* @return command
*/
public static byte[] selectUserDefinedCharacterSet() {
return new byte[]{ESC, 37, 1};
}
/**
* Defines user-defined characters
* y specifies the number of bytes in the vertical direction, it always 3.
* c1 specifies the beginning character code for the definition, and c2 specifies the final code.
* X specifies the number of dots in the horizontal direction.
* ESC & y c1 c2 [x1 d1…d(y x x1)]..[ xk d1..d(y x xk)]
*
* @param c1 32≤c1≤c2≤126
* @param c2 32≤c1≤c2≤126
* @param dots 0 ≤ x ≤ 12 Font A (when font A (12 x 24) is selected)
* 0 ≤ x ≤ 9 Font B (when font B (9 x 17) is selected)
* 0 ≤ d1 ... d(y x xk) ≤ 255
* @return command
*/
public static byte[] defineUserDefinedCharacters(int c1, int c2, byte[] dots) {
byte[] part = new byte[]{ESC, 38, 3, (byte) c1, (byte) c2};
byte[] destination = new byte[part.length + dots.length];
System.arraycopy(part, 0, destination, 0, part.length);
System.arraycopy(dots, 0, destination, part.length, dots.length);
return destination;
}
/**
* Selects a bit-image mode using m for the number of dots specified by nL and nH, as follows:
* m=0
* Mode:8-dot single-density
* Vertical NO. of Dots:8
* Vertical Dot Density: 60 DPI
* Horizontal Dot Density: 90 DPI
* Number of (Data(K)):nL + nH x 256
* m=1
* Mode:8-dot double-density
* Vertical NO. of Dots:8
* Vertical Dot Density: 60 DPI
* Horizontal Dot Density: 180 DPI
* Number of (Data(K)):nL + nH x 256
* m=32
* Mode:24-dot single-density
* Vertical NO. of Dots:24
* Vertical Dot Density: 180 DPI
* Horizontal Dot Density: 90 DPI
* Number of (Data(K)):(nL + nH x 256) x 3
* m=33
* Mode:24-dot single-density
* Vertical NO. of Dots:24
* Vertical Dot Density: 180 DPI
* Horizontal Dot Density: 180 DPI
* Number of (Data(K)):(nL + nH x 256) x 3
* ESC * m nL nH [d1...dk]
*
* @param m m = 0, 1, 32, 33
* @param nL 0≤nL ≤255
* @param nH 0≤nH ≤3
* @param image 0≤d≤255
* @return command
*/
public static byte[] selectBitImageMode(int m, int nL, int nH, byte[] image) {
byte[] part = new byte[]{ESC, 42, (byte) m, (byte) nL, (byte) nH};
byte[] destination = new byte[part.length + image.length];
System.arraycopy(part, 0, destination, 0, part.length);
System.arraycopy(image, 0, destination, part.length, image.length);
return destination;
}
/**
* Turns underline mode off
* ESC - n
*
* @return command
*/
public static byte[] turnUnderlineModeOff() {
return new byte[]{ESC, 45, 0};
}
/**
* Turns underline mode on or off, based on the following values of n.
* n=0, 48 : Turns off underline mode
* n=1, 49 : Turns on underline mode (1-dot thick)
* n=2, 50 : Turns on underline mode (2-dots thick)
* ESC - n
*
* @param n 0≤n ≤2, 48≤n ≤50
* @return command
*/
public static byte[] turnUnderlineMode(int n) {
return new byte[]{ESC, 45, 1};
}
/**
* Selects approximately 4.23 mm {1/6"} spacing.
* ESC 2
*
* @return command
*/
public static byte[] selectDefaultLineSpacing() {
return new byte[]{ESC, 50};
}
/**
* Sets the line spacing to [n x (vertical or horizontal motion unit)] inches.
* ESC 3 n
*
* @param n 0≤n≤255
* @return command
*/
public static byte[] setLineSpacing(int n) {
return new byte[]{ESC, 51, (byte) n};
}
/**
* Selects device to which host computer sends data, using n as follows:
* n=0 : Printer disabled
* n=1 : Printer enabled
* ESC = n
*
* @param n 1≤n≤255 default 1
* @return command
*/
public static byte[] setPeripheralDevice(int n) {
return new byte[]{ESC, 61, (byte) n};
}
/**
* Cancels user-defined characters.
* ESC ? n
*
* @param n 32 ≤n ≤126
* @return command
*/
public static byte[] cancelUserDefinedCharacters(int n) {
return new byte[]{ESC, 63, (byte) n};
}
/**
* Clears the data in the print buffer and resets the printer mode to the mode
* that was in effect when the power was turned on.
* ESC @
*
* @return command
*/
public static byte[] initializePrinter() {
return new byte[]{ESC, 64};
}
/**
* Set is horizontal tab positions.
* n specifies the column number for setting a horizontal tab position from the beginning of the line.
* k indicates the total number of horizontal tab positions to be set.
* ESC D [n1...nk] NUL
*
* @param nk 1≤n ≤255
* 0≤k ≤32
* @return command
*/
public static byte[] setHorizontalTabPositions(byte[] nk) {
byte[] part = new byte[]{ESC, 68};
byte[] destination = new byte[part.length + nk.length + 1];
System.arraycopy(part, 0, destination, 0, part.length);
System.arraycopy(nk, 0, destination, part.length, nk.length);
destination[part.length + nk.length] = 0;
return destination;
}
/**
* Turns emphasized mode off.
* ESC E n
*
* @return command
*/
public static byte[] turnOffEmphasizedMode() {
return new byte[]{ESC, 69, 0};
}
/**
* Turns emphasized mode on.
* ESC E n
*
* @return command
*/
public static byte[] turnOnEmphasizedMode() {
return new byte[]{ESC, 69, 1};
}
/**
* Turns double-strike mode on or off.
* When the LSB of n is 0, double-strike mode is turned off.
* When the LSB of n is1, double-strike mode is turned on.
* ESC G n
*
* @param n 0≤n≤255 default 0
* @return command
*/
public static byte[] turnDoubleStrikeMode(int n) {
return new byte[]{ESC, 71, (byte) n};
}
/**
* Prints the data in the print buffer and feeds the paper [n x vertical or horizontal motion unit].
* ESC J n
*
* @param n 0≤n ≤255
* @return command
*/
public static byte[] printFeedPaper(int n) {
return new byte[]{ESC, 74, (byte) n};
}
/**
* Switches from standard mode to page mode.
* ESC L
*
* @return command
*/
public static byte[] selectPageMode() {
return new byte[]{ESC, 76};
}
/**
* Selects character fonts
* n=0, 48 : Character font A (12 X 24 ) Selected
* n=1, 49 : Character font B (9 X 24 ) Selected
* ESC M n
*
* @param n n= 0, 1 , 48, 49
* @return command
*/
public static byte[] selectCharacterFont(int n) {
return new byte[]{ESC, 77, (byte) n};
}
/**
* Selects an international character set n from the following:
* n=0 : U. S. A
* n=1 : France
* n=2 : Germany
* n=3 : U. K.
* n=4 : Denmark I
* n=5 : Sweden
* n=6 : Italy
* n=7 : Spain I
* n=8 : Japan
* n=9 : Norway
* n=10 : Denmark II
* n=11 : Spain II
* n=12 : Latin America
*
* @param n 0≤n≤13 default 0
* @return command
*/
public static byte[] selectAnInternationalCharacterSet(int n) {
return new byte[]{ESC, 82, (byte) n};
}
/**
* Switches from page mode to standard mode.
* ESC S
*
* @return command
*/
public static byte[] selectStandardMode() {
return new byte[]{ESC, 83};
}
/**
* Select the print direction and starting position in page mode.
* n specifies the print direction and starting position as follows:
* n=0, 48 : Left to right(Print Direction) Upper left(Starting Position)
* n=1, 49 : Bottom to top(Print Direction) Lower left(Starting Position)
* n=2, 50 : Right to left(Print Direction) Lower right(Starting Position)
* n=3, 51 : Top to bottom(Print Direction) Upper right(Starting Position)
* ESC T n
*
* @param n 0≤n ≤3,
* 48≤n ≤51
* @return command
*/
public static byte[] selectPrintDirectionInPageMode(int n) {
return new byte[]{ESC, 84, (byte) n};
}
/**
* Turns 90˚ clockwise rotation mode on or off.
* n is used as follows:
* n=0, 48 : Turns off 90˚ clockwise rotation mode
* n=1, 49 : Turns on 90˚ clockwise rotation mode
* ESC V n
*
* @param n 0≤n≤1,48≤n≤49 default 0
* @return command
*/
public static byte[] turn90ClockwiseRotationMode(int n) {
return new byte[]{ESC, 86, (byte) n};
}
/**
* The horizontal starting position, vertical starting position, printing area
* width, and printing area height are defined as x0, y0, dx, dy,
* respectively.
* Each setting for the printable area is calculated as follow:
* x0 = [(xL + xH x 256) x (horizontal motion unit)]
* y0 = [(yL + yH x 256) x (vertical motion unit)]
* dx = [(dxL + dxH x 256) x (horizontal motion unit)]
* dy = [(dyL + dyH x 256) x (vertical motion unit)]
* ESC W xL xH yL yH dxL dxH dyL dyH
*
* @param xL 0≤ xL xH yL yH dxL dxH dyL dyH ≤255 (except dxL=dxH=0 or dyL=dyH=0)
* @param xH 0≤ xL xH yL yH dxL dxH dyL dyH ≤255 (except dxL=dxH=0 or dyL=dyH=0)
* @param yL 0≤ xL xH yL yH dxL dxH dyL dyH ≤255 (except dxL=dxH=0 or dyL=dyH=0)
* @param yH 0≤ xL xH yL yH dxL dxH dyL dyH ≤255 (except dxL=dxH=0 or dyL=dyH=0)
* @param dxL 0≤ xL xH yL yH dxL dxH dyL dyH ≤255 (except dxL=dxH=0 or dyL=dyH=0)
* @param dxH 0≤ xL xH yL yH dxL dxH dyL dyH ≤255 (except dxL=dxH=0 or dyL=dyH=0)
* @param dyL 0≤ xL xH yL yH dxL dxH dyL dyH ≤255 (except dxL=dxH=0 or dyL=dyH=0)
* @param dyH 0≤ xL xH yL yH dxL dxH dyL dyH ≤255 (except dxL=dxH=0 or dyL=dyH=0)
* default xL = xH = yL = yH = 0, dxL = 0, dxH = 2, dyL =126, dyH = 6
* @return command
*/
public static byte[] setPrintingAreaInPageMode(int xL, int xH, int yL, int yH,
int dxL, int dxH, int dyL, int dyH) {
return new byte[]{ESC, 87, (byte) xL, (byte) xH, (byte) yL, (byte) yH,
(byte) dxL, (byte) dxH, (byte) dyL, (byte) dyH};
}
/**
* Sets the print starting position based on the current position by using the horizontal or vertical motion unit.
* This command sets the distance from the current position to [(nL+ nH x 256) x (horizontal or vertical unit)].
* ESC \ nL nH
*
* @param nL 0≤nL≤255
* @param nH 0≤nH≤255
* @return command
*/
public static byte[] setRelativePrintPosition(int nL, int nH) {
return new byte[]{ESC, 92, (byte) nL, (byte) nH};
}
/**
* Aligns all the data in one line to the specified position
* n selects the justification as follows:
* n=0,48 : Left justification
* n=1,49 : Centering
* n=2,50 : Right justification
* ESC a n
*
* @param n 0≤n≤2,48≤n≤50 default 0
* @return command
*/
public static byte[] selectJustification(int n) {
return new byte[]{ESC, 97, (byte) n};
}
/**
* Selects the paper sensor(s) to output paper end signals.
* Each bit of n is used as follows:
* n=0 : Paper roll near-end sensor disabled / Paper roll end sensor disabled
* n=1,2 : Paper roll near-end sensor enabled
* n=4,8 : Paper roll end sensor enabled
* ESC c 3 n
*
* @param n 0≤n≤255 default 15
* @return command
*/
public static byte[] selectPaperSensorToOutputPaperEndSignals(int n) {
return new byte[]{ESC, 99, 51, (byte) n};
}
/**
* Selects the paper sensor(s) used to stop printing when a paper-end is detected.
* using n as follows:
* n=0 : Paper roll near end sensor disabled
* n=1,2 : Paper roll near end sensor enabled
* ESC c 4 n
*
* @param n 0≤n≤255 default 0
* @return command
*/
public static byte[] selectPaperSensorToStopPrinting(int n) {
return new byte[]{ESC, 99, 52, (byte) n};
}
/**
* Disables the panel buttons.
* ESC c 5 n
*
* @return command
*/
public static byte[] disablePanelButtons() {
return new byte[]{ESC, 99, 53, 0};
}
/**
* Enables the panel buttons.
* ESC c 5 n
*
* @return command
*/
public static byte[] enablePanelButtons() {
return new byte[]{ESC, 99, 53, 1};
}
/**
* Prints the data in the print buffer and feeds n lines.
* ESC d n
*
* @param n 0≤n ≤255
* @return command
*/
public static byte[] printFeedNLines(int n) {
return new byte[]{ESC, 100, (byte) n};
}
/**
* When this command is received, paper is cut (only when the auto cutter is loaded).
* ESC i
*
* @return command
*/
public static byte[] executePaperFullCut() {
return new byte[]{ESC, 105};
}
/**
* When this command is received, paper is cut (only when the auto cutter is loaded).
* ESC m
*
* @return command
*/
public static byte[] executePaperPartialCut() {
return new byte[]{ESC, 109};
}
/**
* Outputs the pulse specified by t1 and t2 to connector pin m as follows:
* m=0,48 : Drawer kick-out connector pin2.
* m=1,49 : Drawer kick-out connector pin5.
* ESC p m t1 t2
*
* @param m m = 0, 1, 48, 49
* @param t1 0≤t1≤255
* @param t2 0≤t2≤255
* @return command
*/
public static byte[] generatePulse(int m, int t1, int t2) {
return new byte[]{ESC, 112, (byte) m, (byte) t1, (byte) t2};
}
/**
* Selects a page n from the character code table.
* n=0 : PC437 [U.S.A., Standard Europe]
* n=1 : Katakana
* n=2 : PC850 [Multilingual]
* n=3 : PC860 [Portuguese]
* n=4 : PC863 [Canadian-French]
* n=5 : PC865 [Nordic]
* n=17 : PC866 [Cyrillic #2]
* n=255 : Space page
* ESC t n
*
* @param n 0≤n≤5, 16≤n≤26, n=255 default 0
* @return command
*/
public static byte[] selectCharacterCodeTable(int n) {
return new byte[]{ESC, 116, (byte) n};
}
/**
* Turns upside-down printing mode off.
* ESC { n
*
* @return command
*/
public static byte[] turnsOffUpsideDownPrintingMode() {
return new byte[]{ESC, 123, 0};
}
/**
* Turns upside-down printing mode on.
* ESC { n
*
* @return command
*/
public static byte[] turnsOnUpsideDownPrintingMode() {
return new byte[]{ESC, 123, 1};
}
/**
* Prints a NV bit image n using the mode specified by m.
* m=0,48 : Normal Mode Vertical=180dpi Horizontal=180dpi
* m=1,49 : Double-width Mode Vertical=180dpi Horizontal=90dpi
* m=2,50 : Double-height Mode Vertical=90dpi Horizontal=180dpi
* m=3,51 : Quadruple Mode Vertical=90dpi Horizontal=90dpi
* FS p n m
*
* @param n 1≤n≤255
* @param m 0≤m≤3, 48≤m≤51
* @return command
*/
public static byte[] printNVBitImage(int n, int m) {
return new byte[]{FS, 112, (byte) n, (byte) m};
}
/**
* Define the NV bit image specified by n.
* FS q n [xL xH yL yH d1...dk] 1...[xL xH yL yH d1...dk]n
*
* @param n 1≤n≤255
* @param image 0≤xL≤255
* 0≤xH≤3 (when 1≤(xL + xH x 256)≤1023)
* 0≤yL≤255
* 0≤yL≤1 (when 1≤(yL + yH x 256)≤288)
* 0≤d≤255
* k = (xL + xH x 256) x (yL + yH x 256) x 8
* Total defined data area = 2M bits (256K bytes)
* @return command
*/
public static byte[] defineNVBitImage(int n, byte[] image) {
byte[] part = new byte[]{FS, 113, (byte) n};
byte[] destination = new byte[part.length + image.length];
System.arraycopy(part, 0, destination, 0, part.length);
System.arraycopy(image, 0, destination, part.length, image.length);
return destination;
}
/**
* Selects the character height using bits 0 to 3 and selects the character width using bits
* 4 to 7, as follows:
* 0-3bit:
* n=0 : height = 1(normal)
* n=1 : height = 2(double-height)
* n=2 : height = 3
* n=3 : height = 4
* n=4 : height = 5
* n=5 : height = 6
* n=6 : height = 7
* n=7 : height = 8
* 4-7bit:
* n=0 : height = 1(normal)
* n=1 : height = 2(double-width)
* n=2 : height = 3
* n=3 : height = 4
* n=4 : height = 5
* n=5 : height = 6
* n=6 : height = 7
* n=7 : height = 8
* GS ! n
*
* @param n 0≤n≤255(1≤vertical number of times≤8, 1≤horizontal number of times≤8) default 0
* @return command
*/
public static byte[] selectCharacterSize(int n) {
return new byte[]{GS, 33, (byte) n};
}
/**
* Sets the absolute vertical print starting position for buffer character data in page mode.
* This command sets the absolute print position to [ (nL + nH x 256) x (vertical or horizontal
* motion unit)] inches.
* If the [ (nL + nH x 256) x (vertical or horizontal motion unit)] exceeds the specified
* printing area, this command is ignored.
* The horizontal starting buffer position does not move.
* The reference starting position is that specified by ESC T.
* This command operates as follows, depending on the starting position of the printing area
* specified by ESC T:
* 1. When the starting position is set to the upper left or lower right, this command sets the
* absolute position in the vertical direction.
* 2. When the starting position is set to the upper right or lower left, this command sets the
* absolute position in the horizontal direction.
* The horizontal and vertical motion units are specified by GS P.
* The GS P command can change the horizontal and vertical motion unit.
* However, the value cannot be less than the minimum horizontal movement amount, and it must be
* in even units of the minimum horizontal movement amount.
* GS $ nL nH
*
* @param nL 0≤nL≤255
* @param nH 0≤nH≤255
* @return command
*/
public static byte[] setAbsoluteVerticalPrintPositionInPageMade(int nL, int nH) {
return new byte[]{GS, 36, (byte) nL, (byte) nH};
}
/**
* Defines a downloaded bit image with the number of dots specified by x and y.
* x indicates the number of dots in the horizontal direction.
* y indicates he number of dots in the vertical direction.
* GS * x y d1...d (x x y x 8)
*
* @param x 1≤n≤255
* @param y 1≤n≤255
* @param image x x y≤1536
* 0≤d≤255
* @return command
*/
public static byte[] defineDownloadedBitImage(int x, int y, byte[] image) {
byte[] part = new byte[]{GS, 42, (byte) x, (byte) y};
byte[] destination = new byte[part.length + image.length];
System.arraycopy(part, 0, destination, 0, part.length);
System.arraycopy(image, 0, destination, part.length, image.length);
return destination;
}
/**
* Prints a downloaded bit image using the mode specified by m.
* m selects a mode from the table below:
* m=0,48 : Normal Mode Vertical=180dpi Horizontal=180dpi
* m=1,49 : Double-width Mode Vertical=180dpi Horizontal=90dpi
* m=2,50 : Double-height Mode Vertical=90dpi Horizontal=180dpi
* m=3,51 : Quadruple Mode Vertical=90dpi Horizontal=90dpi
* GS / m
*
* @param m 0≤m≤3, 48≤m≤51
* @return command
*/
public static byte[] printDownloadedBitImage(int m) {
return new byte[]{GS, 47, (byte) m};
}
/**
* Starts or ends macro definition.
* GS :
*
* @return command
*/
public static byte[] startOrEndMacroDefinition() {
return new byte[]{GS, 58};
}
/**
* Turns off white/black reverse printing mode.
* GS B n
*
* @return command
*/
public static byte[] turnOffWhiteBlackReversePrintingMode() {
return new byte[]{GS, 66, 0};
}
/**
* Turns on white/black reverse printing mode.
* GS B n
*
* @return command
*/
public static byte[] turnOnWhiteBlackReversePrintingMode() {
return new byte[]{GS, 66, 1};
}
/**
* Selects the printing position of HRI characters when printing a bar code.
* n selects the printing position as follows:
* m=0,48 : Not printed
* m=1,49 : Above the bar code
* m=2,50 : Below the bar code
* m=3,51 : Both above and below the bar code
* GS H n
*
* @param n 0≤m≤3, 48≤m≤51 default 0
* @return command
*/
public static byte[] selectPrintingPositionOfHRICharacters(int n) {
return new byte[]{GS, 72, (byte) n};
}
/**
* Sets the left margin using nL and nH.
* The left margin is set to [(nL + nH x 256) x (horizontal motion unit)] inches.
* GS L nL nH
*
* @param nL 0≤nL≤255 default 0
* @param nH 0≤nH≤255 default 0
* @return command
*/
public static byte[] setLeftMargin(int nL, int nH) {
return new byte[]{GS, 76, (byte) nL, (byte) nH};
}
/**
* Sets the horizontal and vertical motion units to 1/x inch and 1/y inch, respectively.
* When x and u are set to 0, the default setting of each value is used. (x = 180, y = 360)
* GS P x y
*
* @param x 0≤x≤255 default 180
* @param y 0≤y≤255 default 360
* @return command
*/
public static byte[] setHorizontalAndVerticalMotionUnits(int x, int y) {
return new byte[]{GS, 80, (byte) x, (byte) y};
}
/**
* Selects a mode for cutting paper and executes paper cutting. The value of m selects the mode
* as follows:
* m=1,49 : Partial cut(one point center uncut)
* m=66 : Feeds paper(cutting position + [n x(vertical motion unit)]) ,
* and cuts the paper partially(one point center uncut)
* GS V m
* GS V m n
*
* @param m m=1,49,66
* @param n 0≤n≤255
* @return command
*/
public static byte[] selectCutModeAndCutPaper(int m, int n) {
if (m == 66) {
return new byte[]{GS, 86, 66, (byte) n};
} else {
return new byte[]{GS, 86, (byte) m};
}
}
/**
* Sets the printing area width to the area specified by nL and nH.
* The printing area width is set to [( nL + nH x 256) x horizontal motion
* unit]].
* GS W nL nH
*
* @param nL 0≤nL≤255 default 0
* @param nH 0≤nH≤255 default 2
* @return command
*/
public static byte[] setPrintingAreaWidth(int nL, int nH) {
return new byte[]{GS, 87, (byte) nL, (byte) nH};
}
/**
* Sets the relative vertical print starting position from the current position in page mode.
* This command sets the distance from the current position to [( nL + nH x 256) vertical or
* horizontal motion unit] inches.
* GS \ nL nH
*
* @param nL 0≤nL≤255
* @param nH 0≤nH≤255
* @return command
*/
public static byte[] setRelativeVerticalPrintPositionInPageMode(int nL, int nH) {
return new byte[]{GS, 92, (byte) nL, (byte) nH};
}
/**
* Executes a macro.
* r specifies the number of times to execute the macro.
* t specifies the waiting time for executing the macro.
* m specifies macro executing mode.
* When the LSB of m = 0:
* The macro executes r times continuously at the interval specified by t.
* When the LSB of m = 1:
* After waiting for the period specified by t, the PAPER OUT LED indicators blink and the
* printer waits for the FEED button to be pressed. After the button is pressed, the printer
* executes the macro once. The printer repeats the operation r times.
* GS ^ r t m
*
* @param r 0≤r≤255
* @param t 0≤t≤255
* @param m m=0,1
* @return command
*/
public static byte[] executeMacro(int r, int t, int m) {
return new byte[]{GS, 94, (byte) r, (byte) t, (byte) m};
}
/**
* Enables or disables ASB and specifies the status items to include, using n as follows:
* bit=0,n=0 : Drawer kick-out connector pin 3 status disabled.
* bit=0,n=1 : Drawer kick-out connector pin 3 status enabled.
* bit=1,n=0 : On-line/off-line status disabled.
* bit=1,n=2 : On-line/off-line status enabled,
* bit=2,n=0 : Error status disabled.
* bit=2,n=4 : Error status enabled.
* bit=3,n=0 : Paper roll sensor status disabled.
* bit=3,n=8 : Paper roll sensor status enabled.
* GS a n
*
* @param n 0≤n≤255 default 0
* @return command
*/
public static byte[] setAutomaticStatusBack(int n) {
return new byte[]{GS, 97, (byte) n};
}
/**
* selects a font for the HRI characters used when printing a bar code.
* n selects the font from the following table:
* n=0,48 : Font A (12 x 24)
* n=1,49 : Font B (9 x 24)
* GS f n
*
* @param n n = 0, 1, 48, 49
* @return command
*/
public static byte[] selectFontForHumanReadableInterpretationCharacters(int n) {
return new byte[]{GS, 102, (byte) n};
}
/**
* Select the height of the bar code.
* n specifies the number of dots in the vertical direction.
* GS h n
*
* @param n 1≤n≤255 default 162
* @return command
*/
public static byte[] selectBarCodeHeight(int n) {
return new byte[]{GS, 104, (byte) n};
}
/**
* Selects a bar code system and prints the bar code.
* m selects a bar code system as follows:
* m=0 : UPC–A 11≤k≤12 48≤d≤57
* m=1 : UPC–E 11≤k≤12 48≤d≤57
* m=2 : EAN13 12≤k≤13 48≤d≤57
* m=3 : EAN8 7≤k≤8 48≤d≤57
* m=4 : CODE39 1≤k 48≤d≤57,65≤d≤90,32,36,37,43,45,46,47
* m=5 : ITF 1≤k(even number) 48≤d≤57
* m=6 : CODABAR 1≤k 48≤d≤57,65≤d≤68,36,43,45,46,47,58
* m=65 : UPC–A 11≤k≤12 48≤d≤57
* m=66 : UPC–E 11≤k≤12 48≤d≤57
* m=67 : EAN13 12≤k≤13 48≤d≤57
* m=68 : EAN8 7≤k≤8 48≤d≤57
* m=69 : CODE39 1≤k≤255 48≤d≤57,65≤d≤90,32,36,37,43,45,46,47
* m=70 : ITF 1≤k≤255(even number) 48≤d≤57
* m=71 : CODABAR 1≤k≤255 48≤d≤57,65≤d≤68,36,43,45,46,47,58
* m=72 : CODE93 1≤k≤255 0≤d≤127
* m=73 : CODE128 2≤k≤255 0≤d≤127
* GS k m d1…dk NUL
* GS k m n d1…dn
*
* @param m 0≤m≤6
* 65≤m≤73
* @param n n and d depends on the code system used
* @param data k and d depends on the code system used
* @return command
*/
public static byte[] printBarCode(int m, int n, byte[] data) {
if (m <= 6) {
byte[] part = new byte[]{GS, 107, (byte) m};
byte[] destination = new byte[part.length + data.length + 1];
System.arraycopy(part, 0, destination, 0, part.length);
System.arraycopy(data, 0, destination, part.length, data.length);
destination[part.length + data.length] = 0;
return destination;
} else {
byte[] part = new byte[]{GS, 107, (byte) m, (byte) n};
byte[] destination = new byte[part.length + data.length];
System.arraycopy(part, 0, destination, 0, part.length);
System.arraycopy(data, 0, destination, part.length, data.length);
return destination;
}
}
/**
* Transmits the status specified by n as follows:
* n=1,49 : Transmits paper sensor status
* n=2,50 : Transmits drawer kick-out connector status
* GS r n
*
* @param n n=1, 2, 49, 50
* @return command
*/
public static byte[] transmitStatus(int n) {
return new byte[]{GS, 114, (byte) n};
}
/**
* Selects Raster bit-image mode.
* The value of m selects the mode, as follows:
* m=0,48 : Normal Mode Vertical=180dpi Horizontal=180dpi
* m=1,49 : Double-width Mode Vertical=180dpi Horizontal=90dpi
* m=2,50 : Double-height Mode Vertical=90dpi Horizontal=180dpi
* m=3,51 : Quadruple Mode Vertical=90dpi Horizontal=90dpi
* xL, xH, select the number of data bytes (xL+xHx256) in the horizontal direction for the bit
* image.
* yL, yH, select the number of data bytes (xL+xHx256) in the vertical direction for the bit
* image.
* GS v 0 m xL xH yL yH d1....dk
*
* @param m 0≤m≤3, 48≤m≤51
* @param xL 0≤xL≤255
* @param xH 0≤xH≤255
* @param yL 0≤yL≤255
* @param yH 0≤yH≤8
* @param image 0≤d≤255
* k=(xL + xH x 256) x (yL + yH x 256) (k≠0)
* @return command
*/
public static byte[] printRasterBitImage(int m, int xL, int xH, int yL, int yH, byte[] image) {
byte[] part = new byte[]{GS, 118, 48, (byte) m, (byte) xL, (byte) xH, (byte) yL, (byte) yH};
byte[] destination = new byte[part.length + image.length];
System.arraycopy(part, 0, destination, 0, part.length);
System.arraycopy(image, 0, destination, part.length, image.length);
return destination;
}
/**
* Set the horizontal size of the bar code.
* n specifies the bar code width as follows:
* n=2 :
* 0.282mm (Module width for Mult-level Bar code),
* 0.282mm (Thin element width),
* 0.706mm (Thick element width)
* n=3 :
* 0.423mm (Module width for Mult-level Bar code),
* 0.423mm (Thin element width),
* 1.129mm (Thick element width)
* n=4 :
* 0.564mm (Module width for Mult-level Bar code),
* 0.564mm (Thin element width),
* 1.411mm (Thick element width)
* n=5 :
* 0.706mm (Module width for Mult-level Bar code),
* 0.706mm (Thin element width),
* 1.834mm (Thick element width)
* n=6 :
* 0.847mm (Module width for Mult-level Bar code),
* 0.847mm (Thin element width),
* 2.258mm (Thick element width)
* Multi-level bar codes are as follows:
* UPC-A, UPC-E, JAN13 (EAN13), JAN8 (EAN8), CODE93, CODE128
* Binary-level bar codes are as follows: CODE39, ITF, CODABAR
* GS w n
*
* @param n 2≤n≤6
* @return command
*/
public static byte[] setBarCodeWidth(int n) {
return new byte[]{GS, 119, (byte) n};
}
/**
* Selects the model for QR Code.
* (pL + pH x 256) = 4 (pL=4, pH=0)
* cn = 49
* fn = 65
* n1 Function
* 49 Selects model 1.
* 50 Selects model 2.
* GS ( k pL pH cn fn n1 n2
*
* @param n1 n1 = 49,50
* @param n2 n2 = 0
* @return command
*/
public static byte[] selectQRCodeModel(int n1, int n2) {
return new byte[]{GS, 40, 107, 4, 0, 49, 65, (byte) n1, (byte) n2};
}
/**
* Sets the size of the module for QR Code to n dots.
* GS ( k pL pH cn fn n
*
* @param n (pL + pH x 256) = 3 (pL=3, pH=0)
* cn = 49
* fn = 67
* @return command
*/
public static byte[] setQRCodeSizeOfModule(int n) {
return new byte[]{GS, 40, 107, 3, 0, 49, 67, (byte) n};
}
/**
* Selects the error correction level for QR code.
* n fuction Recovery Capacity %(approx.)
* 48 Selects Error correction level L 7
* 49 Selects Error correction level M 15
* 50 Selects Error correction level Q 25
* 51 Selects Error correction level H 30
* (pL + pH x 256) = 3 (pL=3, pH=0)
* cn = 49
* fn = 69
* GS ( k pL pH cn fn n
*
* @param n 47<n<52
* @return command
*/
public static byte[] selectQRCodeErrorCorrectionLevel(int n) {
return new byte[]{GS, 40, 107, 3, 0, 49, 69, (byte) n};
}
/**
* Store the QR Code symbol data (d1…dk) in the symbol storage area.
* cn = 49
* fn = 80
* m = 48
* GS ( k pL pH cn fn m d1…dk
*
* @param pL 0≤pL<256,
* @param pH 0≤pH<28
* @param data 0≤d < 255
* k = (pL + pH* 256) - 3
* @return command
*/
public static byte[] storeQRCodeDataInTheSymbolStorageArea(int pL, int pH, byte[] data) {
byte[] part = new byte[]{GS, 40, 107, (byte) pL, (byte) pH, 49, 80, 48};
byte[] destination = new byte[part.length + data.length];
System.arraycopy(part, 0, destination, 0, part.length);
System.arraycopy(data, 0, destination, part.length, data.length);
return destination;
}
/**
* Encodes and prints the QR Code symbol data in the symbol storage area using the process of
* <Store the data >.
* (pL + pH x 256) = 3 (pL=3, pH=0)
* cn = 49
* fn = 81
* m = 48
* GS ( k pL pH cn fn m
*
* @return command
*/
public static byte[] printQRCodeSymbolDataInTheSymbolStorageArea() {
return new byte[]{GS, 40, 107, 3, 0, 49, 81, 48};
}
/**
* Sets the number of columns of the data area for PDF417.
* n = 0 specifies automatic processing.
* (pL + pH x 256) = 3 (pL=3, pH=0)
* cn = 48
* fn = 65
* GS ( k pL pH cn fn n
*
* @param n 0≤n≤30
* @return command
*/
public static byte[] setNumberOfColumnsOfTheDataAreaForPDF417(int n) {
return new byte[]{GS, 40, 107, 3, 0, 48, 65, (byte) n};
}
/**
* Sets the number of rows of data area for PDF417.
* n = 0 specifies automatic processing.
* (pL + pH x 256) = 3 (pL=3, pH=0)
* cn = 48
* fn = 66
* GS ( k pL pH cn fn n
*
* @param n n=0, 3≤n≤90
* @return command
*/
public static byte[] setNumberOfRowsOfDataAreaForPDF417(int n) {
return new byte[]{GS, 40, 107, 3, 0, 48, 66, (byte) n};
}
/**
* Sets the module width of one PDF417 symbol to n dots.
* (pL + pH x 256) = 3 (pL=3, pH=0)
* cn = 48
* fn = 67
* GS ( k pL pH cn fn n
*
* @param n 2≤n≤8
* @return command
*/
public static byte[] setModuleWidthOfOnePDF417SymbolDots(int n) {
return new byte[]{GS, 40, 107, 3, 0, 48, 67, (byte) n};
}
/**
* Sets the module height to [(module width) × n].
* (pL + pH x 256) = 3 (pL=3, pH=0)
* cn = 48
* fn = 68
* GS ( k pL pH cn fn n
*
* @param n 2≤n≤8
* @return command
*/
public static byte[] setPDF417ModuleHeight(int n) {
return new byte[]{GS, 40, 107, 3, 0, 48, 68, (byte) n};
}
/**
* Sets the error correction level for PDF417 symbols.
* (pL + pH x 256) = 4 (pL=4, pH=0)
* cn = 48
* fn = 69
* GS ( k pL pH cn fn m n
*
* @param m m = 48,49
* @param n 48≤n≤56 (when m=48 is specified)
* 1≤n≤40 (when m=49 is specified)
* @return command
*/
public static byte[] setErrorCorrectionLevelForPDF417Symbols(int m, int n) {
return new byte[]{GS, 40, 107, 4, 0, 48, 69, (byte) m, (byte) n};
}
/**
* Stores symbol data (d1...dk) in the PDF417 symbol storage area.
* Bytes of ((pL + pH × 256) - 3) after m (d1…dk) are processed as symbol data.
* 4≤(pL + pH x 256) ≤65535 (0≤pL≤255, 0≤pH≤255)
* cn = 48
* fn = 80
* m = 48
* GS ( k pL pH cn fn m d1…dk
*
* @param pL 0≤pL≤255
* @param pH 0≤pH≤255
* @param data 0≤d≤255
* k = (pL + pH*256) - 3
* @return command
*/
public static byte[] storeSymbolDataInThePDF417SymbolStorageArea(int pL, int pH, byte[] data) {
byte[] part = new byte[]{GS, 40, 107, (byte) pL, (byte) pH, 48, 80, 48};
byte[] destination = new byte[part.length + data.length];
System.arraycopy(part, 0, destination, 0, part.length);
System.arraycopy(data, 0, destination, part.length, data.length);
return destination;
}
/**
* Prints the PDF417 symbol data in the symbol storage area.
* (pL + pH* 256) = 4 (pL=4, pH=0)
* cn = 48
* fn = 81
* m = 48
* GS ( k pL pH cn fn m
*
* @return command
*/
public static byte[] printPDF417SymbolDataInTheSymbolStorageArea() {
return new byte[]{GS, 40, 107, 4, 0, 48, 81, 48};
}
}
/*
* Copyright (C) 2015 AlexMofer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gingersoft.gsa.cloud.print;
import java.util.List;
/**
* Print
* Created by Alex on 2016/11/10.
*/
public interface PrintDataMaker {
List<byte[]> getPrintData(int type);
}
/*
* Copyright (C) 2015 AlexMofer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gingersoft.gsa.cloud.print;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import java.lang.ref.WeakReference;
import java.util.List;
/**
* 打印执行者
* Created by Alex on 2016/11/10.
*/
public class PrintExecutor {
private int type;
private PrintSocketHolder holder;
private int mReconnectTimes = 0;
private int time = 0;
private PrintSocketHolder.OnStateChangedListener listener;
private WeakReference<OnPrintResultListener> mListener;
public PrintExecutor(BluetoothDevice device, int type) {
holder = new PrintSocketHolder(device);
setType(type);
}
public PrintExecutor(String ip, int port, int type) {
holder = new PrintSocketHolder(ip, port);
setType(type);
}
/**
* 执行打印请求
*
* @return 错误代码
*/
private int doRequest(PrintDataMaker maker) {
if (mReconnectTimes == 0) {
holder.onPrinterStateChanged(PrintSocketHolder.STATE_0);
List<byte[]> data = maker.getPrintData(type);
if (!holder.isSocketPrepared()) {
int prepare = holder.prepareSocket();
if (prepare != PrintSocketHolder.ERROR_0)
return prepare;
}
return holder.sendData(data);
} else {
holder.onPrinterStateChanged(PrintSocketHolder.STATE_0);
List<byte[]> data = maker.getPrintData(type);
if (holder.isSocketPrepared()) {
if (sendData(data))
return PrintSocketHolder.ERROR_0;
else
return PrintSocketHolder.ERROR_100;
} else {
if (prepareSocket() && sendData(data)) {
return PrintSocketHolder.ERROR_0;
} else {
return PrintSocketHolder.ERROR_100;
}
}
}
}
/**
* 执行打印请求
*
* @return 错误代码
*/
public int doPrinterRequest(PrintDataMaker maker) {
holder.setOnStateChangedListener(listener);
return doRequest(maker);
}
private boolean prepareSocket() {
time++;
return time < mReconnectTimes &&
(holder.prepareSocket() == PrintSocketHolder.ERROR_0 || prepareSocket());
}
private boolean sendData(List<byte[]> data) {
if (holder.sendData(data) == PrintSocketHolder.ERROR_0) {
time = 0;
return true;
} else {
return prepareSocket() && sendData(data);
}
}
/**
* 异步执行打印请求
*/
public void doPrinterRequestAsync(PrintDataMaker maker) {
new PrintTask().execute(maker);
}
/**
* 销毁
*/
public int closeSocket() {
return holder.closeSocket();
}
/**
* 设置IP及端口
*
* @param ip IP
* @param port 端口
*/
public void setIp(String ip, int port) {
holder.setIp(ip, port);
}
/**
* 设置蓝牙
*
* @param device 设备
*/
public void setDevice(BluetoothDevice device) {
holder.setDevice(device);
}
/**
* 设置打印类型
*
* @param type 打印类型
*/
public void setType(int type) {
this.type = type;
}
/**
* 设置状态监听
*
* @param listener 监听
*/
public void setOnStateChangedListener(PrintSocketHolder.OnStateChangedListener listener) {
this.listener = listener;
}
/**
* 设置重连次数
*
* @param times 次数
*/
public void setReconnectTimes(int times) {
mReconnectTimes = times;
}
/**
* 设置结果回调
*
* @param listener 回调
*/
public void setOnPrintResultListener(OnPrintResultListener listener) {
mListener = new WeakReference<>(listener);
}
public interface OnPrintResultListener {
void onResult(int errorCode);
}
private class PrintTask extends AsyncTask<PrintDataMaker, Integer, Integer> implements
PrintSocketHolder.OnStateChangedListener {
@Override
protected void onPreExecute() {
super.onPreExecute();
holder.setOnStateChangedListener(this);
}
@Override
protected Integer doInBackground(PrintDataMaker... makers) {
if (makers == null || makers.length < 1)
return PrintSocketHolder.ERROR_0;
return doRequest(makers[0]);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (values == null || values.length < 1)
return;
if (listener != null)
listener.onStateChanged(values[0]);
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if (integer != null) {
onResult(integer);
}
}
/**
* 打印结果
*
* @param errorCode 错误代码
*/
private void onResult(int errorCode) {
try {
if (mListener != null)
mListener.get().onResult(errorCode);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onStateChanged(int state) {
publishProgress(state);
}
}
}
/*
* Copyright (C) 2015 AlexMofer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gingersoft.gsa.cloud.print;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import com.gingersoft.gsa.cloud.constans.PrintConstans;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;
import java.util.UUID;
/**
* 打印Socket
* Created by Alex on 2016/11/10.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class PrintSocketHolder {
public static final int STATE_0 = 0;// 生成测试页面数据
public static final int STATE_1 = 1;// 创建Socket连接
public static final int STATE_2 = 2;// 获取输出流
public static final int STATE_3 = 3;// 写入测试页面数据
public static final int STATE_4 = 4;// 关闭输出流
public static final int ERROR_0 = 0;// 成功
public static final int ERROR_1 = -1;// 生成测试页面数据失败
public static final int ERROR_2 = -2;// 创建Socket失败
public static final int ERROR_3 = -3;// 获取输出流失败
public static final int ERROR_4 = -4;// 写入测试页面数据失败
public static final int ERROR_5 = -5;// 必要参数不能为空
public static final int ERROR_6 = -6;// 关闭Socket出错
public static final int ERROR_100 = -100;// 失败
private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//蓝牙打印UUID
private String ip;
private int port = 9100;
private BluetoothDevice mDevice;
private Socket socket;
private BluetoothSocket bluetoothSocket;
private OutputStream out;
private WeakReference<OnStateChangedListener> mListener;
public PrintSocketHolder(BluetoothDevice device) {
setDevice(device);
}
public PrintSocketHolder(String ip, int port) {
setIp(ip, port);
}
@SuppressLint("MissingPermission")
public int createSocket() {
onPrinterStateChanged(STATE_1);
if (mDevice == null && ip == null)
return ERROR_5;
try {
if (mDevice != null) {
bluetoothSocket = mDevice.createRfcommSocketToServiceRecord(uuid);
bluetoothSocket.connect();
} else {
socket = new Socket();//ip, port
InetSocketAddress socketAddress = new InetSocketAddress(ip, port);
//设置 超时时间
socket.setSoTimeout(PrintConstans.SO_TIMEOUT);
socket.connect(socketAddress, PrintConstans.PRINT_TIMEOUT);//开始连接ip
}
} catch (Exception e) {
closeSocket();
return ERROR_2;
}
return ERROR_0;
}
public int getOutputStream() {
onPrinterStateChanged(STATE_2);
try {
if (mDevice != null) {
out = bluetoothSocket.getOutputStream();
} else {
out = socket.getOutputStream();
}
} catch (IOException e) {
closeSocket();
return ERROR_3;
}
return ERROR_0;
}
public boolean isSocketPrepared() {
return (bluetoothSocket != null || socket != null) && out != null;
}
public int sendData(List<byte[]> data) {
onPrinterStateChanged(STATE_3);
if (data == null || data.size() <= 0)
return ERROR_0;
for (byte[] item : data) {
try {
out.write(item);
out.flush();
} catch (IOException e) {
closeSocket();
return ERROR_4;
}
}
return ERROR_0;
}
public int sendData(byte[] data) {
onPrinterStateChanged(STATE_3);
try {
out.write(data);
out.flush();
} catch (IOException e) {
closeSocket();
return ERROR_4;
}
return ERROR_0;
}
public int sendData(byte[]... data) {
onPrinterStateChanged(STATE_3);
for (byte[] item : data) {
try {
out.write(item);
out.flush();
} catch (IOException e) {
closeSocket();
return ERROR_4;
}
}
return ERROR_0;
}
public int prepareSocket() {
int create = createSocket();
if (create != PrintSocketHolder.ERROR_0)
return create;
return getOutputStream();
}
/**
* 销毁
*/
public int closeSocket() {
onPrinterStateChanged(STATE_4);
boolean error = false;
try {
if (out != null) {
out.close();
out = null;
}
} catch (IOException e) {
out = null;
error = true;
}
try {
if (socket != null) {
socket.close();
socket = null;
}
} catch (IOException e) {
socket = null;
error = true;
}
try {
if (bluetoothSocket != null) {
bluetoothSocket.close();
bluetoothSocket = null;
}
} catch (IOException e) {
bluetoothSocket = null;
error = true;
}
return error ? ERROR_6 : ERROR_0;
}
/**
* 打印状态变化
*
* @param state 打印状态
*/
public void onPrinterStateChanged(int state) {
try {
if (mListener != null)
mListener.get().onStateChanged(state);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 设置IP及端口
*
* @param ip IP
* @param port 端口
*/
public void setIp(String ip, int port) {
this.ip = ip;
this.port = port;
}
/**
* 设置蓝牙
*
* @param device 设备
*/
public void setDevice(BluetoothDevice device) {
this.mDevice = device;
}
/**
* 设置状态监听
*
* @param listener 监听
*/
public void setOnStateChangedListener(OnStateChangedListener listener) {
mListener = new WeakReference<>(listener);
}
public interface OnStateChangedListener {
void onStateChanged(int state);
}
}
/*
* Copyright (C) 2015 AlexMofer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gingersoft.gsa.cloud.print;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import java.util.ArrayList;
import java.util.List;
/**
* ESC-POS指令集
* 未经过测试的指令集已全部放在了 {@link PrintCommands}
* Created by Alex on 2015/9/22.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class PrinterUtils {
private static String hexStr = "0123456789ABCDEF";
private static String[] binaryArray = {"0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"};
/**
* 初始化打印机
*
* @return command
*/
public static byte[] initPrinter() {
return PrintCommands.initializePrinter();
}
/**
* 打印并换行
*
* @return command
*/
public static byte[] printLineFeed() {
return PrintCommands.printLineFeed();
}
/**
* 开启着重强调(加粗)
* ESC E n
*
* @return bytes for this command
*/
public static byte[] emphasizedOn() {
return PrintCommands.turnOnEmphasizedMode();
}
/**
* 关闭着重强调(加粗)
* ESC E n
*
* @return bytes for this command
*/
public static byte[] emphasizedOff() {
return PrintCommands.turnOffEmphasizedMode();
}
/**
* 左对齐
* ESC a n
*
* @return bytes for this command
*/
public static byte[] alignLeft() {
return PrintCommands.selectJustification(0);
}
/**
* 居中对齐
* ESC a n
*
* @return bytes for this command
*/
public static byte[] alignCenter() {
return PrintCommands.selectJustification(1);
}
/**
* 右对齐
* ESC a n
*
* @return bytes for this command
*/
public static byte[] alignRight() {
return PrintCommands.selectJustification(2);
}
/**
* 设置行间距
*
* @param height 0≤height≤255
* @return command
*/
public static byte[] printLineHeight(int height) {
return PrintCommands.setLineSpacing(height);
}
/**
* 字体变大为标准的n倍
*
* @param num 倍数
* @return bytes for this command
*/
public static byte[] fontSizeSetBig(int num) {
byte realSize = 0;
switch (num) {
case 0:
//noinspection ConstantConditions
realSize = 0;
break;
case 1:
realSize = 17;
break;
case 2:
realSize = 34;
break;
case 3:
realSize = 51;
break;
case 4:
realSize = 68;
break;
case 5:
realSize = 85;
break;
case 6:
realSize = 102;
break;
case 7:
realSize = 119;
break;
}
return PrintCommands.selectCharacterSize(realSize);
}
/**
* 进纸切割
* Feeds paper to ( cutting position + n x vertical motion unit )
* and executes a full cut ( cuts the paper completely )
*
* @return bytes for this command
*/
public static byte[] feedPaperCut() {
return PrintCommands.selectCutModeAndCutPaper(1, 0);
}
/**
* 进纸切割(留部分)
* Feeds paper to ( cutting position + n x vertical motion unit )
* and executes a partial cut ( one point left uncut )
*
* @return bytes for this command
*/
public static byte[] feedPaperCutPartial() {
return PrintCommands.selectCutModeAndCutPaper(66, 0);
}
/**
* 解码图片
*
* @param image 图片
* @param parting 高度分割值
* @return 数据流
*/
public static ArrayList<byte[]> decodeBitmapToDataList(Bitmap image, int parting) {
if (parting <= 0 || parting > 255)
parting = 255;
if (image == null)
return null;
final int width = image.getWidth();
final int height = image.getHeight();
if (width <= 0 || height <= 0)
return null;
if (width > 2040) {
// 8位9针,宽度限制2040像素(但一般纸张都没法打印那么宽,但并不影响打印)
final float scale = 2040 / (float) width;
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap resizeImage;
try {
resizeImage = Bitmap.createBitmap(image, 0, 0, width, height, matrix, true);
} catch (OutOfMemoryError e) {
return null;
}
ArrayList<byte[]> data = decodeBitmapToDataList(resizeImage, parting);
resizeImage.recycle();
return data;
}
// 宽命令
String widthHexString = Integer.toHexString(width % 8 == 0 ? width / 8 : (width / 8 + 1));
if (widthHexString.length() > 2) {
// 超过2040像素才会到达这里
return null;
} else if (widthHexString.length() == 1) {
widthHexString = "0" + widthHexString;
}
widthHexString += "00";
// 每行字节数(除以8,不足补0)
String zeroStr = "";
int zeroCount = width % 8;
if (zeroCount > 0) {
for (int i = 0; i < (8 - zeroCount); i++) {
//noinspection StringConcatenationInLoop
zeroStr += "0";
}
}
ArrayList<String> commandList = new ArrayList<>();
// 高度每parting像素进行一次分割
int time = height % parting == 0 ? height / parting : (height / parting + 1);// 循环打印次数
for (int t = 0; t < time; t++) {
int partHeight = t == time - 1 ? height % parting : parting;// 分段高度
// 高命令
String heightHexString = Integer.toHexString(partHeight);
if (heightHexString.length() > 2) {
// 超过255像素才会到达这里
return null;
} else if (heightHexString.length() == 1) {
heightHexString = "0" + heightHexString;
}
heightHexString += "00";
// 宽高指令
String commandHexString = "1D763000";
commandList.add(commandHexString + widthHexString + heightHexString);
ArrayList<String> list = new ArrayList<>(); //binaryString list
StringBuilder sb = new StringBuilder();
// 像素二值化,非黑即白
for (int i = 0; i < partHeight; i++) {
sb.delete(0, sb.length());
for (int j = 0; j < width; j++) {
// 实际在图片中的高度
int startHeight = t * parting + i;
//得到当前像素的值
int color = image.getPixel(j, startHeight);
int red, green, blue;
if (image.hasAlpha()) {
//得到alpha通道的值
int alpha = Color.alpha(color);
//得到图像的像素RGB的值
red = Color.red(color);
green = Color.green(color);
blue = Color.blue(color);
final float offset = alpha / 255.0f;
// 根据透明度将白色与原色叠加
red = 0xFF + (int) Math.ceil((red - 0xFF) * offset);
green = 0xFF + (int) Math.ceil((green - 0xFF) * offset);
blue = 0xFF + (int) Math.ceil((blue - 0xFF) * offset);
} else {
//得到图像的像素RGB的值
red = Color.red(color);
green = Color.green(color);
blue = Color.blue(color);
}
// 接近白色改为白色。其余黑色
if (red > 160 && green > 160 && blue > 160)
sb.append("0");
else
sb.append("1");
}
// 每一行结束时,补充剩余的0
if (zeroCount > 0) {
sb.append(zeroStr);
}
list.add(sb.toString());
}
// binaryStr每8位调用一次转换方法,再拼合
ArrayList<String> bmpHexList = new ArrayList<>();
for (String binaryStr : list) {
sb.delete(0, sb.length());
for (int i = 0; i < binaryStr.length(); i += 8) {
String str = binaryStr.substring(i, i + 8);
// 2进制转成16进制
String hexString = binaryStrToHexString(str);
sb.append(hexString);
}
bmpHexList.add(sb.toString());
}
// 数据指令
commandList.addAll(bmpHexList);
}
ArrayList<byte[]> data = new ArrayList<>();
for (String hexStr : commandList) {
data.add(hexStringToBytes(hexStr));
}
return data;
}
/**
* 解码图片
*
* @param image 图片
* @param parting 高度分割值
* @return 数据流
*/
public static byte[] decodeBitmap(Bitmap image, int parting) {
ArrayList<byte[]> data = decodeBitmapToDataList(image, parting);
int len = 0;
//noinspection ConstantConditions
for (byte[] srcArray : data) {
len += srcArray.length;
}
byte[] destArray = new byte[len];
int destLen = 0;
for (byte[] srcArray : data) {
System.arraycopy(srcArray, 0, destArray, destLen, srcArray.length);
destLen += srcArray.length;
}
return destArray;
}
/**
* 解码图片
*
* @param image 图片
* @return 数据流
*/
public static byte[] decodeBitmap(Bitmap image) {
return decodeBitmap(image, PrinterWriter.HEIGHT_PARTING_DEFAULT);
}
/**
* 合并byte数组
*
* @param byteArray byte数组
* @return 一个byte数组
*/
public static byte[] mergerByteArray(byte[]... byteArray) {
int length = 0;
for (byte[] item : byteArray) {
length += item.length;
}
byte[] result = new byte[length];
int index = 0;
for (byte[] item : byteArray) {
for (byte b : item) {
result[index] = b;
index++;
}
}
return result;
}
/**
* 2进制转成16进制
*
* @param binaryStr 2进制串
* @return 16进制串
*/
public static String binaryStrToHexString(String binaryStr) {
String hex = "";
String f4 = binaryStr.substring(0, 4);
String b4 = binaryStr.substring(4, 8);
for (int i = 0; i < binaryArray.length; i++) {
if (f4.equals(binaryArray[i]))
//noinspection StringConcatenationInLoop
hex += hexStr.substring(i, i + 1);
}
for (int i = 0; i < binaryArray.length; i++) {
if (b4.equals(binaryArray[i]))
//noinspection StringConcatenationInLoop
hex += hexStr.substring(i, i + 1);
}
return hex;
}
/**
* 16进制指令list转换为byte[]指令
*
* @param list 指令集
* @return byte[]指令
*/
public static byte[] hexListToByte(List<String> list) {
ArrayList<byte[]> commandList = new ArrayList<>();
for (String hexStr : list) {
commandList.add(hexStringToBytes(hexStr));
}
int len = 0;
for (byte[] srcArray : commandList) {
len += srcArray.length;
}
byte[] destArray = new byte[len];
int destLen = 0;
for (byte[] srcArray : commandList) {
System.arraycopy(srcArray, 0, destArray, destLen, srcArray.length);
destLen += srcArray.length;
}
return destArray;
}
/**
* 16进制串转byte数组
*
* @param hexString 16进制串
* @return byte数组
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* 16进制char 转 byte
*
* @param c char
* @return byte
*/
private static byte charToByte(char c) {
return (byte) hexStr.indexOf(c);
}
}
/*
* Copyright (C) 2015 AlexMofer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gingersoft.gsa.cloud.print;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
/**
* 打印机写入器
* Created by Alex on 2016/4/18.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public abstract class PrinterWriter {
public static final int HEIGHT_PARTING_DEFAULT = 255;
private static final String CHARSET = "gb2312";
private ByteArrayOutputStream bos;
private int heightParting;
public PrinterWriter() throws IOException {
this(HEIGHT_PARTING_DEFAULT);
}
public PrinterWriter(int parting) throws IOException {
if (parting <= 0 || parting > HEIGHT_PARTING_DEFAULT)
heightParting = HEIGHT_PARTING_DEFAULT;
else
heightParting = parting;
init();
}
/**
* 判断是否中文
* GENERAL_PUNCTUATION 判断中文的“号
* CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号
* HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的,号
*
* @param c 字符
* @return 是否中文
*/
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION;
}
public static boolean isCyrillic(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
return ub == Character.UnicodeBlock.CYRILLIC;
}
/**
* 初始化
*
* @throws IOException 异常
*/
public void init() throws IOException {
bos = new ByteArrayOutputStream();
write(PrinterUtils.initPrinter());
}
/**
* 获取预打印数据并重置流
*
* @return 预打印数据
* @throws IOException 异常
*/
public byte[] getDataAndReset() throws IOException {
byte[] data;
bos.flush();
data = bos.toByteArray();
bos.reset();
return data;
}
/**
* 获取预打印数据并关闭流
*
* @return 预打印数据
* @throws IOException 异常
*/
public byte[] getDataAndClose() throws IOException {
byte[] data;
bos.flush();
data = bos.toByteArray();
bos.close();
bos = null;
return data;
}
/**
* 写入数据
*
* @param data 数据
* @throws IOException 异常
*/
public void write(byte[] data) throws IOException {
if (bos == null)
init();
bos.write(data);
}
/**
* 设置居中
*
* @throws IOException 异常
*/
public void setAlignCenter() throws IOException {
write(PrinterUtils.alignCenter());
}
/**
* 设置左对齐
*
* @throws IOException 异常
*/
public void setAlignLeft() throws IOException {
write(PrinterUtils.alignLeft());
}
/**
* 设置右对齐
*
* @throws IOException 异常
*/
public void setAlignRight() throws IOException {
write(PrinterUtils.alignRight());
}
/**
* 开启着重
*
* @throws IOException 异常
*/
public void setEmphasizedOn() throws IOException {
write(PrinterUtils.emphasizedOn());
}
/**
* 关闭着重
*
* @throws IOException 异常
*/
public void setEmphasizedOff() throws IOException {
write(PrinterUtils.emphasizedOff());
}
/**
* 设置文字大小
*
* @param size 文字大小 (0~7)(默认0)
* @throws IOException 异常
*/
public void setFontSize(int size) throws IOException {
write(PrinterUtils.fontSizeSetBig(size));
}
/**
* 设置行高度
*
* @param height 行高度
* @throws IOException 异常
*/
public void setLineHeight(int height) throws IOException {
write(PrinterUtils.printLineHeight(height));
}
/**
* 写入字符串
*
* @param string 字符串
* @throws IOException 异常
*/
public void print(String string) throws IOException {
print(string, CHARSET);
}
/**
* 写入字符串
*
* @param string 字符串
* @param charsetName 编码方式
* @throws IOException 异常
*/
public void print(String string, String charsetName) throws IOException {
if (string == null)
return;
write(string.getBytes(charsetName));
}
/**
* 写入一条横线
*
* @throws IOException 异常
*/
@SuppressWarnings("StringConcatenationInLoop")
public void printLine() throws IOException {
int length = getLineWidth();
String line = "";
while (length > 0) {
line += "─";
length--;
}
print(line);
}
/**
* 获取横线线宽
*
* @return 横线线宽
*/
protected abstract int getLineWidth();
/**
* 一行输出
*
* @param str1 字符串
* @param str2 字符串
* @param textSize 文字大小
* @throws IOException 异常
*/
public void printInOneLine(String str1, String str2, int textSize) throws IOException {
printInOneLine(str1, str2, textSize, CHARSET);
}
/**
* 一行输出
*
* @param str1 字符串
* @param str2 字符串
* @param textSize 文字大小
* @param charsetName 编码方式
* @throws IOException 异常
*/
@SuppressWarnings("StringConcatenationInLoop")
public void printInOneLine(String str1, String str2, int textSize, String charsetName) throws IOException {
int lineLength = getLineStringWidth(textSize);
int needEmpty = lineLength - (getStringWidth(str1) + getStringWidth(str2)) % lineLength;
String empty = "";
while (needEmpty > 0) {
empty += " ";
needEmpty--;
}
print(str1 + empty + str2, charsetName);
}
/**
* 获取一行字符串长度
*
* @param textSize 文字大小
* @return 一行字符串长度
*/
protected abstract int getLineStringWidth(int textSize);
private int getStringWidth(String str) {
int width = 0;
for (char c : str.toCharArray()) {
width += isChinese(c) || isCyrillic(c) ? 2 : 1;
}
return width;
}
/**
* 获取图片数据流
*
* @param res Resources
* @param id 资源ID
* @return 数据流
*/
public ArrayList<byte[]> getImageByte(Resources res, int id) {
int maxWidth = getDrawableMaxWidth();
Bitmap image = scalingBitmap(res, id, maxWidth);
if (image == null)
return null;
ArrayList<byte[]> data = PrinterUtils.decodeBitmapToDataList(image, heightParting);
image.recycle();
return data;
}
/**
* 获取图片最大宽度
*
* @return 图片最大宽度
*/
protected abstract int getDrawableMaxWidth();
/**
* 缩放图片
*
* @param res 资源
* @param id ID
* @param maxWidth 最大宽
* @return 缩放后的图片
*/
private Bitmap scalingBitmap(Resources res, int id, int maxWidth) {
if (res == null)
return null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;// 设置只量取宽高
BitmapFactory.decodeResource(res, id, options);// 量取宽高
options.inJustDecodeBounds = false;
// 粗略缩放
if (maxWidth > 0 && options.outWidth > maxWidth) {
// 超过限定宽
double ratio = options.outWidth / (double) maxWidth;// 计算缩放比
int sampleSize = (int) Math.floor(ratio);// 向下取整,保证缩放后不会低于最大宽高
if (sampleSize > 1) {
options.inSampleSize = sampleSize;// 设置缩放比,原图的几分之一
}
}
try {
Bitmap image = BitmapFactory.decodeResource(res, id, options);
final int width = image.getWidth();
final int height = image.getHeight();
// 精确缩放
if (maxWidth <= 0 || width <= maxWidth) {
return image;
}
final float scale = maxWidth / (float) width;
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap resizeImage = Bitmap.createBitmap(image, 0, 0, width, height, matrix, true);
image.recycle();
return resizeImage;
} catch (OutOfMemoryError e) {
return null;
}
}
/**
* 获取图片数据流
*
* @param drawable 图片
* @return 数据流
*/
public ArrayList<byte[]> getImageByte(Drawable drawable) {
int maxWidth = getDrawableMaxWidth();
Bitmap image = scalingDrawable(drawable, maxWidth);
if (image == null)
return null;
ArrayList<byte[]> data = PrinterUtils.decodeBitmapToDataList(image, heightParting);
image.recycle();
return data;
}
/**
* 缩放图片
*
* @param drawable 图片
* @param maxWidth 最大宽
* @return 缩放后的图片
*/
private Bitmap scalingDrawable(Drawable drawable, int maxWidth) {
if (drawable == null || drawable.getIntrinsicWidth() == 0
|| drawable.getIntrinsicHeight() == 0)
return null;
final int width = drawable.getIntrinsicWidth();
final int height = drawable.getIntrinsicHeight();
try {
Bitmap image = Bitmap.createBitmap(width, height,
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(image);
drawable.setBounds(0, 0, width, height);
drawable.draw(canvas);
// 精确缩放
if (maxWidth <= 0 || width <= maxWidth) {
return image;
}
final float scale = maxWidth / (float) width;
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap resizeImage = Bitmap.createBitmap(image, 0, 0, width, height, matrix, true);
image.recycle();
return resizeImage;
} catch (OutOfMemoryError e) {
return null;
}
}
/**
* 获取图片数据流
*
* @param image 图片
* @return 数据流
*/
public ArrayList<byte[]> getImageByte(Bitmap image) {
int maxWidth = getDrawableMaxWidth();
Bitmap scalingImage = scalingBitmap(image, maxWidth);
if (scalingImage == null)
return null;
ArrayList<byte[]> data = PrinterUtils.decodeBitmapToDataList(image, heightParting);
image.recycle();
return data;
}
/**
* 缩放图片
*
* @param image 图片
* @param maxWidth 最大宽
* @return 缩放后的图片
*/
private Bitmap scalingBitmap(Bitmap image, int maxWidth) {
if (image == null || image.getWidth() <= 0 || image.getHeight() <= 0)
return null;
try {
final int width = image.getWidth();
final int height = image.getHeight();
// 精确缩放
float scale = 1;
if (maxWidth <= 0 || width <= maxWidth) {
scale = maxWidth / (float) width;
}
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
return Bitmap.createBitmap(image, 0, 0, width, height, matrix, true);
} catch (OutOfMemoryError e) {
return null;
}
}
/**
* 获取图片数据流
*
* @param filePath 图片路径
* @return 数据流
*/
public ArrayList<byte[]> getImageByte(String filePath) {
Bitmap image;
try {
int width;
int height;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
width = options.outWidth;
height = options.outHeight;
if (width <= 0 || height <= 0)
return null;
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
image = BitmapFactory.decodeFile(filePath, options);
} catch (OutOfMemoryError | Exception e) {
return null;
}
return getImageByte(image);
}
/**
* 输出并换行
*
* @throws IOException 异常
*/
public void printLineFeed() throws IOException {
write(PrinterUtils.printLineFeed());
}
/**
* 进纸切割
*
* @throws IOException 异常
*/
public void feedPaperCut() throws IOException {
write(PrinterUtils.feedPaperCut());
}
/**
* 进纸切割(留部分)
*
* @throws IOException 异常
*/
public void feedPaperCutPartial() throws IOException {
write(PrinterUtils.feedPaperCutPartial());
}
/**
* 获取图片打印高度分割值
*
* @return 高度分割值
*/
public int getHeightParting() {
return heightParting;
}
/**
* 设置图片打印高度分割值
* 最大允许255像素
*
* @param parting 高度分割值
*/
public void setHeightParting(int parting) {
if (parting <= 0 || parting > HEIGHT_PARTING_DEFAULT)
return;
heightParting = parting;
}
}
/*
* Copyright (C) 2015 AlexMofer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gingersoft.gsa.cloud.print;
import java.io.IOException;
/**
* 纸宽58mm的打印机
* Created by Alex on 2016/6/17.
*/
@SuppressWarnings("unused")
public class PrinterWriter58mm extends PrinterWriter {
public static final int TYPE_58 = 58;// 纸宽58mm
public int width = 380;
public PrinterWriter58mm() throws IOException {
}
public PrinterWriter58mm(int parting) throws IOException {
super(parting);
}
public PrinterWriter58mm(int parting, int width) throws IOException {
super(parting);
this.width = width;
}
@Override
protected int getLineWidth() {
return 16;
}
@Override
protected int getLineStringWidth(int textSize) {
switch (textSize) {
default:
case 0:
return 31;
case 1:
return 15;
}
}
@Override
protected int getDrawableMaxWidth() {
return width;
}
}
/*
* Copyright (C) 2015 AlexMofer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gingersoft.gsa.cloud.print;
import java.io.IOException;
/**
* 纸宽80mm的打印机
* Created by Alex on 2016/6/17.
*/
@SuppressWarnings("unused")
public class PrinterWriter80mm extends PrinterWriter {
public static final int TYPE_80 = 80;// 纸宽80mm
public int width = 500;
public PrinterWriter80mm() throws IOException {
}
public PrinterWriter80mm(int parting) throws IOException {
super(parting);
}
public PrinterWriter80mm(int parting, int width) throws IOException {
super(parting);
this.width = width;
}
@Override
protected int getLineWidth() {
return 24;
}
@Override
protected int getLineStringWidth(int textSize) {
switch (textSize) {
default:
case 0:
return 47;
case 1:
return 23;
}
}
@Override
protected int getDrawableMaxWidth() {
return width;
}
}
...@@ -481,5 +481,5 @@ ...@@ -481,5 +481,5 @@
<dimen name="sp_42">42sp</dimen> <dimen name="sp_42">42sp</dimen>
<dimen name="sp_48">48sp</dimen> <dimen name="sp_48">48sp</dimen>
<!-- 清機報表字體大小 --> <!-- 清機報表字體大小 -->
<dimen name="settlement_report_text_size">@dimen/dp_16</dimen> <dimen name="settlement_report_text_size">@dimen/sp_18</dimen>
</resources> </resources>
\ No newline at end of file
package com.gingersoft.gsa.cloud.table.mvp.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.gingersoft.gsa.cloud.base.qmui.arch.QMUIFragmentPagerAdapter;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerOrderCenterComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderCenterContract;
import com.gingersoft.gsa.cloud.table.mvp.presenter.OrderCenterPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.AllOrderFragment;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;
import butterknife.BindView;
import static com.jess.arms.utils.Preconditions.checkNotNull;
/**
* ================================================
* Description:
* <p>
* Created by MVPArmsTemplate on 03/13/2020 14:28
* <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
* <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
* <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
* ================================================
*/
public class OrderCenterActivity extends BaseActivity<OrderCenterPresenter> implements OrderCenterContract.View {
@BindView(R2.id.topbar)
QMUITopBar mTopBar;
@BindView(R2.id.tabSegment)
QMUITabSegment mTabSegment;
@BindView(R2.id.contentViewPager)
ViewPager mContentViewPager;
private String[] tabTitles = {"全部", "已取消"};
@Override
public void setupActivityComponent(@NonNull AppComponent appComponent) {
DaggerOrderCenterComponent //如找不到该类,请编译一下项目
.builder()
.appComponent(appComponent)
.view(this)
.build()
.inject(this);
}
@Override
public int initView(@Nullable Bundle savedInstanceState) {
return R.layout.activity_order_center; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
}
@Override
public void initData(@Nullable Bundle savedInstanceState) {
initTabAndPager();
}
private void initTabAndPager() {
QMUIFragmentPagerAdapter pagerAdapter = new QMUIFragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment createFragment(int position) {
AllOrderFragment fragment = new AllOrderFragment();
Bundle bundle = new Bundle();
bundle.putInt("currentPageIndex", position);
fragment.setArguments(bundle);
return fragment;
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "全部";
case 1:
return "已取消";
case 3:
default:
return "全部";
}
}
};
mContentViewPager.setAdapter(pagerAdapter);
mTabSegment.setupWithViewPager(mContentViewPager);
}
@Override
public void initIntent() {
}
@Override
public void initTopBar() {
mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color));
mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
killMyself();
}
});
mTopBar.setTitle("張單管理");
}
@Override
public void initLanguage() {
}
@Override
public void initLayoutParams() {
}
@Override
public void initLayoutVisible() {
}
@Override
public void showLoading(String message) {
if (message != null)
LoadingDialog.showDialogForLoading(this, message, true);
else
LoadingDialog.showDialogForLoading(this);
}
@Override
public void hideLoading() {
LoadingDialog.cancelDialogForLoading();
}
@Override
public void showMessage(@NonNull String message) {
checkNotNull(message);
ArmsUtils.makeText(this, message);
}
@Override
public void launchActivity(@NonNull Intent intent) {
checkNotNull(intent);
ArmsUtils.startActivity(intent);
}
@Override
public void killMyself() {
finish();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment