Using Java itextPdf pdf file is not being printed in android - java

I am writing a mobil application which contains Dynamic Report part. I'm making it with Java ItextPdf Library but when I sent it to printer printer don't accept my file and giving a notification "File Type is not supported by this device." But When I send normal pdf file which is created by pc it is printing.
Printing Class
PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
// Set job name, which will be displayed in the print queue
String jobName = " Document";
// Start a print job, passing in a PrintDocumentAdapter implementation
// to handle the generation of a print document
File path = context.getFilesDir();
File file = new File(path,"ss.pdf");
FileOutputStream os = null;
FileInputStream is = null;
try {
os = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Adisyon a = new Adisyon(os);
a.createFile();
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
printManager.print(jobName, new printAdapter(Siparis.this,is),
PrintAdapter Class
#TargetApi(Build.VERSION_CODES.KITKAT)
public class printAdapter extends PrintDocumentAdapter
{
Context context;
InputStream input;
public printAdapter(Context context,FileInputStream input)
{
this.context = context;
this.input = input;
}
#Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
OutputStream output = null;
try {
output = new FileOutputStream(destination.getFileDescriptor());
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
} catch (FileNotFoundException ee){
//Catch exception
} catch (Exception e) {
//Catch exception
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("deneme.txt").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();
callback.onLayoutFinished(pdi, true);
}
}
Itext Class
public class Adisyon {
FileOutputStream stream;
Context appContext = LoginActivity.getContextOfApplication();
public Adisyon(FileOutputStream stream) {
this.stream = stream;
}
public void createFile() {
try {
Document document = new Document();
PdfWriter.getInstance(document, stream);
document.open();
//addMetaData(document);
//addTitlePage(document);
//addContent(document);
createAdisyon(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
...

Related

download image from unformatted url [duplicate]

This question already has answers here:
How to download and save an image in Android
(10 answers)
Closed 3 years ago.
I want to download an image from url. if the url does not have an image format at the end of the link? Example of url:
https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=1937530436393797&height=200&width=200&ext=1579152762&hash=AeQEq164H_oXIMjx
Try this code :
Create LocalImageSaver.java :
public class LocalImageSaver extends AsyncTask<Void, String, Boolean> {
private final SaveCompletionInterface saveCompletionInterface;
private final String originalImageUrl;
private final Context context;
private String savedImagePath;
private String fUrl;
public LocalImageSaver(Context context, String originalImageUrl, SaveCompletionInterface saveCompletionInterface) {
this.context = context;
this.saveCompletionInterface = saveCompletionInterface;
this.originalImageUrl = originalImageUrl;
}
/**
* Downloading file in background thread
*/
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected Boolean doInBackground(Void... f_url) {
this.fUrl = originalImageUrl;
FileOutputStream output = null;
InputStream is = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(fUrl);
HttpContext context = new BasicHttpContext();
HttpResponse response = client.execute(get, context);
is = response.getEntity().getContent();
int status = response.getStatusLine().getStatusCode();
if (status == 200 && is != null) {
String imageNameToSave;
String extension = originalImageUrl.substring(originalImageUrl.lastIndexOf(".") + 1); // Without dot jpg, png
if (extension.contains("mp4")) {
extension = "mp4";
}
String fileName = "";//originalImageUrl.substring(originalImageUrl.lastIndexOf("/") + 1); // Without dot jpg, png
fileName = "05Media_" + Calendar.getInstance().getTimeInMillis() + "." + extension;
imageNameToSave = fileName;
Uri savedImagePathUri = CommonImageUtil.createImageFile(imageNameToSave);
savedImagePath = savedImagePathUri.getPath();
// Output stream to write file
output = new FileOutputStream(savedImagePathUri.getPath());
int read = 0;
byte[] buffer = new byte[32768];
while ((read = is.read(buffer)) > 0) {
output.write(buffer, 0, read);
}
// flushing output
output.flush();
// closing streams
output.close();
is.close();
return true;
}
} catch (ClientProtocolException e) {
Lg.printStackTrace(e);
} catch (IOException e) {
Lg.printStackTrace(e);
} catch (Exception e) {
Lg.printStackTrace(e);
} finally {
// flushing output
try {
if (output != null) {
output.flush();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
Lg.printStackTrace(e);
}
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
saveCompletionInterface.onSaved(result, savedImagePath);
}
public interface SaveCompletionInterface {
public void onSaved(boolean result, String imageNameToSave);
}
}
and call this :
LocalImageSaver localImageSaver = new LocalImageSaver(getActivity(), url, new LocalImageSaver.SaveCompletionInterface() {
#Override
public void onSaved(boolean result, String savedImagePath) {
if (result) {
//showToast(getActivity(), (R.string.image_save_succesfull));
// refresh gallery
try {
MediaScannerConnection.scanFile(getActivity(), new String[]{savedImagePath}, null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
}
} else {
//showToast(getActivity(), (R.string.error_saving_image));
}
}
});
localImageSaver.execute();

Reading and Writing External Storage file From Background Not Working Android

In my App I am using FirebaseMessagingService under which I am receiving the notification, For these notifications I am creating a log in the external storage, When My app is in running mode, The logs are getting created perfectly, but after the app has been killed, the logs are not getting created, but the notification are coming. I don't understand what's the problem, In logcat also am not getting any exception.
public class MyAndroidFirebaseMsgService extends FirebaseMessagingService {
public String message = null;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
message=remoteMessage.getNotification().getBody();
if(message.contains("Text")){
try {
intent1 = new Intent(this, ResultActivity.class);
intent1.putExtra("TextData", message);
intent1.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT );
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setDefaults(Notification.DEFAULT_ALL);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(message);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
try {
File file = new File(getExternalFilesDir("MyStorage"),strNotificationFileName);
if (file.exists())
{
IsFileExist=true;
strNotificationFileName=file.getPath();
}
else
{
IsFileExist=true;
try{
file.createNewFile();
strNotificationFileName=file.getPath();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
catch (Exception ex)
{
}
try {
ArrayList<Object> listNotificationread=readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
UpdateNotificationList("Text");
}catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}
}
public ArrayList<Object> readObject() throws ClassNotFoundException, IOException {
File file = new File(getExternalFilesDir("MyStorage"),"Notification.xml");
if (file.exists()) {
}
listNotification = new ArrayList();
//Create new FileInputStream object to read file
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
//Create new ObjectInputStream object to read object from file
ObjectInputStream obj = new ObjectInputStream(fis);
try {
while (fis.available() != -1) {
//Read object from file
NotificationSavedList acc = (NotificationSavedList) obj.readObject();
listNotification.add(acc);
}
} catch (EOFException ex) {
System.out.println(ex.getMessage());
}
//Collections.reverse(listNotification);
return listNotification;
}
public void writeObject(ArrayList<Object> listNotification) throws IOException {
File file = new File(getExternalFilesDir("MyStorage"),"Notification.xml");
//Create FileOutputStream to write file
FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
//Create ObjectOutputStream to write object
ObjectOutputStream objOutputStream = new ObjectOutputStream(fos);
//Write object to file
for (Object obj : listNotification) {
objOutputStream.writeObject(obj);
objOutputStream.reset();
}
objOutputStream.close();
}
public void UpdateNotificationList(String type) {
try {
try {
if (listNotification.size() > 20) {
listNotification.remove(0);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
String parsedDate = formatter.format(currentTime);
NotificationSavedList _NotificationSavedList = new NotificationSavedList(listNotification.size()+1, type, message, parsedDate);
listNotification.add(_NotificationSavedList);
writeObject(listNotification);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}

Uploading files to Parse database

I want to add a feature to my app in which the users can upload files (PDF files) from their mobile to the database, then download this file back to the app and display it.
I have no idea how to start doing this and what is the right code to use.
I tried using this code,
ParseObject pObject = new ParseObject("ExampleObject");
pObject.put("myNumber", number);
pObject.put("myString", name);
pObject.saveInBackground(); // asynchronous, no callback
- EDIT -
I tried this code but the app crashes when I click the button:
public class Test extends Activity {
Button btn;
File PDFFile;
ParseObject po;
String userPDFFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
po = new ParseObject("pdfFilesUser");
btn = (Button) findViewById(R.id.button);
PDFFile = new File("res/raw/test.pdf");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadPDFToParse(PDFFile, po, userPDFFile);
}
});
}
private ParseObject uploadPDFToParse(File PDFFile, ParseObject po, String columnName){
if(PDFFile != null){
Log.d("EB", "PDFFile is not NULL: " + PDFFile.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(PDFFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read;
byte[] buff = new byte[1024];
try {
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] pdfBytes = out.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile(PDFFile.getName() , pdfBytes);
po.put(columnName, file);
// Upload the file into Parse Cloud
file.saveInBackground();
po.saveInBackground();
}
return po;
}
}
You can upload a file manually via REST API. Take a look at this docs here
Can try this code:
private ParseObject uploadPDFToParse(File PDFFile, ParseObject po, String columnName){
if(PDFFile != null){
Log.d("EB", "PDFFile is not NULL: " + PDFFile.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(PDFFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read;
byte[] buff = new byte[1024];
try {
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] pdfBytes = out.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile(PDFFile.getName() , pdfBytes);
po.put(columnName, file);
// Upload the file into Parse Cloud
file.saveInBackground();
po.saveInBackground();
}
return po;
}
For more details check this
I would strongly suggest you quickly get up to speed with the Parse Java development wiki.
To answer your question. You want to be using:
byte[] data = "Working at Parse is great!".getBytes();
ParseFile file = new ParseFile("resume.txt", data);
file.saveInBackground();
First declare your file etc then save it using that. But once again, first read the guidelines to better understand the framework you working with.
https://parseplatform.github.io/docs/android/guide/

Decrypt AES256 encrypted file and save it in the phone

I'm downloading a file that is stored on a remote server, I try to decrypt it using JNCryptor, and all goes well except that the file I have downloaded and store in the phone external storage is corrupted and I cannot open it. Can anyone tell me where im going wrong?
Im trying to get the InputStream from the file, decrypt it, and save the file on external storage.
Thanks
Here is my code:
private void downloadFile() {
final String FILE_URL = "https://www.google.com";
final String PASS = "password";
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
Log.d(TAG, "starting");
JNCryptor cryptor = new AES256JNCryptor();
int count;
try {
URL url = new URL(FILE_URL);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
//decrypt istream
byte[] b = null;
byte[] data = null;
try {
b = new byte[input.available()];
input.read(b);
} catch (IOException e) {
Log.i("decrypt error", e.toString());
}
AES256JNCryptorOutputStream cryptorStream = null;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try {
cryptorStream = new AES256JNCryptorOutputStream(byteStream,
PASS.toCharArray());
} catch (CryptorException e) {
e.printStackTrace();
}
try {
cryptorStream.write(b);
cryptorStream.flush();
cryptorStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
byte[] encrypted = byteStream.toByteArray();
try {
data = cryptor.decryptData(encrypted, PASS.toCharArray());
Log.d(TAG, "decrypted");
} catch (InvalidHMACException e) {
e.printStackTrace();
} catch (CryptorException e) {
e.printStackTrace();
}
if (data != null) {
Log.d(TAG, "data is ok");
}
//end decryption
// Output stream
//test
FileOutputStream fos = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/temp.zip");
fos.write(data);
fos.close();
Log.d(TAG, "file saved ");
input.close();
Log.d(TAG, "done");
} catch (Exception e) {
Log.d(TAG, "Error: " + e.getMessage());
}
return null;
}
}.execute();
}
P.S. Im not getting any error or warning in logCat.

getting blank pdf on implementing pdf reader in project

i am trying to implement a pdf reader via a pdf library from git hub https://github.com/jblough/Android-Pdf-Viewer-Library but when i implement the code.. all i am getting is a blank page.. the url is correct the pdf has content and this is similar to this q .. Example of code to implement a PDF reader
my code consist of multiple methods, the main method is used to select the which pdf should be chosen to display. then the pdf name is passed on to method "copyreadassets"
public void CopyReadAssets(String url) {
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getApplicationContext().getFilesDir(), url);
try {
in = assetManager.open(url);
out = getApplicationContext().openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = "file://" + getApplicationContext().getFilesDir() + "/"+url;
openPdfIntent(path); }
the openpdfintentmethod is used to open the values
private void openPdfIntent(String path) {
// TODO Auto-generated method stub
try {
final Intent intent = new Intent(Question_Point_Main.this, Pdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
pdf.class contains the following..
public class Pdf extends Activity{
public int getPreviousPageImageResource() {
return R.drawable.left_arrow; }
public int getNextPageImageResource() {
return R.drawable.right_arrow; }
public int getZoomInImageResource() {
return R.drawable.zoom_in; }
public int getZoomOutImageResource() {
return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() {
return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() {
return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() {
return R.id.etPassword; }
public int getPdfPasswordOkButton() {
return R.id.btOK; }
public int getPdfPasswordExitButton() {
return R.id.btExit; }
public int getPdfPageNumberEditField() {
return R.id.pagenum_edit; }
}
In your AndroidManifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<activity android:name="com.example.readassetpdf.myPDFActivity"></activity>
in your case activity is pdf class
<activity android:name="com.example.readassetpdf.pdf"></activity>
and use following method
public void CopyReadAssets(String url) {
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getApplicationContext().getFilesDir(), url);
try {
in = assetManager.open(url);
//out = getApplicationContext().openFileOutput(file.getName(),
//Context.MODE_WORLD_READABLE);
out=new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf");
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf";
openPdfIntent(path);
}
and call it as below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
CopyReadAssets("mypdf.pdf");
}
And the function copyfile is as below
private void copyFile(InputStream in, OutputStream out) throws IOException{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
The replacement is
out = getApplicationContext().openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
to
out=new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf");

Categories