How to add inline images in iText when using Colum

2019-09-20 08:36发布

问题:

private void processImage(Phrase phrase, Picture picture, ColumnText column)
{
    // TODO Auto-generated method stub
    byte[] pictureData = picture.getContent();
        float ls = 12.0f;
        float multiline = 1.0f;
        column.setLeading(ls, multiline);
        pictureData = WordToPdfUtils.getMetaFileAsImage(pictureData);           

    if (pictureData != null) {
        try {
            Image pic = Image.getInstance(pictureData);
            float[] scwh = scaleInlinePicture(picture);
            pic.scaleAbsolute(scwh[0], scwh[1]);
            phrase.add(new Chunk(pic, 0, 0, true)); 
            column.addText(phrase);         
        } catch (BadElementException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

When i add phrase containing inline image to the ColumnText, the image appears to overlap on the above paragraphs in the generated pdf, how to add inline images while working with ColumnText. A link to sample pdf file generated with the issue is as below

pdf sample with inline picture issue Thank you.

回答1:

Please take a look at the ColumnTextChunkImage example. It adds a text containing images wrapped in a Chunk. The leading is adapted automatically based on the height of the images:

The code to achieve this is very similar to yours:

Image dog = Image.getInstance(DOG);
Image fox = Image.getInstance(FOX);
Phrase p = new Phrase("quick brown fox jumps over the lazy dog.");
p.add("Or, to say it in a more colorful way: quick brown ");
p.add(new Chunk(fox, 0, 0, true));
p.add(" jumps over the lazy ");
p.add(new Chunk(dog, 0, 0, true));
p.add(".");
ColumnText ct = new ColumnText(writer.getDirectContent());
ct.setSimpleColumn(new Rectangle(50, 600, 400, 800));
ct.addText(p);
ct.go();

The only apparent difference I see, is that you use:

column.add(phrase);

This method doesn't exist in the official version of iText. You either have addText() (text mode) or addElement() (composite mode). My guess is that you're using an unofficial version of iText. Unfortunately some individuals have created forks of iText using the FFF principle: Fork, F***, Forget. If you are using such a fork and you don't want to be f***ed or forgotten, please switch to using an official version of iText.



标签: java itext