I want to add image to android PDF using iText. I want to achieve this without saving image to SDCard first. I put my image into res/drawable folder but proving the image path doesn’t work and it throws FileNotFound Exception. My path is like this:
String path = “res/drawable/myImage.png”
Image image = Image.getInstance(path);
document.add(image);
Now please suggest me a solution how I will add correct file path to getInstance(…) method. Thanks
Of course it'll not work at that way.
move your image to assets folder to access it with getassets() method
// load image
try {
// get input stream
InputStream ims = getAssets().open("myImage.png");
Bitmap bmp = BitmapFactory.decodeStream(ims);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
document.add(image);
}
catch(IOException ex)
{
return;
}
I found a solution for your issue. If you want to get image from your drawable folder and put it into a PDF file using iText use this code:
try {
document.open();
Drawable d = getResources().getDrawable(R.drawable.myImage);
BitmapDrawable bitDw = ((BitmapDrawable) d);
Bitmap bmp = bitDw.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
document.add(image);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
Here is the code to add image to PDF using iText, if the image is dynamic (i.e), if the image cannot be added to asset folder at compile time,
public void addImage(Document document,ImageView ivPhoto) throws DocumentException {
try {
BitmapDrawable drawable = (BitmapDrawable) ivPhoto.getDrawable();
Bitmap bitmap = drawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imageInByte = stream.toByteArray();
Image image = Image.getInstance(imageInByte);
document.add(image);
}
catch(IOException ex)
{
return;
}
}
Here is my code, To set Image on particular position
move your image to assets folder to get image by getassets() method.
Hope this will help you!
try {
InputStream ims = getAssets().open("header1.png");
Bitmap bmp = BitmapFactory.decodeStream(ims);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
image.setAbsolutePosition(10f,750f);
image.scaleToFit(850,78);
document.add(image);
}
catch(IOException ex)
{
ex.printStackTrace();
return;
}
try {
FileInputStream in = new FileInputStream("input file uri");
PdfReader pdfReader = new PdfReader(in);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("output file uri"));
PdfContentByte content = pdfStamper.getOverContent(1);
Image deliverImg = Image.getInstance("image URI");
deliverImg.setAbsolutePosition(420f, 100f);
content.addImage(deliverImg);
pdfStamper.close();
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
Related
I am trying to creating pdfs from images in my Android application.
I get the image successfully and created the pdf file successfully. But When I open my pdf file, images are not displayed. I have tried many solutions on Internet but all in vain.
I am pasting my code. Kindly guide me.
First I am pasting the code for getting image from gallery
Intent myIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(myIntent,120);
Now I am pasting the code of OnActivityResult Method, in which I am getting the image and craeating a pdf file.
try {
Document doc = new Document();
if (resultCode == RESULT_OK) {
if (requestCode == 120) {
if (data.getData() != null) {
Uri uri = data.getData();
Image image = Image.getInstance(uri.toString());
FileOutputStream fileOutputStream =openFileOutput("mypdf.pdf", Context.MODE_PRIVATE);
PdfWriter.getInstance(doc, fileOutputStream);
doc.open();
doc.add(image);
doc.close();
}
}
}
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
As you are using iText you need to create BitMap format of image and then need to add into pdf.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, <pass the uri of image>);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAbsolutePosition(470f,755f);
myImg.scaleToFit(100f,100f);
document.add(myImg);
I have solved it, The solution was to use Input Stream as follows:
Uri uri = data.getData();
InputStream ims = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(ims);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Image image = Image.getInstance(byteArray);
doc.add(image);
doc.close();
I just create an image that comes from the camera on an Android application:
YuvImage yuv = new YuvImage(
byteArrayDataFromCamera,
camera.getParameters().getPreviewFormat(),
imageWidth,
imageHeight, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuv.compressToJpeg(new Rect(0, 0, imageWidth, imageHeight, 100, out);
byte[] bytes = out.toByteArray();
Bitmap image = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
And I want to add Exif information to it. Since now I've tried this:
// Save image on SD
storeImage(image, "Image_0.jpg");
String filePath = Environment.getExternalStorageDirectory() + "/MyFolder/Image_0.jpg";
try {
ExifInterface exif = new ExifInterface(filePath);
exif.setAttribute("UserComment", "my custom comment");
exif.saveAttributes();
}
catch (IOException e) {
e.printStackTrace();
}
The storeImage method:
private boolean storeImage(Bitmap imageData, String filename) {
//get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/MyFolder/";
File sdIconStorageDir = new File(iconsStoragePath);
//create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
String filePath = sdIconStorageDir.toString() + filename;
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
//choose another format if PNG doesn't suit you
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
} catch (IOException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
}
return true;
}
As my image is recently created, it doesn't have any ExifInterface information. I want to know how to add new ExifInterface to my recently created image. How can achieve this?
I know that you can add rotation in image information but to add comment it's more complicated. The Exif class doesn't work correctly... Because you can read Exif information from stream but you can write this information. When I search information to add image info the users have the same problem as you, and I know that existing libraries to add information in image information...
When I find the post I give you the URL!!
I can find the post, read this!!
Tell me if I helped you and good programming!
Hi I am working on application which gets .png files in byte stream from server. When I got it I try to make from it bmp and later convert it to .png file, but the following method ( Bitmap img = BitmapFactory.decodeByteArray(result, 0, result.length); ) returns me null.
Here is my code:
byte[] result
Bitmap img = BitmapFactory.decodeByteArray(result, 0, result.length);
try {
File filename = new File(imageUri.getPath()+name);
File parentFile = new File(imageUri.getPath());
parentFile.mkdirs();
FileOutputStream out = new FileOutputStream(filename);
img.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (FileNotFoundException e) {
Log.e("imageDownloaded", e.toString());
} catch (Exception e) {
Log.e("imageDownloaded", e.toString());
}
but the img Bitmap is always, null. I uploaded the image as multi part data and it was png file parsed to byte array, but now when i want to retrieve it i get this ugly null. Thanks for any help.
I already create table and some extra information as a PDF. But I couldn't import image to my PDF whatever I did. I have my_thumb.png file in assets folder.
in my MainActivity class
try {
inputStream = MainActivity.this.getAssets().open("my_thumb.png");
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
model.setThumbStream(stream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in my CreatePDF class
Image thumb = Image.getInstance(Model.getThumbStream().toByteArray());
companyLogo.setAbsolutePosition(document.leftMargin(),121);
companyLogo.scalePercent(25);
document.add(thumb);
and the problem is
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
this line returns with null.
What is the point that I missing?
Thanks in advance.
You first get the png to drawable
Drawable d = Drawable.createFromStream(getAssets().open("my_thumb.png"), null);
then convert drawable to bitmap and get the byte array :)
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bitmapdata = stream.toByteArray();
In my application, I am changing the view to PDF, but I don't know how to print the file using printer.
My View to PDF Code
//Below layout View is to change PDF
RelativeLayout MyView = (RelativeLayout)findViewById(R.id.print);
try{
View v1 = MyView.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = v1.getDrawingCache();
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
file =new File(android.os.Environment.getExternalStorageDirectory(),"Test Folder");
if(!file.exists())
{
file.mkdirs();
}
//f = new File(file, "filename"+.png);
//f= new File(file.getAbsolutePath()+file.separator+"test"+".png");
f= new File(file.getAbsolutePath()+file.separator+"test"+".pdf");
}
/* FileOutputStream ostream = new FileOutputStream(f);
bitmap.compress(CompressFormat.PNG, 10, ostream);
ostream.close();*/
}
catch(Exception e){
e.printStackTrace();
}
Document document=new Document();
try{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
PdfWriter.getInstance(document,new FileOutputStream(f));
document.open();
Image image = Image.getInstance (byteArray);
document.add(new Paragraph(""));
document.add(image);
document.close();
}catch(Exception e){
e.printStackTrace();
}
This all function I am putting in print button, after I click the print button change relative layout view to PDF , my doubt is after changing to PDF file I want to print that PDF file through printer. I don't have idea about print function.Can any one know please help me to solve this problem?