Question is already asked here : create PDF of RecyclerView in FULL length
And I also have same Question as i haven't found solution yet, I want to Generate PDF of RecyclerView Content with full length. but did't found solution.
I have already tried all the available solutions and all the possible ways to generate PDF from RecycleView.
Solutions which i have already tried :
https://gist.github.com/PrashamTrivedi/809d2541776c8c141d9a
Take a screenshot of RecyclerView in FULL length
Convert Listview Items into a single Bitmap Image
Have tried all solutions which mentioned above but any of them not working with me and getting error, sometime width & height issue or sometime getting empty white bitmap as output don't know why.
Problem :
I have RecyclerView with HTML Content as well as Images in between contents.
Consider Following Screen as RecyclerView with content.
having content in RecyclerView same as above image with 100+ items.
RecyclerView Item Layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.facebook.drawee.view.SimpleDraweeView
android:id="#+id/leftImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:adjustViewBounds="true"
android:maxHeight="350dp"
fresco:actualImageScaleType="fitCenter"
fresco:placeholderImage="#color/white" />
<jp.wasabeef.richeditor.RichEditor
android:id="#+id/editor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/margin10dp"
android:layout_marginRight="#dimen/margin10dp"
android:layout_weight="1"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false" />
<com.facebook.drawee.view.SimpleDraweeView
android:id="#+id/rightImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:adjustViewBounds="true"
android:maxHeight="350dp"
fresco:actualImageScaleType="fitCenter"
fresco:placeholderImage="#color/white" />
</LinearLayout>
Update
As I was working on PDF to generate PDF from views, and was not able to generate PDF so I have posted this question.
But Now, I found a solution to generate PDF by using Webview you can see my answer on this question has marked as accepted.
Based on solution what I found, I have created a library to generate PDF from any String or Any HTML Content.
PDF-Generator Library: PDF-Generator
Thanks
I was looking at all the answers here, but unfortunately, they didn't work for me. I took the method for creating Bitmap from StackOverflow. The method takes the recycler view as an argument and converts it into a Bitmap which is then used by the PdfDocument.pageInfo to make it work for your needs. I tried it and it works perfectly for all the layouts such as relative layout and linear layout. Hope this will help.
Bitmap recycler_view_bm = getScreenshotFromRecyclerView(mRecyclerView);
try {
pdfFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(pdfFile);
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new
PdfDocument.PageInfo.Builder(recycler_view_bm.getWidth(), recycler_view_bm.getHeight(), 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
recycler_view_bm.prepareToDraw();
Canvas c;
c = page.getCanvas();
c.drawBitmap(recycler_view_bm,0,0,null);
document.finishPage(page);
document.writeTo(fOut);
document.close();
Snackbar snackbar = Snackbar
.make(equipmentsRecordActivityLayout, "PDF generated successfully.", Snackbar.LENGTH_LONG)
.setAction("Open", new View.OnClickListener() {
#Override
public void onClick(View view) {
openPDFRecord(pdfFile);
}
});
snackbar.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public Bitmap getScreenshotFromRecyclerView(RecyclerView view) {
RecyclerView.Adapter adapter = view.getAdapter();
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);
for (int i = 0; i < size; i++) {
Bitmap bitmap = bitmaCache.get(String.valueOf(i));
bigCanvas.drawBitmap(bitmap, 0f, iHeight, paint);
iHeight += bitmap.getHeight();
bitmap.recycle();
}
}
return bigBitmap;
}
Here is a samble code of generating a PDF from a view
//create bitmap from view and returns it
private Bitmap getBitmapFromView(View view) {
ScrollView hsv = (ScrollView) findViewById(R.id.scrollViewP);
HorizontalScrollView horizontal = (HorizontalScrollView) findViewById(R.id.hsv);
int totalHeight = hsv.getChildAt(0).getHeight();
int totalWidth = horizontal.getChildAt(0).getWidth();
Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth, totalHeight,Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null) {
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
} else{
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
}
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
private static void addImage(Document document,byte[] byteArray)
{
Image image = null;
try
{
image = Image.getInstance(byteArray);
}
catch (BadElementException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// image.scaleAbsolute(150f, 150f);
try
{
document.add(image);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void CreatePDF()
{
File folder = new File(Environment.getExternalStorageDirectory()+File.separator+"PDF Folder");
folder.mkdirs();
Date date = new Date() ;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);
final File myFile = new File(folder + timeStamp + ".pdf");
try {
OutputStream output = new FileOutputStream(myFile);
Document document = new Document(PageSize.A4);
try{
PdfWriter.getInstance(document, output);
document.open();
LinearLayout view2 = (LinearLayout)findViewById(R.id.MainLayout);
view2.setDrawingCacheEnabled(true);
Bitmap screen2= getBitmapFromView(view2);
ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
screen2.compress(Bitmap.CompressFormat.JPEG,100, stream2);
byte[] byteArray2 = stream2.toByteArray();
addImage(document,byteArray2);
document.close();
AlertDialog.Builder builder = new AlertDialog.Builder(PaySlip.this, R.style.AppCompatAlertDialogStyle);
builder.setTitle("Success")
.setMessage("enter code herePDF File Generated Successfully.")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(myFile), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
}).show();
//document.add(new Paragraph(mBodyEditText.getText().toString()));
}catch (DocumentException e)
{
//loading.dismiss();
e.printStackTrace();
}
}catch (FileNotFoundException e)
{
// loading.dismiss();
e.printStackTrace();
}
}
Where view is the instance of RecyclerView:
view.measure(
View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
myBitmap = Bitmap.createBitmap(view.getWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
After lots of workaround and solutions i got solution, and Best approach to achieve this,
Add your content in webview in html form, From webview we can directly do print using Android's PrintManager class.
Like this :
String documentName = "yourDocumentName"; // you can provide any name
// Get a PrintManager instance
PrintManager printManager = (PrintManager) context.getSystemService(PRINT_SERVICE);
// Get a print adapter instance
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(documentName);
PrintJob printJob = printManager.print(documentName, printAdapter, new PrintAttributes.Builder().build());
Above is sample code to do print of webview content, using this we can also generate PDF too.
For more info and use refer this Printing HTML Document
Thanks.
Related
In my Fragment's layout i have a ScrollView with a LinearLayout inside
<ScrollView
android:id="#+id/scrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- Other views -->
</LinearLayout>
</ScrollView>
So i need to create and share a picture of entire content of scrollview. All solutions i've tried take screenshot only of the visible area, and not of entire scrollview content. How can i do?
I hope this is work for you.. source here. this is not technically a screenshot code. but this code convert the whole layout view into bitmap
Bitmap bitmap = getBitmapFromView(scrollview, scrollview.getChildAt(0).getHeight(), scrollview.getChildAt(0).getWidth());
//create bitmap from the ScrollView
private Bitmap getBitmapFromView(View view, int height, int width) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return bitmap;
}
call below method getYourLayout() where you want to take snap of your layout. In this i attach layout in one dialog & take snapshop of root layout whithout showing dialog to user. All thing happens in background.
private void getYourLayout() {
try {
Dialog fb_event_info = new Dialog(YourActivity.this);
fb_event_info.requestWindowFeature(Window.FEATURE_NO_TITLE);
fb_event_info.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
fb_event_info.setContentView(R.layout.yourXmlLayoutFile);
final LinearLayout lnr_fb_info = (LinearLayout) fb_event_info.findViewById(R.id.container);
TextView tv_fb_event_name = (TextView) fb_event_info.findViewById(R.id.tv_fb_event_name);
tv_fb_event_name.setTypeface(Global.setCubanoFont(EventDetailActivity.this));
tv_fb_event_name.setText(tv_event_name.getText().toString());
lnr_fb_info.setDrawingCacheEnabled(true);
lnr_fb_info.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
lnr_fb_info.layout(0, 0, lnr_fb_info.getMeasuredWidth(), lnr_fb_info.getMeasuredHeight());
lnr_fb_info.buildDrawingCache(true);
bitmap = Bitmap.createBitmap(lnr_fb_info.getDrawingCache());
saveImage(bitmap);
} catch (Exception e) {
}
}
This Function is for Saving your Bitmap as file.
private void saveImage(Bitmap bitmap) {
try {
Log.e("----------in---", "saveImage....: ");
if (!rootFile.exists())
rootFile.mkdirs();
long time = System.currentTimeMillis();
fname = "mynight-" + time + ".png";
rootFile = new File(rootFile, fname);
Log.e("----------in---", "saveImage...1.: ");
try {
FileOutputStream Fout = new FileOutputStream(rootFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, Fout);
sendShareFb();
Fout.flush();
Fout.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Below function is for share your image on facebook.
private void sendShareFb() {
try {
Log.e("----------in---", "sendShareFb....: ");
Intent fbIntent = new Intent(Intent.ACTION_SEND);
File imageFile = new File(rootFile.toString());
fbIntent.putExtra(Intent.EXTRA_TEXT, "Share..");
fbIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
fbIntent.setType("image/jpeg/png");
PackageManager pm = getPackageManager();
List<ResolveInfo> lract = pm.queryIntentActivities(fbIntent, PackageManager.MATCH_DEFAULT_ONLY);
boolean resolved = false;
for (ResolveInfo ri : lract) {
if (ri.activityInfo.name.toLowerCase().contains("facebook")) {
fbIntent.setClassName(ri.activityInfo.packageName, ri.activityInfo.name);
resolved = true;
break;
}
}
if (!resolved) {
Toast.makeText(EventDetailActivity.this, "Vous ne semblez pas avoir Facebook installé sur cet appareil", Toast.LENGTH_SHORT).show();
}
startActivity(resolved ? fbIntent : Intent.createChooser(fbIntent, "Choose one"));
} catch (final ActivityNotFoundException e) {
e.printStackTrace();
}
}
Sure that this will Help you. Because this solution has fixed my problem many time.
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;
}
I have a custom tiling view, which was until recently based on a SurfaceView. I have now changed it to extend TextureView.
Basically I am getting a large image in tile bits.
I need to capture all the content of the screen and save it as a bitmap, which has worked with all views including the SurfaceView. However, when i use the same method now, the area of the TextureView is black. I have read that this has something to do with HW acceleration.
Is there any way of capturing the image of the texture view?
Below is the screen capture method.
public File takeScreenShot(View contentView)
{
File result = null;
String mPath = this.cacheDir + "/screenshot.png";
File imageFile = new File(mPath);
if (imageFile.exists()) {
imageFile.delete();
Log.i("ImageManager","Old screenshot image was deleted");
}
// create bitmap screen capture
Bitmap bitmap;
View v1 = contentView;
v1.setDrawingCacheEnabled(true);
v1.setDrawingCacheBackgroundColor(Color.WHITE);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, outputStream);
outputStream.flush();
outputStream.close();
result = imageFile;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
EDIT: New attempt
Get all TextureViews and call getBitmap. This works, however placing them on top of the larger bitmap does not look right with the coordinates from the TilingView it self or the getLocation OnScreen() or getLocationInWindow().
public List<TilingTextureView> getAllTextureViews(View view)
{
List<TilingTextureView> tilingViews = new ArrayList<TilingTextureView>();
if (view instanceof TilingTextureView) {
tilingViews.add((TilingTextureView)view);
}
else if(view instanceof ViewGroup)
{
ViewGroup viewGroup = (ViewGroup)view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
tilingViews.addAll(getAllTextureViews(viewGroup.getChildAt(i)));
}
}
return tilingViews;
}
This bit is added in the takeScreenShot method after getting the screen shot of the entire view.
List<TilingTextureView> tilingViews = getAllTextureViews(contentView);
if (tilingViews.size() > 0) {
Canvas canvas = new Canvas(bitmap);
for (TilingTextureView tilingTextureView : tilingViews) {
Bitmap b = tilingTextureView.getBitmap(tilingTextureView.getWidth(), tilingTextureView.getHeight());
int[] location = new int[2];
tilingTextureView.getLocationInWindow(location);
int[] location2 = new int[2];
tilingTextureView.getLocationOnScreen(location2);
canvas.drawBitmap(b, location[0], location[1], null);
}
}
Some thing to notice:
Bitmap textureViewBitmap = textureView.getBitmap();
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
v1.setDrawingCacheBackgroundColor(Color.TRANSPARENT);
Bitmap viewBitmap = Bitmap.createBitmap(v1.getDrawingCache());
viewBitmap.setHasAlpha(true);
v1.setDrawingCacheEnabled(false);
Canvas canvas = new Canvas(textureViewBitmap);
canvas.drawBitmap(viewBitmap, 0, 0, paint);
FileOutputStream outputStream = new FileOutputStream(imageFileDest);
int quality = 100;
cameraBitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
Assume the textureView is fullscreen and only one. If you would like the overlay view covered the TextureView, viewBitmap.setHasAlpha(true); is important, otherwise the combined bitmap is still black on the "textureView part".
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);
I use below code to convert, but it seems can only get the content in the display screen and can not get the content not in the display screen.
Is there a way to get all the content even out of scroll?
Bitmap viewBitmap = Bitmap.createBitmap(mScrollView.getWidth(),mScrollView.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(viewBitmap);
mScrollView.draw(canvas);
We can convert all the contents of a scrollView to a bitmap image using the code shown below
private void takeScreenShot()
{
View u = ((Activity) mContext).findViewById(R.id.scroll);
HorizontalScrollView z = (HorizontalScrollView) ((Activity) mContext).findViewById(R.id.scroll);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();
Bitmap b = getBitmapFromView(u,totalHeight,totalWidth);
//Save bitmap
String extr = Environment.getExternalStorageDirectory()+"/Folder/";
String fileName = "report.jpg";
File myPath = new File(extr, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(mContext.getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {
Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
The Pops answer is really good, but in some case you could have to create a really big bitmap which could trigger a OutOfMemoryException when you create the bitmap.
So I made a little optimization to be gently with the memory :)
public static Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {
int height = Math.min(MAX_HEIGHT, totalHeight);
float percent = height / (float)totalHeight;
Bitmap canvasBitmap = Bitmap.createBitmap((int)(totalWidth*percent),(int)(totalHeight*percent), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(canvasBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
canvas.save();
canvas.scale(percent, percent);
view.draw(canvas);
canvas.restore();
return canvasBitmap;
}
This one works for me
To save the bitmap check runtime permission first
#OnClick(R.id.donload_arrow)
public void DownloadBitMap()
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
{
downloadData();
Log.e("callPhone: ", "permission" );
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
Toast.makeText(this, "need permission", Toast.LENGTH_SHORT).show();
}
}
To get bitmap
private void downloadData() {
ScrollView iv = (ScrollView) findViewById(R.id.scrollView);
Bitmap bitmap = Bitmap.createBitmap(
iv.getChildAt(0).getWidth()*2,
iv.getChildAt(0).getHeight()*2,
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
c.scale(2.0f, 2.0f);
c.drawColor(getResources().getColor(R.color.colorPrimary));
iv.getChildAt(0).draw(c);
// Do whatever you want with your bitmap
saveBitmap(bitmap);
}
To save the bitmap
public void saveBitmap(Bitmap bitmap) {
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "SidduInvoices");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Do something on success
} else {
// Do something else on failure
}
File imagePath = new File(Environment.getExternalStorageDirectory() + "/SidduInvoices/Siddus.png");
if(imagePath.exists())
{
imagePath=new File(Environment.getExternalStorageDirectory() + "/SidduInvoices/Siddus"+custamername.getText().toString()+".png");
}
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
progressBar.cancel();
final File finalImagePath = imagePath;
new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Saved")
.setContentText("Do you want to share this with whatsapp")
.setCancelText("No,cancel !")
.setConfirmText("Yes,share it!")
.showCancelButton(true)
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
shareImage(finalImagePath);
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
}
})
.show();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
You need get the total width and height of the scrollview, or you created viewBitmap is too small to contain the full content of the scrollview.
check this link
Android: Total height of ScrollView
The issue here is that the only actual pixel content that ever exists is that which is visible on the display screen. Android and other mobile platforms are very careful about memory use and one of the ways a scrolling view can maintain performance is to not draw anything that is offscreen. So there is no "full" bitmap anywhere -- the memory containing the content that moves offscreen is recycled.