在Android中将图像添加到iText pdf

时间:2016-02-26 14:55:51

标签: android image itext spannable itextg

我有一个包含图像的字符串,例如“我的字符串[img src = image_from_drawable /] blablabla”。我能够将此字符串解析为Spannable,以便在我的TextView上显示drawable,并使用以下代码:

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;
}

我正在为我的Android项目使用iText / iTextG库来创建一个pdf文件。

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

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

创建带有图像的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);

我希望这会有所帮助。

相关问题