I made an app in android studio (Java) on which is possible to fill some brief data in text boxes. Also app has two buttons, one for loading image from gallery and one for saving complete data to pdf.
I can successfully save all text data, but have problem with loaded image. Image is sucessfully loaded to app, but i dont know hot to save it to pdf. Image is loaded as an ImageView object.
Just to mention for pdf part i use itext.
Pls, help with hints or code for saving ImageVIew object to pdf file.
i had the same problem, but i can fixed.
first i changed the way i used to pick the image and replaced it with this code:
Intent getImage = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(getImage, GALLERY_REQUEST_CODE);
then, in the class onActivityResult i transformed the uri to a bitmap using this:
if(requestCode==GALLERY_REQUEST_CODE && resultCode== RESULT_OK && data!=null){
Uri imageData = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageData,filePath,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String myPath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(myPath);
then passed the bitmap to the pdf
pdf.addFoto(bitmap);
and finally, in the pdf template i used this to put the image in a table:
public void addFoto (Bitmap u) {
try{
PdfPTable tabla = new PdfPTable(1);
tabla.setWidthPercentage(60);
tabla.setSpacingBefore(10);
tabla.setSpacingAfter(10);
Bitmap bmp = u;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
PdfPCell imageCell = new PdfPCell();
imageCell.addElement(image);
tabla.addCell(imageCell);
document.add(tabla);
Look into PdfDocument
Example from the documentation
// create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(new Rect(0, 0, 100, 100), 1).create();
// start a page
Page page = document.startPage(pageInfo);
// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());
// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());
// close the document
document.close();
Related
I trying to develop an android application that enables the user to add a picture from his gallery, it works fine and displays the picture in the image view.
the problem is I am trying to save this picture in MySQL database (not URL or path of it) I want to store as a blob.
I tried the below code to get the image from user's gallery and display it in the image view.
The attribute test2 is a string and it is what I save in the database
if (requestCode == GET_FROM_GALLERY && resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
}
////// edit
Bitmap image = BitmapFactory.decodeFile(imagepath);
FinalBytes = getBytes(image); // this will be save in DB
Bitmap getIt = getBitmap(FinalBytes);
imgV.setImageBitmap(getIt);
imgV.setDrawingCacheEnabled(true);
imgV.buildDrawingCache();
Bitmap testbit = imgV.getDrawingCache();
ByteArrayOutputStream testbyte = new ByteArrayOutputStream();
testbit.compress(Bitmap.CompressFormat.JPEG, 100, testbyte);
testbyte2 = testbyte.toByteArray();
base64Image = Base64.encodeToString(testbyte2, Base64.DEFAULT);
I used below code for retrieving the image
byte[] decodedString = Base64.decode(Recipes[position].getRimage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.image.setImageBitmap(decodedByte);
But I am getting this message when decoding it.
illegalargumentexception bad base 64
please help I spent 2 days on this error
Trying to write an image on a pdf page
PDDocument document = null;
File inputFile = new File(mFilePath);
document = PDDocument.load(inputFile);
PDPage page = document.getPage(0);
File image = new File("/storage/emulated/0/", "1.jpg");
PDImageXObject img = JPEGFactory.createFromStream(document, inputStream);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(img, 100, 100);
contentStream.close();
File outputFile = new File(inputFile.getParent(), "new file.pdf");
document.save(outputFile);
document.close();
but getting this exception:
java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/imageio/ImageIO;
at org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory.readJPEG(JPEGFactory.java:99)
at org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory.createFromStream(JPEGFactory.java:78)
Note: I have also tried to use
PDImageXObject img = PDImageXObject.createFromFile(image.getPath(), document);
But nothing different happened.
What can i do to add a image to a position in current page with no exception? (If you know a better soloution let me know)
Finaly, I used Android Port of PDFBox(Link to answer) and added the image to pdf using a sample code from this link:
/**
* Add an image to an existing PDF document.
*
* #param inputFile The input PDF to add the image to.
* #param imagePath The filename of the image to put in the PDF.
* #param outputFile The file to write to the pdf to.
*
* #throws IOException If there is an error writing the data.
*/
public void createPDFFromImage( String inputFile, String imagePath, String outputFile )
throws IOException
{
// the document
PDDocument doc = null;
try
{
doc = PDDocument.load( new File(inputFile) );
//we will add the image to the first page.
PDPage page = doc.getPage(0);
// createFromFile is the easiest way with an image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true);
// contentStream.drawImage(ximage, 20, 20 );
// better method inspired by https://stackoverflow.com/a/22318681/535646
// reduce this value if the image is too large
float scale = 1f;
contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth()*scale, pdImage.getHeight()*scale);
contentStream.close();
doc.save( outputFile );
}
finally
{
if( doc != null )
{
doc.close();
}
}
}
Here i have stored an image by converting as string using 'base64 format' on my server,and i could able to display it in the same way on image view .But now i want download it to my sd card .I can see that some people downloading using 'URL'. But in my case there is no URL.I just converted the image into string and stored and able to display it on imageview by reconverting it.
this is the way i reconverted the string into image
//getting string from server using json parsor
String image=json_data.getString("img");
txt.setText(u);
//converting string to image
byte[] imageAsBytes = Base64.decode(p.getBytes(), 0);
im = (ImageView)this.findViewById(R.id.imageView1);
im.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0,imageAsBytes.length));
Use Image Loader libraries instead of yours.
https://github.com/nostra13/Android-Universal-Image-Loader
https://github.com/bumptech/glide
http://square.github.io/picasso/
THIS SNIPPET SHOULD HELP !
// give any name to file xxx.jpg
File filePath = new File(Environment.getExternalStorageDirectory()+"/name.jpg");
FileOutputStream os = new FileOutputStream(filePath, true);
EDIT
Bitmap x = BitmapFactory.decodeByteArray(imageasbytes , 0 , inageasbytes.length());
x.compress(
Bitmap.CompressFormat.JPEG, 85, os);
os.flush();
os.close();
Also , add the following permission .
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Also if you want to know how to recover it..
String imgFile = Environment.getExternalStorageDirectory() + "/name.jpg";
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile);
Imageview.setimagebitmap(mybitmap);
I have a 300 page PDF file. I want to create a new PDF file from my chosen pages the existing pdf file.
I have created a blank PDF File (using PDFBox ) like this:
// Create a new empty document
PDDocument document = new PDDocument();
// Create a new blank page and add it to the document
PDPage blankPage = new PDPage();
document.addPage( blankPage );
// Save the newly created document
document.save("BlankPage.pdf");
and this is how I am reading a page from pdf File.
PDDocument doc = PDDocument.load("Hello World.pdf");
PDPage firstPage = (PDPage) doc.getDocumentCatalog().getAllPages().get(67);
My question is, how do I get the contents of 'firstpage' into "blankPage.pdf".
If I can choose the x,y coordinates of the firstpage(where it is to be overlayed), it would be even better.
P.S.
The page sizes of my Hello World file are not A4.Each page is more like a thumbnail with text and shapes.So, overlaying is possible on A4. Also, I do not want to convert the files to image and then onverlay, I want the whole pdf file to be pasted as is(without converting to image first)
it turns out that iText can do the same thing.Here is the code for that :
PdfReader reader = new PdfReader("Hello World.pdf");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("RESULT.PDF"));
document.open();
PdfContentByte canvas = writer.getDirectContent();
PdfImportedPage page;
for (int i = 3; i <=6; i++) {
page = writer.getImportedPage(reader, i);
canvas.addTemplate(page, 1f, 0, 0, 1, 0, i*30-250);
}
document.close();
Is it possible to get a cover picture by song and not by album.
Because I have one self combined album with songs and they all have different cover pictures.
But when I want to query them I always get the same picture returned.
String[] ARG_STRING = {MediaStore.Audio.Media.ALBUM_ID};
...
String albumCover = _cursor.getString(_cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
...
MusicUtils.getArtwork(this, -1, Integer.parseInt(albumID));
So i would like to know how it's possible to get an cover image of an song.
I know MusicUtils supports getArtwork by SongId, but what ID should I use because MediaStore.Audio.Media._ID is not working.
I'm not familiar with MusicUtils, however, you should be able to get the cover art from the file itself by using MediaMetadataRetriever. Here is a brief code snippet showing how to use it. The uri referenced is the content uri for the file you want to retrieve the art for.
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
byte[] rawArt;
Bitmap art;
BitmapFactory.Options bfo=new BitmapFactory.Options();
mmr.setDataSource(getApplicationContext(), uri);
rawArt = mmr.getEmbeddedPicture();
// if rawArt is null then no cover art is embedded in the file or is not
// recognized as such.
if (null != rawArt)
art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
// Code that uses the cover art retrieved below.