I am taking a photo with the camera and saving the photo value into a bitmap. I would like to use that photo in itext to generate an pdf.
This is the code I have so far.
Bitmap bitmap;
public void Picture()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
bitmap=(Bitmap)data.getExtras().get("data");
PDF();
}
public void PDF()
{
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Image img = Image.getInstance(bitmap);
Document document = new Document();
PdfWriter.getInstance(document, out);
document.open();
document.add(new Paragraph("Example"));
document.close();
}
bitmap=(Bitmap)data.getExtras().get("data");
ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream3);
Image maimg = Image.getInstance(stream3.toByteArray());
maimg.setAbsolutePosition(490, 745);
maimg.scalePercent(40);
document.add(maimg);
you should download itextpdf-5.3.2.jar file and attach in your project.
You can use it as an example:
public class WritePdfActivity extends Activity
{
private static String FILE = "mnt/sdcard/FirstPdf.pdf";
static Image image;
static ImageView img;
Bitmap bmp;
static Bitmap bt;
static byte[] bArray;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img=(ImageView)findViewById(R.id.imageView1);
try
{
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addImage(document);
document.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void addImage(Document document)
{
try
{
image = Image.getInstance(bArray); ///Here i set byte array..you can do bitmap to byte array and set in image...
}
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();
}
}
}
Here is the reference, Please check
enter link description here
One Important thing better to use PDFBox library for convert Image to PDF
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm making a wallpaper application. In this full-screen image activity, this activity is getting data from previous activity by intent. Now I want to set the image(that comes from URL) as wallpaper. This code is not working.
public class PhotoFullPopupWindow extends AppCompatActivity {
Activity context;
Bitmap bitmap=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_screen_image_view);
ImageView fullScreenImageView = findViewById(R.id.FullScreenImageView);
final String url=getIntent().getStringExtra("url");
Glide.with(this)
.load(url)
.into(fullScreenImageView);
context=this;
bitmap = getBitmap(url);
Button setWallpaperButton = findViewById(R.id.setWallpaper);
setWallpaperButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
try {
wallpaperManager.setBitmap(bitmap);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL URL = new URL(bitmapUrl);
return BitmapFactory.decodeStream(URL.openConnection().getInputStream());
}
catch(Exception ex) {
return null;
}
}
}
below is the code i used for setting the wallpaper
public void setWallpaper(String url) {
WallpaperManager myWallManager = WallpaperManager.getInstance(getApplicationContext());
Glide.with(this)
.asBitmap()
.load(url)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(getLocalBitmapUri(resource), "image/*");
intent.putExtra("jpg", "image/*");
startActivity(Intent.createChooser(
intent, "Set as:"));
}
private Uri getLocalBitmapUri(Bitmap bmp) {
Uri bmpUri = null;
try {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),
"OP_Wallpaper_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
Try this:
In your first activity, you should save the Bitmap to disk.
Then load it up in the next activity.
Make sure to recycle your bitmap in the first activity to prime it for garbage collection.
In Activity 1:
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bmp.recycle();
//Pop intent
Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
In Activity 2:
Bitmap bmp = null;
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
This question already has answers here:
How I can convert a bitmap into PDF format in android [closed]
(3 answers)
Closed 2 months ago.
I am trying to convert an activity to pdf format.I have taken a screenshot of the same as a bitmap.PLease help me to convert that sreenshot to the required pdf file.Thank you.
Please provide the code.Thank you.
This is the code I used...
1) MainActivity
public class MainActivity extends Activity {
//Button btn_getpdf;
private LinearLayout linearLayout;
private Bitmap myBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// btn_getpdf = (Button) findViewById(R.id.button_pdf);
linearLayout = (LinearLayout) findViewById(R.id.linear1);
linearLayout.post(new Runnable() {
public void run() {
//take screenshot
myBitmap = captureScreen(linearLayout);
Toast.makeText(getApplicationContext(), "Screenshot captured..!", Toast.LENGTH_LONG).show();
try {
if (myBitmap != null) {
//save image to SD card
saveImage(myBitmap);
}
Toast.makeText(getApplicationContext(), "Screenshot saved..!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public Bitmap captureScreen(View v) {
Bitmap screenshot = null;
try {
if (v != null) {
screenshot = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(screenshot);
v.draw(canvas);
}
} catch (Exception e) {
// Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
}
return screenshot;
}
public void saveImage(Bitmap bitmap) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File f = new File(root.getAbsolutePath() + "/DCIM/Camera/bitmap.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}
}
2)WritePdfActivity
public class WritePdfActivity extends Activity
{
private static String FILE ="DCIM/Camera/GenPdf.pdf";
static Image image;
static ImageView img;
Bitmap bmp;
static Bitmap bt;
static byte[] bArray;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img=(ImageView)findViewById(R.id.imageView1);
try
{
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addImage(document);
document.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void addImage(DocumentsContract.Document document)
{
try
{
image = Image.getInstance(bArray); ///Here i set byte array..you can do bitmap to byte array and set in image...
}
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();
}
}
}
Plz try this So question:
How I can convert a bitmap into PDF format in android
pdf-format-in-android/14393561#14393561
or also include itextpdf-5.3.2.jar in your project
#Swagatam Dutta use
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera/bitmap.jpg");
I couldn't find the solution for my issue. My MainActivity creates a pdf file, the user adds some text via EditText and closes it, no problem with that. Then I have a secondary activity that is calling the MediaStore.ACTION_IMAGE_CAPTURE to take pictures. Once a picture is taken, I'd like to know how I can get this just-captured image into that pdf.
I know I have to reopen the pdf, that is no problem, since I have the pdf file name saved in a variable. The major problem that I see is that I don't know how to programmatically get the file name of the picture, once it is automatically named after "yyyyMMdd_hhMMss.jpg". So how to get the file name from a picture taken by my secondary activity?
*EDIT - Showing code:
From MainActivity:
public class MainActivity extends Activity {
public String FILE = Environment.getExternalStorageDirectory() + "/CoManut/sample.pdf";
public static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
public static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED);
public static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);
public static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
EditText estRep;
EditText sensRep;
EditText cabRep;
String estais;
String sensores;
String cabos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
estRep = (EditText)findViewById(R.id.estaisRep);
sensRep = (EditText)findViewById(R.id.sensoresRep);
cabRep = (EditText)findViewById(R.id.cabosRep);
}
public void gerarPDF(View view) {
estais = estRep.getText().toString();
sensores = sensRep.getText().toString();
cabos = cabRep.getText().toString();
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addMetaData(document);
addTitlePage(document);
addContent(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("CoManut");
alertDialog.setMessage("Picture?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, PhotoActivity.class);
startActivity(intent);
}
});
alertDialog.setButton2("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Thanks for using this app!", Toast.LENGTH_LONG).show();
MainActivity.this.finish();
}
});
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.show();
}
private static void addMetaData(Document document) {
document.addTitle("Image and text to PDF");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Ricardo Gramowski");
document.addCreator("Ricardo Gramowski");
}
private static void addTitlePage(Document document)
throws DocumentException {
Paragraph preface = new Paragraph();
addEmptyLine(preface, 1);
preface.add(new Paragraph("Maintenance report", catFont));
addEmptyLine(preface, 1);
preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(),
smallBold));
addEmptyLine(preface, 3);
preface.add(new Paragraph("This doc is important", smallBold));
addEmptyLine(preface, 8);
preface.add(new Paragraph("This doc has been generated by Gramowski.",
redFont));
document.add(preface);
// Start a new page
document.newPage();
}
private void addContent(Document document) throws DocumentException {
Anchor anchor = new Anchor("Chapter 1", catFont);
anchor.setName("Chapter 1");
Chapter catPart = new Chapter(new Paragraph(anchor), 1);
Paragraph subPara = new Paragraph("Results", subFont);
Section subCatPart = catPart.addSection(subPara);
addEmptyLine(subPara, 1);
createTable(subCatPart);
document.add(catPart);
}
private void createTable(Section subCatPart)
throws BadElementException {
PdfPTable table = new PdfPTable(2);
PdfPCell c1 = new PdfPCell(new Phrase("Item"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Is that good? (OK/Not OK)"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);
table.addCell("Estais da Torrre ");
table.addCell(estais);
table.addCell("Sensores ");
table.addCell(sensores);
table.addCell("Cabos ");
table.addCell(cabos);
subCatPart.add(table);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
}
And my PhotoActivity:
public class PhotoActivity extends ActionBarActivity {
Button b1;
ImageView iv;
Bitmap bp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
b1 = (Button) findViewById(R.id.button1);
iv = (ImageView) findViewById(R.id.imageView);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(mImageBitmap);
String fpath = Environment.getExternalStorageDirectory() + "/CoManut/sample.pdf";
File file = new File(fpath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(fpath));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = null;
try {
myImg = Image.getInstance(stream.toByteArray());
} 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();
}
myImg.setAlignment(Image.MIDDLE);
try {
document.add(myImg);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.close();
}
}
// Button to go back to the MainActivity
public void onclickButton2(View view) {
PhotoActivity.this.finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Override your onActivitResult() method in your Main Activity
Here you will get the image bitmap from (Intent Data)
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
}
}
Now you have the bitmap. You can add bitmap image like below using the iText Library
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mImageBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // Try with Bitmap.CompressFormat.JPG also
Image image = Image.getInstance(stream.toByteArray());
document.add(image);
}catch(IOException ex){
ex.printStackTrace();
}
Update1
Your onActivityResult() should look like this.
Note Make sure you have WRITE_EXTERNAL_STORAGE permissions in your menifest.xml file.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
img.setImageBitmap(mImageBitmap);
String fpath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/sample.pdf";
File file = new File(fpath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(fpath));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = null;
try {
myImg = Image.getInstance(stream.toByteArray());
} 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();
}
myImg.setAlignment(Image.MIDDLE);
try {
document.add(myImg);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.close();
}
}
This will create a sample.pdf file in your sdcard and add Image bitmap into it.
Hope this helps.
I tested it here its working. :)
I can rake pictures from this code but i am not able to save the pictures into custom directory Uri uriTarget = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
and i think this is probably the line where i have to change my code
want to make a custom directory and save my image there
Camera.ShutterCallback myShutterCallback = new Camera.ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
Camera.PictureCallback myPictureCallback_RAW = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
Camera.PictureCallback myPictureCallback_JPG = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Uri uriTarget = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(MainActivity.this,
"waH kiAa selfie hAi :D ",
//+ uriTarget.toString(),
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
Try this approach...
private void saveImage(byte[] arg0) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "YOUR_CUSTOM_FOLDER";
File myDir = new File(root);
myDir.mkdirs();
String fname = "YOUR_IMAGE_NAME" + ".jpg";
file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
Bitmap bitmap1 = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
FileOutputStream out;
try {
out = new FileOutputStream(file);
bitmap1.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
MediaStore.Images.Media.insertImage(activity.getContentResolver(), bitmap1, "", "");
}
I am trying to take the output of the captured image into a uri but it throws null pointer exception on another component which was not null before and when not storing the image in uri it runs okay
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"Photo" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri1);
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
and on activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap temp=null;
Bundle extras = data.getExtras();
/*Uri g=data.getData();
try {
temp = MediaStore.Images.Media.getBitmap(getContentResolver(), g);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
*/
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
int h=photo.getHeight();
int w=photo.getWidth();
/* try {
temp = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageCaptureUri1);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
bitmapdata = stream.toByteArray();
Log.i("image", ""+bitmapdata);
image_boolean=true;
stream.flush();
stream.close();
/*File f = new File(mImageCaptureUri1.getPath());
if (f.exists()) f.delete();*/
}catch(Exception e)
{}
imageView.setImageBitmap(photo);
}}
}