Example usage for com.itextpdf.text.pdf PRStream put

List of usage examples for com.itextpdf.text.pdf PRStream put

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PRStream put.

Prototype

public void put(final PdfName key, final PdfObject object) 

Source Link

Document

Associates the specified PdfObject as value with the specified PdfName as key in this map.

Usage

From source file:org.h819.commons.file.MyPDFUtils.java

/**
 *  pdf ? pdf//w w  w .  j a  v  a  2  s  . co m
 *
 * @param srcPdf      the original PDF
 * @param destPdf     the resulting PDF
 * @param imageFactor The multiplication factor for the image (?  imageFacto =0.5f)
 * @throws IOException
 * @throws DocumentException
 */
public static void compressPdf(File srcPdf, File destPdf, float imageFactor)
        throws IOException, DocumentException {

    PdfReader reader = new PdfReader(srcPdf.getAbsolutePath());
    int n = reader.getXrefSize();
    PdfObject object;
    PRStream stream;
    // Look for image and manipulate image stream
    for (int i = 0; i < n; i++) {
        object = reader.getPdfObject(i);
        if (object == null || !object.isStream())
            continue;
        stream = (PRStream) object;
        if (!PdfName.IMAGE.equals(stream.getAsName(PdfName.SUBTYPE)))
            continue;
        if (!PdfName.DCTDECODE.equals(stream.getAsName(PdfName.FILTER)))
            continue;
        PdfImageObject image = new PdfImageObject(stream);
        BufferedImage bi = image.getBufferedImage();
        if (bi == null)
            continue;
        int width = (int) (bi.getWidth() * imageFactor);
        int height = (int) (bi.getHeight() * imageFactor);
        if (width <= 0 || height <= 0)
            continue;
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        AffineTransform at = AffineTransform.getScaleInstance(imageFactor, imageFactor);
        Graphics2D g = img.createGraphics();
        g.drawRenderedImage(bi, at);
        ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
        ImageIO.write(img, "JPG", imgBytes);
        stream.clear();
        stream.setData(imgBytes.toByteArray(), false, PRStream.NO_COMPRESSION);
        stream.put(PdfName.TYPE, PdfName.XOBJECT);
        stream.put(PdfName.SUBTYPE, PdfName.IMAGE);
        stream.put(PdfName.FILTER, PdfName.DCTDECODE);
        stream.put(PdfName.WIDTH, new PdfNumber(width));
        stream.put(PdfName.HEIGHT, new PdfNumber(height));
        stream.put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
        stream.put(PdfName.COLORSPACE, PdfName.DEVICERGB);
    }
    reader.removeUnusedObjects();
    // Save altered PDF
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destPdf.getAbsolutePath()));
    stamper.setFullCompression();
    stamper.close();
    reader.close();
}