2016-02-26 56 views
2

我有一个包含如 “我串[IMG SRC = image_from_drawable /] blablabla” 图像的字符串。我能够解析这个字符串作为Spannable展现在我的TextView是绘制,用下面的代码:的图像添加到iText的PDF Android中

static public Spannable formatAbility(String _ability) { 
    Spannable spannable = spannableFactory.newSpannable(_ability); 
    addImages(mContext, spannable); 
    return spannable; 
} 

private static boolean addImages(Context context, Spannable spannable) { 
    Pattern refImg = Pattern 
      .compile("\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E"); 
    boolean hasChanges = false; 

    Matcher matcher = refImg.matcher(spannable); 
    while (matcher.find()) { 
     boolean set = true; 
     for (ImageSpan span : spannable.getSpans(matcher.start(), 
       matcher.end(), ImageSpan.class)) { 
      if (spannable.getSpanStart(span) >= matcher.start() 
        && spannable.getSpanEnd(span) <= matcher.end()) { 
       spannable.removeSpan(span); 
      } else { 
       set = false; 
       break; 
      } 
     } 
     String resname = spannable 
       .subSequence(matcher.start(1), matcher.end(1)).toString() 
       .trim(); 
     int id = context.getResources().getIdentifier(resname, "drawable", 
       context.getPackageName()); 

     if (set) { 
      hasChanges = true; 

      spannable.setSpan(new ImageSpan(context, id, 
        ImageSpan.ALIGN_BASELINE), matcher.start(), matcher 
        .end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
     } 
    } 

    return hasChanges; 
} 

我为了创建一个PDF文件利用iText/iTextG库我的Android项目。

我的问题是:有没有一种简单的方法可以在iText中做到这一点?写一个包含图像的短语或段落?我认为Chunks会有所帮助,但我不会找到方式,例子或其他任何东西。

谢谢你的时间。

回答

1

创建具有图像的Chunk确实是要走的路。请看看在ZUGFeRD教程的这一章在:Creating PDF/A files with iText

它有一个创建了图片中的文字看起来像这样的一个例子:

enter image description here

这是它是如何做:

Paragraph p = new Paragraph(); 
Chunk c = new Chunk("The quick brown "); 
p.add(c); 
Image i = Image.getInstance("resources/images/fox.bmp""); 
c = new Chunk(i, 0, -24); 
p.add(c); 
c = new Chunk(" jumps over the lazy "); 
p.add(c); 
i = Image.getInstance("resources/images/dog.bmp""); 
c = new Chunk(i, 0, -24); 
p.add(c); 
document.add(p); 

我希望这有助于。

+0

谢谢。大块是答案。这个例子有很多帮助! –

相关问题