Stephy Samaniego
Stephy Samaniego

Reputation: 242

Add a Bitmap image in a PDF document in Android

please, how can i directly pass a bitmap image to a pdf file. I have made a graph with GraphView and at the end i convert it to Bitmap, inside an OnClickListener:

write.setOnClickListener(new View.OnClickListener() 
{
        @Override
        public void onClick(View arg0) {
            Bitmap bitmap;
            graph.setDrawingCacheEnabled(true);
            bitmap = Bitmap.createBitmap(graph.getDrawingCache());
            graph.setDrawingCacheEnabled(false);
            String filename = "imagen";
            FileOperations fop = new FileOperations();
            fop.write(filename, bitmap);
            if (fop.write(filename,bitmap)) {
                Toast.makeText(getApplicationContext(),
                        filename + ".pdf created", Toast.LENGTH_SHORT)
                        .show();
            } else {
                Toast.makeText(getApplicationContext(), "I/O error",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });

The problem is that in the class FileOperations:

public FileOperations() {
}

public Boolean write(String fname, Bitmap bm) {
    try {
        String fpath = "/sdcard/" + fname + ".pdf";
        File file = new File(fpath);
        if (!file.exists()) {
            file.createNewFile();
        }
        Document document = new Document();
        PdfWriter.getInstance(document,
                new FileOutputStream(file.getAbsoluteFile()));
        document.open();
        String filename = bm.toString();
        com.itextpdf.text.Image image  =com.itextpdf.text.Image.getInstance(filename);
        document.add(image);
        document.add(new Paragraph("Hello World2!"));
        // step 5
        document.close();

        Log.d("Suceess", "Sucess");
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
}
}

I want to know how can i pass the bitmap Image to add it in the pdf document, i do this but i think this works only when i give it a path.

String filename = bm.toString(); com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance(filename);

Upvotes: 5

Views: 11655

Answers (1)

Stephy Samaniego
Stephy Samaniego

Reputation: 242

I just solve it:

        document.open();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
        Image myImg = Image.getInstance(stream.toByteArray());
        myImg.setAlignment(Image.MIDDLE);
        document.add(myImg);

in the FileOperations class

Upvotes: 11

Related Questions