Android API PdfDocument not writing data in file using writeTo(outputStream) - android

Button for creating pdf file
//button listener for creating pdf file
convert2PDF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//pdf document created
PdfDocument document = new PdfDocument();
//pageinfo created
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(800, 800, 1).create();
//page created based on pageinfo
PdfDocument.Page page = document.startPage(pageInfo);
//ImageView used to draw bitmap on page's canvas
ImageView imageView = new ImageView(context);
//setting imageView height weight equal to page height weight
imageView.setMaxHeight(800);
imageView.setMaxWidth(800);
//setting the imageView to bitmap selected from list
imageView.setImageBitmap(BitmapFactory.decodeFile(selectedFileList.get(0).getPath()));
//imageView drawn on canvas
imageView.draw(page.getCanvas());
//page finished
document.finishPage(page);
File result = null;
try {
result = File.createTempFile("afew", ".pdf",
context.getCacheDir());
//writing the pdf doc to temp file
document.writeTo(new BufferedOutputStream(new
FileOutputStream(result)));
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),Toast.LENGTH_SHORT).show();
}
document.close();
//main file
File a = new File("/storage/sdcard/b.pdf");
//funct transfer used for transferring bytes from one file to another
transfer(result, a);
//set content of layout with imageView
context.setContentView(imageView);
}});
**I tried running above code but the file created at /storage/sdcard/b.pdf is empty always **
i searched through many answers here but none of them worked
is there anyway i can resolve this issue plz help

wow 3 days & found answer
protected File doInBackground(ArrayList<File>... params) {
File output = null;
PdfDocument doc = new PdfDocument();
ArrayList<Bitmap> images = new ArrayList<Bitmap>();
PdfDocument.Page page = null;
ArrayList<Bitmap> bitmaps = null;
Canvas canvas = null;
File outputDir = new File(getFilesDir()+"/Output/PDF");
if(!outputDir.exists()){
outputDir.mkdirs();
}
Random rand = new Random();
output = new File(getFilesDir()+"/Output/PDF/data-"+rand.nextInt()+".pdf");
for(File a: params[0]){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(a.getPath(), options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
Bitmap b = decodeSampledBitmapFromResource(a, imageWidth/2, imageHeight/2);
if(b!=null){
images.add(b);
}
}
int i = 0;
for(Bitmap a: images){
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(a.getWidth(), a.getHeight(), i++).create();
page = doc.startPage(pageInfo);
page.getCanvas().drawBitmap(a, 0, 0, new Paint(Paint.ANTI_ALIAS_FLAG));
doc.finishPage(page);
}
try{
FileOutputStream out = new FileOutputStream(output);
doc.writeTo(out);
out.flush();
out.close();
}catch(FileNotFoundException e){}
catch(IOException e){}
doc.close();
return output;
}

Related

Taking Screenshot of Webview in above api 21

I am trying screenshot of webview in above Api 21 and it only capture content from webview that is visible on screen, other part is also getting captured but without any content. Means it shows white space.
I am using below code for taking screenshot.
public static String getScreenShotOf(View view, Context context) {
try {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return storeImage(context, bitmap);
}
catch (Exception e) {
UtillsG.showToast("Error while taking screenshot.", context, false);
}
return null;
}
This things works perfectly in LOLLIPOP or below versions.
See screenshot of kitkat and marshmallow devices.
Can anybody help me out for this?
Any support will be appreciated.
You can use root layout as webview and try with below code.
public Bitmap takeScreenshot() {
View rootView = getWindow().getDecorView().findViewById(R.id.PP_Ll);
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/Folder");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "Photo-" + n + ".jpg";
File file = new File(newDir, fotoname);
if (file.exists())
file.delete();
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
Toast.makeText(getApplicationContext(),
"Saved in folder: 'Folder'", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

getWidth must be called from UI thread

getWidth must be called from UI thread..How do i fix it??Im trying to create pdf file..but getWidth,getHeight and getCanvas is coming up errors!!!
private class PdfGenerationTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
PdfDocument document = new PdfDocument();
// repaint the user's text into the page
View content = findViewById(R.id.pdf_content);
// crate a page description
int pageNumber = 1;
PageInfo pageInfo = new PageInfo.Builder(content.getWidth(),
content.getHeight() - 20, pageNumber).create();
// create a new page from the PageInfo
Page page = document.startPage(pageInfo);
content.draw(page.getCanvas());
// do final processing of the page
document.finishPage(page);
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss");
String pdfName = "pdfdemo"
+ sdf.format(Calendar.getInstance().getTime()) + ".pdf";
File outputFile = new File("/sdcard/PDFDemo_AndroidSRC/", pdfName);
try {
outputFile.createNewFile();
OutputStream out = new FileOutputStream(outputFile);
document.writeTo(out);
document.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return outputFile.getPath();
}
You can get the dimension of your screen like that:
Display display = getWindowManager().getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
But it seems to be deprecated. Get it like that now:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenWidth = metrics.heightPixels;
int screenHeight = metrics.widthPixels;
Implement onPreExecute of AsyncTask and Do the calling of getHeight,getWidth and getCanvas
private class PdfGenerationTask extends AsyncTask<Void, Void, String> {
#Override
protected String onPreExecute(Void params){
this.height=getHeight();
this.width=getWidth();
}
#Override
protected String doInBackground(Void... params) {
PdfDocument document = new PdfDocument();
// repaint the user's text into the page
View content = findViewById(R.id.pdf_content);
// crate a page description
int pageNumber = 1;
PageInfo pageInfo = new PageInfo.Builder(content.getWidth(),
content.getHeight() - 20, pageNumber).create();
// create a new page from the PageInfo
Page page = document.startPage(pageInfo);
content.draw(page.getCanvas());
// do final processing of the page
document.finishPage(page);
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss");
String pdfName = "pdfdemo"
+ sdf.format(Calendar.getInstance().getTime()) + ".pdf";
File outputFile = new File("/sdcard/PDFDemo_AndroidSRC/", pdfName);
try {
outputFile.createNewFile();
OutputStream out = new FileOutputStream(outputFile);
document.writeTo(out);
document.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return outputFile.getPath();
}
AsyncTask runs on Different Thread and UI operations happens on Main Thread so you can't get UI related info from different Thread. You have to pass UI related data to your AsyncTask and have work done.
In your Activity's onCreate() method get dimensions like this
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenWidth = metrics.heightPixels;
int screenHeight = metrics.widthPixels;
Canvas canvas = page.getCanvas();
and pass this to your asyncTask as follows
PdfGenerationTask pdfGenerationTask = new PdfGenerationTask(screenWidth, screenHeight, canvas);
pdfGenerationTask.execute();
and update your PdfGenerationTask class as follows
private class PdfGenerationTask extends AsyncTask<Void, Void, String> {
int width, height;
Canvas canvas;
PdfGenerationTask(int width, int height, Canvas canvas) {
this.width = width;
this.height = height;
this.canvas = canvas;
}
#Override
protected String doInBackground(Void... params) {
PdfDocument document = new PdfDocument();
// repaint the user's text into the page
View content = findViewById(R.id.pdf_content);
// crate a page description
int pageNumber = 1;
PageInfo pageInfo = new PageInfo.Builder(width,
height - 20, pageNumber).create();
// create a new page from the PageInfo
Page page = document.startPage(pageInfo);
content.draw(canvas);
// do final processing of the page
document.finishPage(page);
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss");
String pdfName = "pdfdemo"
+ sdf.format(Calendar.getInstance().getTime()) + ".pdf";
File outputFile = new File("/sdcard/PDFDemo_AndroidSRC/", pdfName);
try {
outputFile.createNewFile();
OutputStream out = new FileOutputStream(outputFile);
document.writeTo(out);
document.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return outputFile.getPath();
}

how to create and save a screenshot from a surfaceview?

I have an app that I want to be able to capture a screenshot
Here is my code :
public class Screenshot {
private final View view;
/** Create snapshots based on the view and its children. */
public Screenshot(View root) {
this.view = root;
}
/** Create snapshot handler that captures the root of the whole activity. */
public Screenshot(Activity activity) {
final View contentView = activity.findViewById(android.R.id.content);
this.view = contentView.getRootView();
}
/** Take a snapshot of the view. */
public Bitmap snap() {
Bitmap bitmap = Bitmap.createBitmap(this.view.getWidth(), this.view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
}
but the contents of the surfaceView is saved as black.!!!
Please help me, Thanks...
I hope you have used this solution which was posted here Get screenshot of surfaceView in Android
this thing is explained here Take Screenshot of SurfaceView
The SurfaceView's surface is independent of the surface on which View elements are drawn. So capturing the View contents won't include the SurfaceView.........
I hope this Taking screenshot programmatically doesnt capture the contents of surfaceVIew code can help you out more
public class Cam_View extends Activity implements SurfaceHolder.Callback {
protected static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
private SurfaceView SurView;
private SurfaceHolder camHolder;
private boolean previewRunning;
final Context context = this;
public static Camera camera = null;
private RelativeLayout CamView;
private Bitmap inputBMP = null, bmp, bmp1;
private ImageView mImage;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
CamView = (RelativeLayout) findViewById(R.id.camview);//RELATIVELAYOUT OR
//ANY LAYOUT OF YOUR XML
SurView = (SurfaceView)findViewById(R.id.sview);//SURFACEVIEW FOR THE PREVIEW
//OF THE CAMERA FEED
camHolder = SurView.getHolder(); //NEEDED FOR THE PREVIEW
camHolder.addCallback(this); //NEEDED FOR THE PREVIEW
camHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//NEEDED FOR THE PREVIEW
camera_image = (ImageView) findViewById(R.id.camera_image);//NEEDED FOR THE PREVIEW
Button btn = (Button) findViewById(R.id.button1); //THE BUTTON FOR TAKING PICTURE
btn.setOnClickListener(new OnClickListener() { //THE BUTTON CODE
public void onClick(View v) {
camera.takePicture(null, null, mPicture);//TAKING THE PICTURE
//THE mPicture IS CALLED
//WHICH IS THE LAST METHOD(SEE BELOW)
}
});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,//NEEDED FOR THE PREVIEW
int height) {
if(previewRunning) {
camera.stopPreview();
}
Camera.Parameters camParams = camera.getParameters();
Camera.Size size = camParams.getSupportedPreviewSizes().get(0);
camParams.setPreviewSize(size.width, size.height);
camera.setParameters(camParams);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning=true;
} catch(IOException e) {
e.printStackTrace();
}
}
public void surfaceCreated(SurfaceHolder holder) { //NEEDED FOR THE PREVIEW
try {
camera=Camera.open();
} catch(Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
finish();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) { //NEEDED FOR THE PREVIEW
camera.stopPreview();
camera.release();
camera=null;
}
public void TakeScreenshot(){ //THIS METHOD TAKES A SCREENSHOT AND SAVES IT AS .jpg
Random num = new Random();
int nu=num.nextInt(1000); //PRODUCING A RANDOM NUMBER FOR FILE NAME
CamView.setDrawingCacheEnabled(true); //CamView OR THE NAME OF YOUR LAYOUR
CamView.buildDrawingCache(true);
Bitmap bmp = Bitmap.createBitmap(CamView.getDrawingCache());
CamView.setDrawingCacheEnabled(false); // clear drawing cache
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 100, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream fis = new ByteArrayInputStream(bitmapdata);
String picId=String.valueOf(nu);
String myfile="Ghost"+picId+".jpeg";
File dir_image = new File(Environment.getExternalStorageDirectory()+//<---
File.separator+"Ultimate Entity Detector"); //<---
dir_image.mkdirs(); //<---
//^IN THESE 3 LINES YOU SET THE FOLDER PATH/NAME . HERE I CHOOSE TO SAVE
//THE FILE IN THE SD CARD IN THE FOLDER "Ultimate Entity Detector"
try {
File tmpFile = new File(dir_image,myfile);
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
Toast.makeText(getApplicationContext(),
"The file is saved at :SD/Ultimate Entity Detector",Toast.LENGTH_LONG).show();
bmp1 = null;
camera_image.setImageBitmap(bmp1); //RESETING THE PREVIEW
camera.startPreview(); //RESETING THE PREVIEW
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private PictureCallback mPicture = new PictureCallback() { //THIS METHOD AND THE METHOD BELOW
//CONVERT THE CAPTURED IMAGE IN A JPG FILE AND SAVE IT
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File dir_image2 = new File(Environment.getExternalStorageDirectory()+
File.separator+"Ultimate Entity Detector");
dir_image2.mkdirs(); //AGAIN CHOOSING FOLDER FOR THE PICTURE(WHICH IS LIKE A SURFACEVIEW
//SCREENSHOT)
File tmpFile = new File(dir_image2,"TempGhost.jpg"); //MAKING A FILE IN THE PATH
//dir_image2(SEE RIGHT ABOVE) AND NAMING IT "TempGhost.jpg" OR ANYTHING ELSE
try { //SAVING
FileOutputStream fos = new FileOutputStream(tmpFile);
fos.write(data);
fos.close();
//grabImage();
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
String path = (Environment.getExternalStorageDirectory()+
File.separator+"Ultimate EntityDetector"+
File.separator+"TempGhost.jpg");//<---
BitmapFactory.Options options = new BitmapFactory.Options();//<---
options.inPreferredConfig = Bitmap.Config.ARGB_8888;//<---
bmp1 = BitmapFactory.decodeFile(path, options);//<--- *********(SEE BELOW)
//THE LINES ABOVE READ THE FILE WE SAVED BEFORE AND CONVERT IT INTO A BitMap
camera_image.setImageBitmap(bmp1); //SETTING THE BitMap AS IMAGE IN AN IMAGEVIEW(SOMETHING
//LIKE A BACKGROUNG FOR THE LAYOUT)
tmpFile.delete();
TakeScreenshot();//CALLING THIS METHOD TO TAKE A SCREENSHOT
//********* THAT LINE MIGHT CAUSE A CRASH ON SOME PHONES (LIKE XPERIA T)<----(SEE HERE)
//IF THAT HAPPENDS USE THE LINE "bmp1 =decodeFile(tmpFile);" WITH THE METHOD BELOW
}
};
public Bitmap decodeFile(File f) { //FUNCTION BY Arshad Parwez
Bitmap b = null;
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int IMAGE_MAX_SIZE = 1000;
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(
2,
(int) Math.round(Math.log(IMAGE_MAX_SIZE
/ (double) Math.max(o.outHeight, o.outWidth))
/ Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return b;
}
}
try out this also
public static Bitmap overlay(Bitmap bmp1,Bitmap bmp2) {
Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, 0,0, null);
canvas.drawBitmap(bmp2, 0, 0, null);
Log.i("bmOverlay.......",""+bmOverlay);
bmp3=bmOverlay;
return bmOverlay;
}
private void getScreen() {
Toast.makeText(BookType1.this, "saved", Toast.LENGTH_SHORT).show();
File myDir=new File("/sdcard/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".png";
File file = new File (myDir, fname);
try
{
FileOutputStream ostream = new FileOutputStream(file);
bmp3.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
and you can also go through these references which gives you more idea
How to capture screenshot of surfaceview with background
Taking screen shot of a SurfaceView in android
How to take a screenshot of Android's Surface View?
How to programmatically take a screenshot in Android?

how to create pdf file with multiple pages from image file in android

How to create PDF file with multiple pages from image file in Android? I created one PDF file from image. That PDF file has one page. That is half of that image. In the right side search part is cut in PDF file.
I am using itext-5.3.4.jar for create PDF.
wbviewnews.loadUrl("http://developer.android.com/about/index.html");
// button for create wbpage to image than image to PDF file
Button btnclick =(Button)findViewById(R.id.btnclick);
btnclick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Picture p = wbviewnews.capturePicture();
bitmap=null;
PictureDrawable pictureDrawable = new PictureDrawable(p);
bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(),pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
//Bitmap bitmap = Bitmap.createBitmap(200,200, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pictureDrawable.getPicture());
ImageView imgdata=(ImageView)findViewById(R.id.imgdata);
imgdata.setImageBitmap(bitmap);
String filename = "pippo.png";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);
String pdffilename = "pippo.pdf";
File pdffilepath = new File(sd, pdffilename);
try {
FileOutputStream out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Exception", e.toString());
}
Document document=new Document();
try {
Log.e("pdffilepath", pdffilepath.toString());
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(pdffilepath));
document.open();
// URL url = new URL (Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+filename);
// Log.e("url", url.toString());
Image image = Image.getInstance(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+filename) ;
document.add(image);
document.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("FileNotFoundException", e.toString());
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("DocumentException", e.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("MalformedURLException", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("IOException", e.toString());
}
}
});
Your search through StackOverflow is less I guess cause I found these answer already there having solution, yes its contained in different answer and looking at the Q/A I guess they can solve your problem, if not then keep trying :)
how to Generate Pdf File with Image in android?
How to create a PDF with multiple pages from a Graphics object with Java and itext
iText Example
if your linear layout height is very large than try this code
https://demonuts.com/android-generate-pdf-view/
follow this link and just change the lines
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, 10000, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawPaint(paint);
Bitmap bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, 10000, true);
canvas.drawBitmap(bitmap, 0, 0 , null);
document.finishPage(page);`
If you want to create a pdf file with multiple images you can use PdfDocument from Android. Here is a demo:
private void createPDFWithMultipleImage(){
File file = getOutputFile();
if (file != null){
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
PdfDocument pdfDocument = new PdfDocument();
for (int i = 0; i < images.size(); i++){
Bitmap bitmap = BitmapFactory.decodeFile(images.get(i).getPath());
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), (i + 1)).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawPaint(paint);
canvas.drawBitmap(bitmap, 0f, 0f, null);
pdfDocument.finishPage(page);
bitmap.recycle();
}
pdfDocument.writeTo(fileOutputStream);
pdfDocument.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private File getOutputFile(){
File root = new File(this.getExternalFilesDir(null),"My PDF Folder");
boolean isFolderCreated = true;
if (!root.exists()){
isFolderCreated = root.mkdir();
}
if (isFolderCreated) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "PDF_" + timeStamp;
return new File(root, imageFileName + ".pdf");
}
else {
Toast.makeText(this, "Folder is not created", Toast.LENGTH_SHORT).show();
return null;
}
}
Here images is the ArrayList of the images with path.
you can set the image like this way...
Bitmap bt=Bitmap.createScaledBitmap(btm, 200, 200, false);
bt.compress(Bitmap.CompressFormat.PNG,100, bos);

How to resize image for list view

i am loading image and title for list view from webservices text is f9 but image is too big.how to resize it and i want to set text in right side and image in left side in each row of list view .i am using this method Bitmap resized = Bitmap.createScaledBitmap(bitmap, 70, 70, true); but nothing appearing on emulator This is my costant class where i am loading image
public static Bitmap loadPhotoBitmap(URL url) {
Bitmap bitmap = null ;
InputStream in = null;
BufferedOutputStream out = null;
BufferedOutputStream bfs = null;
try {
FileOutputStream fos = new FileOutputStream("/sdcard/photo-tmp.jpg");
bfs = new BufferedOutputStream(fos);
in = new BufferedInputStream(url.openStream(),8192);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 8192);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bfs.write(data, 0, data.length);
bfs.flush();
BitmapFactory.Options opt = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opt);
//System.out.println(resized);
Bitmap resized = Bitmap.createScaledBitmap(bitmap, 70,70, true);
return resized;
} catch (IOException e) {
// android.util.Log.e("message", "Could not load photo: " + this, e);
System.out.println("Exception while loading image");
} finally {
closeStream(in);
closeStream(out);
closeStream(bfs);
}
System.out.println("returning");
return bitmap;
}
LazyAdapter.class
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("Exception before..");
String strUrl = Constants.vctrImagePath.elementAt(counter).toString();// getting imgurl
System.out.println("Urls...." + strUrl);
URL url =null;
try {
url = new URL(strUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = Constants.loadPhotoBitmap(url);
//Bitmap resized = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
RelativeLayout layout = new RelativeLayout(mContext);
RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
TextView text1 = new TextView(mContext);
text1.setText(Constants.vctrCategory.elementAt(counter).toString());
LayoutParams params1 = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
text1.setLayoutParams(params1);
text1.setTextSize(20);
text1.setGravity(Gravity.RIGHT);
layout.addView(text1);
ImageView img = new ImageView(mContext);
img.setImageBitmap(bitmap);
layout.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
layout.addView(img);
counter++;
return layout;
}
private void setContentView(ImageView image) {
// TODO Auto-generated method stub
}
Instead of
BitmapFactory.Options opt = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opt);
Replace that with
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
problem was not in my this bitmapfactory class.i hav resolved my isssue.
i just change code in my lazy adapter class.
Bitmap bitmap = Constants.DownloadImage(strUrl);
Bitmap resized=null;
if(bitmap!=null){
resized = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
}else{
System.out.println(strUrl+ "no image here");
}
before i was resizing image in my list view.while it will resize in adpter class of list view.

Categories

Resources