2013-04-01 13 views
6

Ich möchte Bild zu Android PDF mit iText hinzufügen. Ich möchte dies erreichen, ohne zuerst das Bild auf SDCard zu speichern. Ich lege mein Bild in den res/drawbaren Ordner, aber es beweist, dass der Image-Pfad nicht funktioniert und FileNotFound Exception ausgelöst wird. Mein Weg ist dies wie:Bild aus Drawable und Hinzufügen zu PDF mit iText

String path = “res/drawable/myImage.png” 
Image image = Image.getInstance(path); 
document.add(image); 

Jetzt bitte ich um eine Lösung vorschlagen, wie ich korrekten Dateipfad zu getInstance (...) Methode hinzufügen. Danke

Antwort

22

Natürlich wird es auf diese Weise nicht funktionieren.

Ihr Bild Assets Ordner verschieben, darauf zuzugreifen mit getAssets() -Methode

// 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; 
     } 
+0

@NaeemShah i mein Code nur –

+0

aktualisieren kann ich nicht hinzufügen Bitmap-Dokument Methode, nicht vom Typ Bitmap zu unterstützen :( – sns

+0

@NaeemShah werfen Sie einen Blick auf das Update –

1

Hier ist der Code Bild zu PDF mit iText hinzuzufügen, wenn das Bild dynamisch ist (dh), wenn das Bild nicht zum Kompilierzeit,

hinzugefügt werden
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; 
    } 
} 
6

Ich habe eine Lösung für Ihr Problem gefunden. Wenn Sie Bild von Ihrem ziehbar Ordner erhalten möchten und legen Sie sie in eine PDF-Datei mit iText diesen Code verwenden:

try { 
 

 
    document.open(); 
 
\t \t \t \t 
 
    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); \t 
 
\t \t  
 
    document.close(); 
 

 
} catch (Exception e) { 
 
    e.printStackTrace(); 
 
}

+0

Working Great! Genial. – Neela

Verwandte Themen