I am using itext 5.5.13 to resize images in my pdf. I'm basically following the steps in Chapter 16's ResizeImage.java.
However, for certain PDF files I get a black background for my image. Is this a normal thing, and is there a way to prevent getting black backgrounds?
I tried to extract the image with itext also, and the image appears to have a black background too. This is confusing me, because the original PDF did not have a black background for the image.
I followed the code from this question to extract the image.
How to extract images from a PDF with iText in the correct order?
Here is my code: https://pastebin.com/hN6CTCRP
public static void resizePdf() throws DocumentException, IOException {
String src = "input.pdf";
String dest = "output.pdf";
PdfReader reader = new PdfReader(src);
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();
double factor = .5;
if (bi == null)
continue;
int width = (int) (bi.getWidth() * factor);
int height = (int) (bi.getHeight() * factor);
if (width <= 0 || height <= 0)
continue;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
AffineTransform at = AffineTransform.getScaleInstance(factor, factor);
Graphics2D g = img.createGraphics();
g.drawRenderedImage(bi, at);
System.out.println(image.getFileType());
ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
ImageIO.write(img, image.getFileType(), 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(dest));
stamper.setFullCompression();
stamper.close();
reader.close();
}