malditoraton.com

Eliminar imágenes de PDF con Java y iText

by Marat on May.26, 2011, under Java

A pesar del título, ya avanzo que no se trata de eliminar imégenes sino de ocultarlas a la vista y redimensionandolas para que no pesen. En mi deformación de copia-pega y después de buscar código que me permitiese eliminar todas las imágenes de un archivo pdf,me dí cuenta que la mejor solución sería utilizar las librerías de iText.

Con estas librerías podría redimensionar las imágenes existentes en el pdf. El código, completamente funcional que se presenta a continuación lo permite. Está basado en un código traducido de C# cuyo autor no he conseguido encontrar ( y a quien estaré encantado en atribuir si alguien me lo proporciona) y en un ejemplo propio de iText para redimensionar imágenes con referencia conocida.

La ventaja de mi código es que lee cualquier archivo sin protección, “oculta” todas las imágenes de todas las páginas y con cambios menores puede personalizarse cuantas y cuáles imágenes serán ocultadas.

En contados documentos, en algunos dispositivos como eReaders, teléfonos,… o versiones antiguas de Adobe Acrobat Reader puede ocasionar un ocultamiento del texto. Se investigará

 

/*
 * ResizeImage.java
 * =========================
 * ===    ResizeImage       ===
 * =========================
 * ResizeImage is a sample, about resampling images within a PDF file
 * Some information is available at http://www.malditoraton.com/erase-pdf-images-itext/
 * Copyright (c) 2011 Owners ofwww.malditoraton.com,
 *
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author http://www.malditoraton.com
 */
package resizeimage;
 
import java.io.FileOutputStream;
import java.util.Iterator; 
 
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfObject;
import com.itextpdf.text.pdf.PRStream;
import com.itextpdf.text.pdf.PdfNumber;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.parser.PdfImageObject;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
 
public class ResizeImage {
    public static String SOURCE = "Full path to any pdf existing file";
    public static String RESULT = "Full path to the new pdf file";
    public static float FACTOR = 0.99f;
    static  String pdfFileName;
    static int i=1;
    public static void main(String[] args) {
        try { 
 
            PdfReader readPdf = new PdfReader(SOURCE);
            int n = readPdf.getNumberOfPages();
            while(i<=n){
                PdfDictionary pagDictionary = readPdf.getPageN(i);
                PdfDictionary resDictionary = (PdfDictionary)PdfReader.getPdfObject(pagDictionary.get(PdfName.RESOURCES));
                PdfDictionary xobDictionary = (PdfDictionary)PdfReader.getPdfObject(resDictionary.get(PdfName.XOBJECT));
                if (xobDictionary != null) {
                    for (Iterator it = xobDictionary.getKeys().iterator(); it.hasNext(); ) {
                        PdfObject objPdf = xobDictionary.get((PdfName)it.next());
                        if (objPdf != null || objPdf.isStream()/*obj.isIndirect()*/) {
                            PdfDictionary odfDictionary = (PdfDictionary)PdfReader.getPdfObject(objPdf);
                            if (odfDictionary == null) {continue;}
                            PdfObject stObject = odfDictionary.get(PdfName.SUBTYPE);
                            if (stObject == null) {continue;}
                            PdfName type = (PdfName)PdfReader.getPdfObject(stObject);
                            if (PdfName.IMAGE.equals(type)){
                                PdfObject obdObject = PdfReader.getPdfObject(objPdf,xobDictionary);
                                PdfReader.killIndirect(objPdf);
                                PRStream odbStream = (PRStream)obdObject;
                                PdfImageObject image = new PdfImageObject(odbStream);
                                BufferedImage bi = image.getBufferedImage();
                                if (bi == null) continue;
                                int width = (int)(bi.getWidth() * FACTOR);
                                int height = (int)(bi.getHeight() * FACTOR);
                                if(width==0) width = 1;
                                if(height==0) height = 1;
                                BufferedImage img = new BufferedImage(width,
                                        height, BufferedImage.TYPE_INT_RGB);
                                AffineTransform at = AffineTransform.getScaleInstance(FACTOR, FACTOR);
                                Graphics2D g = img.createGraphics();
                                g.drawRenderedImage(bi, at);
                                ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
                                ImageIO.write(img, "JPG", imgBytes);
                                odbStream.clear();
                                odbStream.setData(imgBytes.toByteArray(), false, PRStream.BEST_SPEED);
                                odbStream.put(PdfName.TYPE, PdfName.XOBJECT);
                                odbStream.put(PdfName.SUBTYPE, PdfName.IMAGE);
                                odbStream.put(PdfName.FILTER, PdfName.DCTDECODE);
                                odbStream.put(PdfName.WIDTH, new PdfNumber(width));
                                odbStream.put(PdfName.HEIGHT, new PdfNumber(height));
                                odbStream.put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
                                odbStream.put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                            } 
 
                        }
                    }
                }
                i=i+1;
            }
            FileOutputStream foStream = new FileOutputStream(RESULT);
            PdfStamper stamper = new PdfStamper(readPdf, foStream);
            stamper.close();
        }
        catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

:,

Leave a Reply

You must be logged in to post a comment.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!