Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Remove interpolation flag from images in a pdf file
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.parser.PdfImageObject;
import java.io.FileOutputStream;
/**
* This remove the interpolation flag in images in a given PDF file using iText 5.
* Requires: iText 5
*
* For more info, see:
* https://stackoverflow.com/questions/20011515/how-to-remove-anti-aliasing-in-pdf-images
*/
public class RemoveInterpolation {
public static void main(String[] args) {
try {
// Open files.
PdfReader reader = new PdfReader("input.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.pdf"));
// Loop through all objects in the PDF looking for images.
for (int i = 0; i <= reader.getXrefSize(); i++) {
// Only look for non-null objects that are streams.
PdfObject pdfObject = reader.getPdfObject(i);
if (pdfObject == null || !pdfObject.isStream()) {
continue;
}
// Check if the stream, is an image.
PRStream stream = (PRStream) pdfObject;
PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE);
// If stream is an image, get its dictionary and remove the interpolate flag.
if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) {
PdfImageObject imageObject = new PdfImageObject(stream);
PdfDictionary inDict = imageObject.getDictionary();
if (inDict != null) {
inDict.remove(PdfName.INTERPOLATE);
}
}
}
// Close output and input files, then exit.
stamper.close();
reader.close();
} catch(Exception e) {
System.out.println("Unable to process file, exception: " + e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.