Itextpdf: The document has no pages error - android

I have a problem with making a pdf file in my android app using ITextPdf. I'm trying to convert a MPAndroidChart linechart to a bitmap and save it to a pdf file.
Here's the code for saveToPdf() method:
private void saveToPdf() {
Bitmap bitmap = saveChartToBitmap();
Document doc = new Document();
File pdfCreated = new File(getBaseContext().getFilesDir() , "PDFCreated.pdf");
try {
PdfWriter.getInstance(doc, new FileOutputStream(pdfCreated));
doc.open();
Image image = Image.getInstance(bitmap);
doc.newPage();
doc.add(image);
Toast.makeText(getBaseContext(), "Pdf created", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException | DocumentException e) {
e.printStackTrace();
} finally {
doc.close();
}
And my saveChartToBitmap() method:
private Bitmap saveChartToBitmap() {
if (lineChart.getMeasuredHeight() <= 0) {
lineChart.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
Bitmap b = Bitmap.createBitmap(lineChart.getMeasuredWidth(), lineChart.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
lineChart.layout(0, 0, lineChart.getMeasuredWidth(), lineChart.getMeasuredHeight());
lineChart.draw(c);
return b;
} else {
return null;
}
}
Don't know if something with my conversion to bitmat or creating an Image object is wrong but can't figure it out. I get: The document has no pages error. So I need advice.
Thanks in advance.

Immediately after opening document, always add an empty chunk to document so that you can avoid this exception.
doc.open;
doc.add(new Chunk(''));

Check if your saveChartToBitmap() method returns null. Also did you see the toast message.

I solved my problem. Instead of passing the bitmap to the Image.getInstance() method as an argument I converted it to a byte array and now It's working. Thanks

Related

How to take the screen-shot of the current video frame in the videoView android?

I am using the video-view to play media and I want to take the screen shot of the current frame. I found some solutions which include using mediaMetaDataRetriever but that method is way too slow and does not perform well in many cases.
I can not use media player over texture view to capture view I knew that approach, because I need by default media controls in my app.
Is there any way to make that process fast?
My CODE:
public Bitmap getBitmapVideoView(){
MediaMetadataRetriever mediaMetadataRetriever;
mediaMetadataRetriever = new MediaMetadataRetriever();
try {
int currentPosition =videoView.getCurrentPosition();
mediaMetadataRetriever.setDataSource(getVideoURL(),new HashMap<String, String>());
Bitmap bitmap = mediaMetadataRetriever.getFrameAtTime(currentPosition*1000);
if (bitmap != null) {
// Canvas canvas = new Canvas(bitmap);
// textureview.draw(canvas);
return bitmap;
}
else{
return null;
}
}
catch (Exception e){
Log.i("Errorrr",e.getMessage());
return null;
}
finally {
try {
mediaMetadataRetriever.release();
}
catch (Exception e){
e.printStackTrace();
}
}
}
Approach:
Bitmap bitmap = Screenshot.INSTANCE.with((MainActivity)activity).setView(findViewById(R.id.relative)).setQuality(Quality.HIGH).getScreenshot();
LayoutInflater inflater = getLayoutInflater();
Toast toastShot = null;
View layout = inflater.inflate(R.layout.layout, (ViewGroup) findViewById(R.id.screen));
ImageView image = (ImageView) layout.findViewById(R.id.shot_image);
image.setImageBitmap(bitmap);
toastShot = new Toast(getApplicationContext());
toastShot.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toastShot.setDuration(Toast.LENGTH_LONG);
toastShot.setView(layout);
toastShot.show();
For taking screenshot you can use this library
implementation 'com.github.MindorksOpenSource:screenshot:v0.0.1'
And for taking screenshot just call this function on button click or any other event
var b = Screenshot.with(activity!!).setView(rl_imageText).setQuality(Quality.HIGH).getScreenshot()
Note: rl_imageText = This is the id of my xml relative layout of which i am taking screenshot.
It will provide you the bitmap of the screenshot and for saving it into the storage or getting path use the below mentioned function
private fun getImageUriFromBitmap(context: Context, bitmap: Bitmap): Uri {
val bytes = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path = MediaStore.Images.Media.insertImage(context.contentResolver, bitmap,"Title",null)
return Uri.parse(path.toString())
}
Note: Please mention if it will not work so that i will provide you other solution.

Android. How to load the picture from memory knowing its full path?

I saved the picture on phone from application. I found a file manager it and I made sure that it really remained. Further I try to load on its full path it by BitmapFactory.decodeFile() method transferring a full path to the picture, a way to pictures at me such there, I will give an example from application:
/storage/emulated/0/Android/data/com .example.home.page/files/2015218161530.jpg
But me jumps out Exception, what decoding is impossible since the file isn't found, what for nonsense? Thanks in advance
You can use this method this will work for you
just pass path of images(where your image is store and object reference of you ImageView as a second argument)
1st argument Path of images want ot display
2nd argument object reference of `ImageView`
public static void ShowPicture(String filePath, ImageView pic) {
File f = new File(filePath);
FileInputStream is = null;
try {
is = new FileInputStream(f);
} catch (FileNotFoundException e) {
Log.d("error: ",String.format( "ShowPicture.java file[%s]Not Found",fileName));
return;
}
Bitmap = BitmapFactory.decodeStream(is, null, null);
pic.setImageBitmap(bm);
}
please also put this permission in manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
try below code that might help you.
File f = new File(PathToFiles +yourFileName);
if (f.exists()) {
Drawable d = Drawable.createFromPath(f.getPath());
imageview.setImageDrawable(d);
}

how to capture listview data as Jpg image

i need to capture listview data and convert it into jpg or png image format , then saved into sd card. I captured only the data which is visible in the screen , but i am unable to capture the data which is avaialble in the scrollview.
So, please guide me guide me how to implement this.
i am using the following code to capture the visible data.
View v1=btnCapture.getRootView();
public void gettingRootView(View v1)
{
if( v1 != null)
{
v1.setDrawingCacheEnabled(true);
v1.buildDrawingCache();
Bitmap bm = v1.getDrawingCache();
try
{
if ( bm != null )
{
Log.e("file","filepath");
savePhoto(bm);
}
}
catch(Exception e){e.printStackTrace();}
}
}
public void savePhoto(Bitmap bmp)
{
Log.e("save photo","save photo");
File fileFolder=new File(Environment.getExternalStorageDirectory(),"SMSREADING");
fileFolder.mkdir();
Calendar c=Calendar.getInstance();
try
{
File fileName=new File(fileFolder,c.getTimeInMillis()+".jpg");
FileOutputStream output=new FileOutputStream(fileName);
bmp.compress(Bitmap.CompressFormat.PNG,100,output);
}
catch(Exception ex){
ex.printStackTrace();
}
}
You can create HTML from your data using one of the many templating libraries out there like, if you have a String list Apache's Velocity might work well. After you create your HTML you can use java-html2image to convert your html to an image.

Getting images from a string path to be viewed in an imageview

I have some picture paths stored in a datastore and i am trying to convert them into drawables and display the in my image view, for some reason im getting a null pointer exception. Can someone please help me? Thanks
String pathName = selectedPlayer.getPicture();
Toast.makeText(this, pathName, Toast.LENGTH_SHORT).show();
Drawable d = Drawable.createFromPath(pathName);
imageView.setImageDrawable(d);
You must check file name is not null
then check that first if file exists or not
if(pathName!=null && pathName!="") <--CHECK FILENAME IS NOT NULL
{
File f = new File(pathName);
if(f.exists()) <-- CHECK FILE EXISTS OR NOT
{
Drawable d = Drawable.createFromPath(pathName);
imageView.setImageDrawable(d);
}
}
EDIT :
You have to initialize your imageview first like
imageView=(ImageView)findViewById(R.id.yourimageviewid);
Look at imageView it should not be null.
And after that try this :
bm = null;
try {
bm = BitmapFactory.decodeFile(imageView);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
imageView.setImageBitmap(bm);

creating a drawable from sd card to set as a background in android

I am trying to use an image from the sd card and set it as the background for a relativelayout. I have tried other solutions that i have found here and elsewhere but they havent seemed to work for me. here is my code. I have commented out other ways that i have tried and didnt work. the only thing that worked for me was using setBackgroudnResource and using a resource from the app, but this was just to test to make sure mRoot was set up correctly. when I have tried all the other ways, it just doesn't set anything. Anyone know what I am doing wrong, or if there is a better way to do this?
//one way i tired...
//String extDir = Environment.getExternalStorageDirectory().toString();
//Drawable d = Drawable.createFromPath(extDir + "/pic.png");
//mRoot.setBackgroundDrawable(d);
//another way tried..
//Drawable d = Drawable.createFromPath("/sdcard/pic.png");
//mRoot.setBackgroundDrawable(d);
//last way i tried...
mRoot.setBackgroundDrawable(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), "pic.png").getAbsolutePath()));
//worked, only to verify mRoot was setup correctly and it could be changed
//mRoot.setBackgroundResource(R.drawable.bkg);
You do not load a drawable from SD card but a bitmap. Here is a method to load it with the reduced sampling (quality) so the program will not complain if the image is too large. Then I guess you need to process this bitmap i.e. crop it and resize for the background.
// Read bitmap from Uri
public Bitmap readBitmap(Uri selectedImage) {
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; //reduce quality
AssetFileDescriptor fileDescriptor =null;
try {
fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage,"r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally{
try {
bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
fileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bm;
}
The Uri here can be supplied from a gallery picker activity.
The image then can be saved into application resources and loaded into an imageView
private void saveBackground(Bitmap Background) {
String strBackgroundFilename = "background_custom.jpg";
try {
Background.compress(CompressFormat.JPEG, 80, openFileOutput(strBackgroundFilename, MODE_PRIVATE));
} catch (Exception e) {
Log.e(DEBUG_TAG, "Background compression and save failed.", e);
}
Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(BackgroundSettings.this.getFilesDir(), strBackgroundFilename));
// Load this image
Bitmap bitmapImage = BitmapFactory.decodeFile(imageUriToSaveCameraImageTo.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
//show it in a view
ImageView backgroundView = (ImageView) findViewById(R.id.BackgroundImageView);
backgroundView.setImageURI(null);
backgroundView.setImageDrawable(bgrImage);
}
File file = new File( url.getAbsolutePath(), imageUrl);
if (file.exists()) {
mDrawable = Drawable.createFromPath(file.getAbsolutePath());
}
I suggest checking that the drawable is being loaded correctly. Some things to try:
Try using a different image on the sd card
Put pic.png in R.drawable and make sure mRoot.setBackgroundResource() does what you expect
After loading the drawable, check d.getBounds() to make sure it is what you expect

Categories

Resources