I have several methods to manipulate my PDF files, such as convert them to .jpg images to make the compression. Now, I have a pdf file that doesn't have an X-Object, ie, I cannot turn it into jpg to compress them. Then i decided to grab the entire pdf file and try some way to compress it, I tried using iText Stamper and pdfBox.addCompression (deprecated) but none worked so far. Follow:
public static byte[] compressPdf(final byte[] imageBytes) {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()){
final PdfReader reader = new PdfReader(imageBytes);
final PdfStamper stamper = new PdfStamper(reader, out, PdfWriter.VERSION_1_7);
stamper.getWriter().setFullCompression();
stamper.getWriter().setCompressionLevel(9);
int total = reader.getNumberOfPages() + 1;
for (int i = 1; i < total; i++) {
reader.setPageContent(i, reader.getPageContent(i));
}
stamper.close();
reader.close();
return out.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Notice that stamper.fullcompression or stamper.setcompressionlevel aren't working.