问题
I have an String containing images like "My string [img src=image_from_drawable/] blablabla". I'm able to parse this string as Spannable to show that drawable on my TextView, with the following code:
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;
}
I'm using iText/iTextG library for my Android project in order to create a pdf file.
My question is: Is there an easy way to do this in iText? Write a Phrase or Paragraph containing images? I presume that Chunks would help, but I don't find the way, examples or anything else.
Thanks for your time.
回答1:
Creating a Chunk
with an image is indeed the way to go. Please take a look at this chapter of the ZUGFeRD tutorial: Creating PDF/A files with iText
It has an example that creates text with images that look like this:
This is how it's done:
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);
I hope this helps.
来源:https://stackoverflow.com/questions/35654918/add-an-image-to-itext-pdf-in-android