Remove pdf image using itext

Asked

Viewed 188 times

1

I am adding image in pdf with itext, but in some moments I need to remove this same image.. How do I do this so as not to corrupt the reading of it? I have tried some ways, as follows::

The first attempt was to clean the streams refente the image

    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));

    for(int i = 0; i < reader.getXrefSize(); i++)
    {
        PdfObject obj = reader.getPdfObject(i);
        if(obj == null)
        {
            continue;
        }

        if(obj.isStream())
        {
            PdfStream stream = (PdfStream) obj;

            PdfObject subtype = stream.get(PdfName.SUBTYPE);

            if(PdfName.IMAGE.equals(subtype))
            {
                stream.clear();
            }
        }
    }

    stamper.close();
    reader.close();

This causes error while reading the file with Adobe Reader, this reader understands that the file is corrupted. Other readers like Foxit works perfectly.

The second attempt was to change the image properties, that is, change the height and width to 1px. However, when changing the properties, it is still a "film" of the same size of the image, which I cannot remove

   PdfReader reader = new PdfReader(src);
   PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));

    for(int i = 0; i < reader.getXrefSize(); i++)
    {
        PdfObject obj = reader.getPdfObject(i);
        if(obj == null)
        {
            continue;
        }

        if(obj.isStream())
        {
            PdfStream stream = (PdfStream) obj;

            PdfObject subtype = stream.get(PdfName.SUBTYPE);

            if(PdfName.IMAGE.equals(subtype))
            {
                stream.put(PdfName.WIDTH, new PdfNumber(1));
                stream.put(PdfName.HEIGHT, new PdfNumber(1));
            }
        }
    }

    stamper.close();
    reader.close();

Would anyone know what I can do to remove the image?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.