Created
February 1, 2016 01:57
-
-
Save yakovsh/3f84442e4412558f3645 to your computer and use it in GitHub Desktop.
Remove interpolation flag from images in a pdf file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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