How to print from Android Studio Barcode printer - android-studio

Barcode I want to send a barcode to the printer. I tried it in PDF, JPEG, PNG format. It prints a blank page on all of them.I couldn't find any results on google.
I need to do it without using Printer Helper, if possible
public class yazdır extends AsyncTask<Void , Void,Void> {
#Override
protected Void doInBackground(Void... arg0) {
DataOutputStream outToServer;
Socket clientSocket;
File filename;
PrintHelper photoPrinter = new PrintHelper(getActivity());
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
for (int i=0;i<=adet;i++) {
try {
String path = Environment.getExternalStorageDirectory().toString();
filename = new File(path + "/folder/subfolder/image.png");
FileInputStream fileInputStream = new FileInputStream(filename);
InputStream is = fileInputStream;
clientSocket = new Socket("192.168.1.31", 9100);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
byte[] buffer = new byte[1024];
int size;
while ((size=is.read(buffer)) !=-1){
outToServer.write(buffer,0,size);
}
outToServer.flush();
} catch (ConnectException connectException) {
Log.e(TAG, connectException.toString(), connectException);
return null;
} catch (UnknownHostException e1) {
Log.e(TAG, e1.toString(), e1);
return null;
} catch (IOException e1) {
Log.e(TAG, e1.toString(), e1);
return null;
} finally {
}
}
return null;}
}
When I send it to a regular printer. Says document is printing and cancels printing.

Related

RecylerView to pdf

Hello am new to Android studio
I have made recylerview for transaction details . I need to create pdf for this recylerview items.
Example: I have 24 cardviews in recylerview so need to create pdf with each page 4 cardviews only . So totally I need to get pdf as 6 pages .
How to do that . Thanks in advance.
This is sample image of my view
Am passing below code
recyclerView.measure(View.MeasureSpec.makeMeasureSpec(recyclerView.getWidth(),View.MeasureSpec.EXACTLY),View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED));
Bitmap bm=Bitmap.createBitmap(recyclerView.getWidth(),recyclerView.getMeasuredHeight(),Bitmap.Config.ARGB_8888);
String mpath2="/mnt/sdcard/mathanpaymentpdf";
File imageFile = new File(mpath2);
PDFHelper pdfHelper = new PDFHelper(imageFile,this);
pdfHelper.saveImageToPDF(recyclerView,bm,"mathan"+System.currentTimeMillis());
public class PDFHelper {
private File mFolder;
private File mFile;
private Context mContext;
public PDFHelper(File folder, Context context) {
this.mContext = context;
this.mFolder = folder;
if(!mFolder.exists())
mFolder.mkdirs();
}
public void saveImageToPDF(View title, Bitmap bitmap, String filename) {
mFile = new File(mFolder, filename + ".pdf");
if (!mFile.exists()) {
int height = title.getHeight() + bitmap.getHeight();
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), height, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
title.draw(canvas);
canvas.drawBitmap(bitmap, null, new Rect(0, title.getHeight(), bitmap.getWidth(),bitmap.getHeight()), null);
document.finishPage(page);
try {
mFile.createNewFile();
OutputStream out = new FileOutputStream(mFile);
document.writeTo(out);
document.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This am tried am getting pdf on a single page only
Just I need to split into multiple pages.
Note: I need code in java, not in kotlin
Am solved this by using itext library
implementation 'com.itextpdf:itextpdf:5.0.6'
Then call with RecylerView
public void generatePDF(RecyclerView view) {
RecyclerView.Adapter adapter = view.getAdapter();
int sie2=adapter.getItemCount();
if (sie2 == 0) {
Toast.makeText(this,"No Transactions",Toast.LENGTH_LONG).show();
}else{
Bitmap bigBitmap = null;
if (adapter != null) {
int size = adapter.getItemCount();
int height = 0;
Paint paint = new Paint();
int iHeight = 0;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
LruCache<String, Bitmap> bitmaCache = new LruCache<>(cacheSize);
for (int i = 0; i < size; i++) {
RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
adapter.onBindViewHolder(holder, i);
holder.itemView.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(), holder.itemView.getMeasuredHeight());
holder.itemView.setDrawingCacheEnabled(true);
holder.itemView.buildDrawingCache();
Bitmap drawingCache = holder.itemView.getDrawingCache();
if (drawingCache != null) {
bitmaCache.put(String.valueOf(i), drawingCache);
}
height += holder.itemView.getMeasuredHeight();
}
bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888);
Canvas bigCanvas = new Canvas(bigBitmap);
bigCanvas.drawColor(Color.WHITE);
Document document=new Document();
final File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MAT"+System.currentTimeMillis()+".pdf");
try {
PdfWriter.getInstance(document, new FileOutputStream(file));
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < size; i++) {
try {
//Adding the content to the document
Bitmap bmp = bitmaCache.get(String.valueOf(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
com.itextpdf.text.Image image= com.itextpdf.text.Image.getInstance(stream.toByteArray());
//Image image = Image.getInstance(stream.toByteArray());
float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
- document.rightMargin() - 50) / image.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
image.scalePercent(scaler);
image.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER | com.itextpdf.text.Image.ALIGN_TOP);
if (!document.isOpen()) {
document.open();
}
document.add(image);
} catch (Exception ex) {
Log.e("TAG-ORDER PRINT ERROR", ex.getMessage());
}
}
if (document.isOpen()) {
document.close();
}
// Set on UI Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivityAdminMain.this);
builder.setTitle("Success")
.setMessage("PDF File Generated Successfully.")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("Open", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// dialog.dismiss();
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent56 = Intent.createChooser(target, "Open File");
try {
startActivity(intent56);
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivityAdminMain.this,"No PDF Viewer Installed.",Toast.LENGTH_LONG).show();
}
}
}).show();
}
});
}}
}
100% working.. This helps to anyone needs

System.out.println displays blank line

Why does the below 'System.out.println'(fileEncodedString) display a blank line while the value is there when I debug and I do get an output when I decode the value and print.
byte[] fileContent = readFileToByteArray(filePath);
String fileEncodedString = Base64.getEncoder().encodeToString(fileContent);
byte[] fileDecodedString = Base64.getDecoder().decode(fileEncodedString);
System.out.println("Base64 Decoded File (Basic): " + new String(fileDecodedString, "utf-8"));
private static byte[] readFileToByteArray(String filePath) {
FileInputStream fileInputStream = null;
byte[] bytesArray = null;
try {
File file = new File(filePath);
bytesArray = new byte[(int) file.length()];
// read file into bytes[]
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytesArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bytesArray;
}
Try to use below method for readFileToByteArray and pass correct file path:
static byte[] readFileToByteArray(String filePath) throws IOException {
File file = new File(filePath);
return Files.readAllBytes(file.toPath());
}
its working fine.

FileInputStream issue - App has stopped working

I am having trouble with FileInputStream in Android Studio. My application has stopped working when I use it to read file .txt in the internal memory (I have writen data to this file successfully). I have try many solutions but they didn't work. Can anyone give the solution for this problem? Here is my code. Thanks very much. (I have added users-permission "WRITE_EXTERNAL_STORAGE" and "READ_EXTERNAL_STORAGE").
String fileName = "infoProfile.txt";
private int readData() {
try {
String path = MainActivity.this.getFilesDir().getAbsolutePath() + "/" + fileName;
FileInputStream in = openFileInput(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
ArrayList<String> str = new ArrayList<>();
String data = "";
while ((data = reader.readLine()) != null) {
str.add(data);
}
in.close();
if (str.isEmpty())
return 0;
etName.setText(str.get(0));
etEmail.setText(str.get(1));
etPhone.setText(str.get(2));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}

how to send data to be printed via bluetooth J2ME

can someone please help. i am trying to send data to a thermal printer using bluetooth. i understand how to discover the devices but not able to connect or know how to send the stream of data to be printed. what do I use here ? there is OBEX and RFComm. which one is appropriate. and can you plz share a sample of code to show how to do it, it would be much appreciated.
Below is a sample code that i have found which uses OBEX to search for near by devices and its actually for image transferring. can you plz point out to me the part that are important and how to change this in order to send a stream of Data rather than picture... plz plz help
public class BluetoothImageSender extends MIDlet implements CommandListener{
public Display display;
public Form discoveryForm;
public Form readyToConnectForm;
public Form dataViewForm;
public ImageItem mainImageItem;
public Image mainImage;
public Image bt_logo;
public TextField addressTextField;
public TextField subjectTextField;
public TextField messageTextField;
public Command selectCommand;
public Command exitCommand;
public Command connectCommand;
public List devicesList;
public Thread btUtility;
public String btConnectionURL;
public boolean readData = false;
public long startTime = 0;
public long endTime = 0;
public BluetoothImageSender() {
startTime = System.currentTimeMillis();
display = Display.getDisplay(this);
discoveryForm = new Form("Image Sender");
try{
mainImage = Image.createImage("/btlogo.png");
bt_logo = Image.createImage("/btlogo.png");
} catch (java.io.IOException e){
e.printStackTrace();
}
mainImageItem = new ImageItem("Bluetooth Image Sender", mainImage, Item.LAYOUT_CENTER, "");
discoveryForm.append(mainImageItem);
discoveryForm.append("\nThis application will scan the area for Bluetooth devices and determine if any are offering OBEX services.\n\n");
/// discoveryForm initialization
exitCommand = new Command("Exit", Command.EXIT, 1);
discoveryForm.addCommand(exitCommand);
discoveryForm.setCommandListener(this);
/// devicesList initialization
devicesList = new List("Select a Bluetooth Device", Choice.IMPLICIT, new String[0], new Image[0]);
selectCommand = new Command("Select", Command.ITEM, 1);
devicesList.addCommand(selectCommand);
devicesList.setCommandListener(this);
devicesList.setSelectedFlags(new boolean[0]);
/// readyToConnectForm initialization
readyToConnectForm = new Form("Ready to Connect");
readyToConnectForm.append("The selected Bluetooth device is currently offering a valid OPP service and is ready to connect. Please click on the 'Connect' button to connect and send the data.");
connectCommand = new Command("Connect", Command.ITEM, 1);
readyToConnectForm.addCommand(connectCommand);
readyToConnectForm.setCommandListener(this);
/// dataViewForm initialization
dataViewForm = new Form("File Sending Progress");
dataViewForm.append("Below is the status of the file sending process:\n\n");
dataViewForm.addCommand(exitCommand);
dataViewForm.setCommandListener(this);
}
public void commandAction(Command command, Displayable d) {
if(command == selectCommand) {
btUtility.start();
}
if(command == exitCommand ) {
readData = false;
destroyApp(true);
}
if(command == connectCommand ) {
Thread filePusherThread = new FilePusher();
filePusherThread.start();
display.setCurrent(dataViewForm);
}
}
public void startApp() {
display.setCurrent(discoveryForm);
btUtility = new BTUtility();
}
public void pauseApp() {
}
public void destroyApp(boolean b) {
notifyDestroyed();
}
////////////////
/**
* This is an inner class that is used for finding
* Bluetooth devices in the vicinity.
*/
class BTUtility extends Thread implements DiscoveryListener {
Vector remoteDevices = new Vector();
Vector deviceNames = new Vector();
DiscoveryAgent discoveryAgent;
// obviously, 0x1105 is the UUID for
// the Object Push Profile
UUID[] uuidSet = {new UUID(0x1105) };
// 0x0100 is the attribute for the service name element
// in the service record
int[] attrSet = {0x0100};
public BTUtility() {
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
discoveryAgent = localDevice.getDiscoveryAgent();
discoveryForm.append(" Searching for Bluetooth devices in the vicinity...\n");
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);
} catch(Exception e) {
e.printStackTrace();
}
}
public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass cod) {
try{
discoveryForm.append("found: " + remoteDevice.getFriendlyName(true));
} catch(Exception e){
discoveryForm.append("found: " + remoteDevice.getBluetoothAddress());
} finally{
remoteDevices.addElement(remoteDevice);
}
}
public void inquiryCompleted(int discType) {
if (remoteDevices.size() > 0) {
// the discovery process was a success
// so out them in a List and display it to the user
for (int i=0; i<remoteDevices.size(); i++){
try{
devicesList.append(((RemoteDevice)remoteDevices.elementAt(i)).getFriendlyName(true), bt_logo);
} catch (Exception e){
devicesList.append(((RemoteDevice)remoteDevices.elementAt(i)).getBluetoothAddress(), bt_logo);
}
}
display.setCurrent(devicesList);
} else {
// handle this
}
}
public void run(){
try {
RemoteDevice remoteDevice = (RemoteDevice)remoteDevices.elementAt(devicesList.getSelectedIndex());
discoveryAgent.searchServices(attrSet, uuidSet, remoteDevice , this);
} catch(Exception e) {
e.printStackTrace();
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord){
for(int i = 0; i < servRecord.length; i++) {
DataElement serviceNameElement = servRecord[i].getAttributeValue(0x0100);
String _serviceName = (String)serviceNameElement.getValue();
String serviceName = _serviceName.trim();
btConnectionURL = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
System.out.println(btConnectionURL);
}
display.setCurrent(readyToConnectForm);
readyToConnectForm.append("\n\nNote: the connection URL is: " + btConnectionURL);
}
public void serviceSearchCompleted(int transID, int respCode) {
if (respCode == DiscoveryListener.SERVICE_SEARCH_COMPLETED) {
// the service search process was successful
} else {
// the service search process has failed
}
}
}
////////////////
/**
* FilePusher is an inner class that
* now gets the byte[] named file
* to read the bytes of the file, and
* then opens a connection to a remote
* Bluetooth device to send the file.
*/
class FilePusher extends Thread{
FileConnection fileConn = null;
String file_url = "/loginscreen.png";
byte[] file = null;
String file_name = "loginscreen.png";
String mime_type = "image/png";
// this is the connection object to be used for
// bluetooth i/o
Connection connection = null;
public FilePusher(){
}
public void run(){
try{
InputStream is = this.getClass().getResourceAsStream(file_url);
ByteArrayOutputStream os = new ByteArrayOutputStream();
// now read the file in into the byte[]
int singleByte = 0;
while(singleByte != -1){
singleByte = is.read();
os.write(singleByte);
}
System.out.println("file size: " + os.size());
file = new byte[os.size()];
file = os.toByteArray();
dataViewForm.append("File name: " + file_url);
dataViewForm.append("File size: " + file.length + " bytes");
is.close();
os.close();
} catch (Exception e){
e.printStackTrace();
System.out.println("Error processing the file");
}
try{
connection = Connector.open(btConnectionURL);
// connection obtained
// create a session and a headerset objects
ClientSession cs = (ClientSession)connection;
HeaderSet hs = cs.createHeaderSet();
// establish the session
cs.connect(hs);
hs.setHeader(HeaderSet.NAME, file_name);
hs.setHeader(HeaderSet.TYPE, mime_type); // be sure to note that this should be configurable
hs.setHeader(HeaderSet.LENGTH, new Long(file.length));
Operation putOperation = cs.put(hs);
OutputStream outputStream = putOperation.openOutputStream();
outputStream.write(file);
// file push complete
outputStream.close();
putOperation.close();
cs.disconnect(null);
connection.close();
dataViewForm.append("Operation complete. File transferred");
endTime = System.currentTimeMillis();
long diff = (endTime - startTime)/1000;
System.out.println("Time to transfer file: " + diff);
dataViewForm.append("Time to transfer file: " + diff);
} catch (Exception e){
System.out.println("Error sending the file");
System.out.println(e);
e.printStackTrace();
}
}
}
}

Reading a file in Blackberry

I am trying to read content from file in blackberry and i read the file content to result object and when i am trying to print the result object it gives error and the file is in res folder,and this is code that i got problem
private String readTextFile(String fName) {
String result = null;
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
is = fconn.openDataInputStream();
byte[] data = IOUtilities.streamToBytes(is);
result = new String(data);
System.out.println("result data is ...... "+result);
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (null != is)
is.close();
if (null != fconn)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return result;
}
what is fName here ?
The file name or the path could cause similar problem.

Resources