Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void PrinterReceipt(Context context, String portname, RelativeLayout layout){
- String portName = portname; //ip address of your printer
- String portSettings = "";
- //have to measure the layout for it to print correctly, otherwise sizes are zero
- layout.measure(View.MeasureSpec.makeMeasureSpec(layout.getLayoutParams().width, View.MeasureSpec.EXACTLY),
- View.MeasureSpec.makeMeasureSpec(layout.getLayoutParams().height, View.MeasureSpec.EXACTLY));
- layout.layout(0, 0, layout.getMeasuredWidth(), layout.getMeasuredHeight());
- Bitmap bitmap = Bitmap.createBitmap(layout.getWidth(),layout.getHeight(), Bitmap.Config.RGB_565);
- Canvas canvas = new Canvas(bitmap);
- canvas.drawColor(Color.WHITE);
- layout.draw(canvas);
- int maxWidth = 576; //default width of tsp100 receipt
- RasterDocument rasterDoc = new RasterDocument(RasterDocument.RasSpeed.Full, RasterDocument.RasPageEndMode.FeedAndFullCut, RasterDocument.RasPageEndMode.FeedAndFullCut, RasterDocument.RasTopMargin.Standard, 0, 0, 0);
- StarBitmap starbitmap = new StarBitmap(bitmap, false, maxWidth);
- StarIOPort port = null;
- try {
- /*
- using StarIOPort3.1.jar (support USB Port)
- Android OS Version: upper 2.2
- */
- port = StarIOPort.getPort(portName, portSettings, 10000, context);
- /*
- using StarIOPort.jar
- Android OS Version: under 2.1
- port = StarIOPort.getPort(portName, portSettings, 10000);
- */
- try {
- Thread.sleep(500);
- }
- catch(InterruptedException e) {}
- byte[] command = rasterDoc.BeginDocumentCommandData();
- port.writePort(command, 0, command.length);
- command = starbitmap.getImageRasterDataForPrinting(true);
- port.writePort(command, 0, command.length);
- command = rasterDoc.EndDocumentCommandData();
- port.writePort(command, 0, command.length);
- try {
- Thread.sleep(1000);
- }
- catch(InterruptedException e) {
- e.printStackTrace();
- }
- } catch (StarIOPortException e) {
- ShowAlertMessage(context, "Failure", "Failed to connect to printer. " + e.getMessage());
- }
- finally {
- if(port != null) {
- try {
- StarIOPort.releasePort(port);
- } catch (StarIOPortException e) {
- e.printStackTrace();
- }
- }
- }
- }
- private static void ShowAlertMessage(final Context context, final String alertTitle, final String message){
- try {
- ((Activity)context).runOnUiThread(new Runnable() {
- @Override
- public void run() {
- AlertDialog.Builder dialog = new AlertDialog.Builder(context);
- dialog.setNegativeButton("Ok", null);
- AlertDialog alert = dialog.create();
- alert.setTitle(alertTitle);
- alert.setMessage(message);
- alert.show();
- }});
- } catch (final Exception e) {
- Log.e("PrintReceipt", e.getMessage());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement