List of usage examples for com.itextpdf.text.pdf PdfName SUBTYPE
PdfName SUBTYPE
To view the source code for com.itextpdf.text.pdf PdfName SUBTYPE.
Click Source Link
From source file:cz.muni.pdfjbim.PdfImageExtractor.java
License:Apache License
/** * Extracts JBIG2Images from Input stream even if they are stored together with global dictionary in separate PDF object * doesn't work yet, its in development stage * @param is/*from w ww.j a va 2 s.c o m*/ * @throws PdfRecompressionException * @deprecated */ public void extractJbig2Images(InputStream is) throws PdfRecompressionException { if (is == null) { throw new IllegalArgumentException("InputStream not given"); } PdfReader pdfReader = null; try { pdfReader = new PdfReader(is); for (int i = 0; i <= pdfReader.getNumberOfPages(); i++) { PdfDictionary d = pdfReader.getPageN(i); PdfIndirectReference ir = d.getAsIndirectObject(PdfName.CONTENTS); PdfObject o = pdfReader.getPdfObject(ir.getNumber()); PdfStream stream = (PdfStream) o; PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE); if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) { byte[] img = PdfReader.getStreamBytesRaw((PRStream) stream); OutputStream out = new FileOutputStream( new File("pdfRecompressor", String.format("%1$05d", i) + ".jpg")); out.write(img); out.flush(); out.close(); } } } catch (IOException ex) { log.error("IOException caught while trying to extract jbig2 images from PDF", ex); throw new PdfRecompressionException("IOException caught while trying to extract jbig2 images from PDF", ex); } finally { if (pdfReader != null) { pdfReader.close(); } } }
From source file:cz.muni.pdfjbim.PdfImageExtractor.java
License:Apache License
private List<Image> getImagesFromPdfDict(PdfDictionary dict, PdfReader doc) throws IOException { List<Image> images = new ArrayList<Image>(); PdfDictionary res = (PdfDictionary) (PdfReader.getPdfObject(dict.get(PdfName.RESOURCES))); PdfDictionary xobj = (PdfDictionary) (PdfReader.getPdfObject(res.get(PdfName.XOBJECT))); if (xobj != null) { for (PdfName name : xobj.getKeys()) { PdfObject obj = xobj.get(name); if (obj.isIndirect()) { PdfDictionary tg = (PdfDictionary) (PdfReader.getPdfObject(obj)); PdfName subtype = (PdfName) (PdfReader.getPdfObject(tg.get(PdfName.SUBTYPE))); if (PdfName.IMAGE.equals(subtype)) { int xrefIdx = ((PRIndirectReference) obj).getNumber(); PdfObject pdfObj = doc.getPdfObject(xrefIdx); PdfStream str = (PdfStream) (pdfObj); byte[] bytes = PdfReader.getStreamBytesRaw((PRStream) str); String filter = tg.get(PdfName.FILTER).toString(); String width = tg.get(PdfName.WIDTH).toString(); String height = tg.get(PdfName.HEIGHT).toString(); String bpp = tg.get(PdfName.BITSPERCOMPONENT).toString(); if ("/FlateDecode".equals(filter)) { bytes = PdfReader.FlateDecode(bytes, true); try { images.add(Image.getInstance(bytes)); } catch (BadElementException ex) { log.warn("problem to process FlatDecoded Image", ex); }// www.j a va 2 s.c o m } else if (PdfName.FORM.equals(subtype) || PdfName.GROUP.equals(subtype)) { images.addAll(getImagesFromPdfDict(tg, doc)); } } } } } return images; }
From source file:cz.muni.pdfjbim.PdfImageProcessor.java
License:Apache License
/** * replace images by they recompressed version according to JBIG2 standard * positions and image data given in imagesData * @param pdfName represents name of original PDF file * @param os represents output stream for writing changed PDF file * @param imagesData contains compressed images according to JBIG2 standard and informations about them * @throws PdfRecompressionException if version of PDF is lower than 1.4 or was catch DocumentException or IOException *//*from w w w . j a va 2s.c o m*/ public void replaceImageUsingIText(String pdfName, OutputStream os, Jbig2ForPdf imagesData) throws PdfRecompressionException { if (pdfName == null) { throw new NullPointerException("pdfName"); } if (os == null) { throw new NullPointerException("os"); } if (imagesData == null) { throw new NullPointerException("imagesData is null => nothing to recompress"); } Map<PdfObjId, PdfImage> jbig2Images = imagesData.getMapOfJbig2Images(); PdfReader pdf; PdfStamper stp = null; try { pdf = new PdfReader(pdfName); stp = new PdfStamper(pdf, os); PdfWriter writer = stp.getWriter(); int version; if ((version = Integer.parseInt(String.valueOf(pdf.getPdfVersion()))) < 4) { writer.setPdfVersion(PdfWriter.PDF_VERSION_1_4); } Iterator itImages = jbig2Images.values().iterator(); String key; if (itImages.hasNext()) { PdfImage myImg = (PdfImage) itImages.next(); key = myImg.getPdfImageInformation().getKey(); } else { key = "im0"; } for (int pageNum = 1; pageNum <= pdf.getNumberOfPages(); pageNum++) { PdfDictionary pg = pdf.getPageN(pageNum); PdfDictionary resPg = (PdfDictionary) PdfReader.getPdfObject(pg.get(PdfName.RESOURCES)); PdfDictionary xobjResPg = (PdfDictionary) PdfReader.getPdfObject(resPg.get(PdfName.XOBJECT)); PdfObject obj = null; if (xobjResPg != null) { for (Iterator it = xobjResPg.getKeys().iterator(); it.hasNext();) { PdfObject pdfObjIndirect = xobjResPg.get((PdfName) it.next()); if (pdfObjIndirect.isIndirect()) { PdfDictionary pdfObj2 = (PdfDictionary) PdfReader.getPdfObject(pdfObjIndirect); PdfDictionary xobj2Res = (PdfDictionary) PdfReader .getPdfObject(pdfObj2.get(PdfName.RESOURCES)); if (xobj2Res != null) { for (Iterator it2 = xobj2Res.getKeys().iterator(); it2.hasNext();) { PdfObject resObj = xobj2Res.get((PdfName) it2.next()); } PdfDictionary xobj = (PdfDictionary) PdfReader .getPdfObject(xobj2Res.get(PdfName.XOBJECT)); if (xobj == null) { continue; } obj = xobj.get(new PdfName(key)); } else { obj = xobjResPg.get(new PdfName(key)); if (obj == null) { obj = pdfObjIndirect; } } } } } if ((obj != null) && (obj.isIndirect())) { PdfDictionary tg = (PdfDictionary) PdfReader.getPdfObject(obj); if (tg == null) { continue; } PdfName type = (PdfName) PdfReader.getPdfObject(tg.get(PdfName.SUBTYPE)); if (PdfName.IMAGE.equals(type)) { PRIndirectReference ref = (PRIndirectReference) obj; PdfObjId imId = new PdfObjId(ref.getNumber(), ref.getGeneration()); PdfImage jbImage = jbig2Images.get(imId); if (jbImage == null) { continue; } PdfImageInformation jbImageInfo = jbImage.getPdfImageInformation(); Image img = Image.getInstance(jbImageInfo.getWidth(), jbImageInfo.getHeight(), jbImage.getImageData(), imagesData.getGlobalData()); PdfReader.killIndirect(obj); Image maskImage = img.getImageMask(); if (maskImage != null) { writer.addDirectImageSimple(maskImage); } writer.addDirectImageSimple(img, (PRIndirectReference) obj); } } } stp.close(); } catch (IOException ioEx) { throw new PdfRecompressionException(ioEx); } catch (DocumentException dEx) { throw new PdfRecompressionException(dEx); } finally { Tools.deleteFilesFromList(imagesData.getJbFiles().toArray(new File[0])); } }
From source file:cz.muni.pdfjbim.PdfImageReplacer.java
License:Apache License
/** * replace images by they recompressed version according to JBIG2 standard positions and image * data given in imagesData/*from w w w . ja v a 2s .co m*/ * * @param originalPdf represents name of original PDF file * @param os represents output stream for writing changed PDF file * @param imagesData contains compressed images according to JBIG2 standard and informations * about them * @throws PdfRecompressionException if version of PDF is lower than 1.4 or was catch * DocumentException or IOException */ public void replaceImageUsingIText(InputStream originalPdf, OutputStream os, List<Jbig2ForPdf> imagesDataList) throws PdfRecompressionException { if (originalPdf == null) { throw new NullPointerException("pdfName"); } if (os == null) { throw new NullPointerException("os"); } if (imagesDataList == null) { throw new NullPointerException("imagesData is null => nothing to recompress"); } log.info("Replacing old images in PDF with their equivalent encoded according to standard JBIG2"); PdfReader pdf; PdfStamper stp = null; try { pdf = new PdfReader(originalPdf); stp = new PdfStamper(pdf, os); PdfWriter writer = stp.getWriter(); int version; if ((version = Integer.parseInt(String.valueOf(pdf.getPdfVersion()))) < 4) { log.debug("PDF version of original PDF was {} => changing to PDF version 1.4", pdf.getPdfVersion()); writer.setPdfVersion(PdfWriter.PDF_VERSION_1_4); } for (Jbig2ForPdf imagesData : imagesDataList) { Map<PdfObjId, PdfImage> jbig2Images = imagesData.getMapOfJbig2Images(); Iterator itImages = jbig2Images.values().iterator(); String key; if (itImages.hasNext()) { PdfImage myImg = (PdfImage) itImages.next(); key = myImg.getPdfImageInformation().getKey(); } else { key = "im0"; } for (int pageNum = 1; pageNum <= pdf.getNumberOfPages(); pageNum++) { PdfDictionary pg = pdf.getPageN(pageNum); PdfDictionary resPg = (PdfDictionary) PdfReader.getPdfObject(pg.get(PdfName.RESOURCES)); PdfDictionary xobjResPg = (PdfDictionary) PdfReader.getPdfObject(resPg.get(PdfName.XOBJECT)); PdfObject obj = null; if (xobjResPg != null) { for (Iterator it = xobjResPg.getKeys().iterator(); it.hasNext();) { PdfObject pdfObjIndirect = xobjResPg.get((PdfName) it.next()); if (pdfObjIndirect.isIndirect()) { PdfDictionary pdfObj2 = (PdfDictionary) PdfReader.getPdfObject(pdfObjIndirect); PdfDictionary xobj2Res = (PdfDictionary) PdfReader .getPdfObject(pdfObj2.get(PdfName.RESOURCES)); if (xobj2Res != null) { for (Iterator it2 = xobj2Res.getKeys().iterator(); it2.hasNext();) { PdfObject resObj = xobj2Res.get((PdfName) it2.next()); } PdfDictionary xobj = (PdfDictionary) PdfReader .getPdfObject(xobj2Res.get(PdfName.XOBJECT)); if (xobj == null) { continue; } obj = xobj.get(new PdfName(key)); } else { obj = xobjResPg.get(new PdfName(key)); if (obj == null) { obj = pdfObjIndirect; } } } } } if ((obj != null) && (obj.isIndirect())) { PdfDictionary tg = (PdfDictionary) PdfReader.getPdfObject(obj); if (tg == null) { continue; } PdfName type = (PdfName) PdfReader.getPdfObject(tg.get(PdfName.SUBTYPE)); if (PdfName.IMAGE.equals(type)) { PRIndirectReference ref = (PRIndirectReference) obj; PdfObjId imId = new PdfObjId(ref.getNumber(), ref.getGeneration()); PdfImage jbImage = jbig2Images.get(imId); if (jbImage == null) { continue; } log.debug("Replacing image {}", jbImage); PdfImageInformation jbImageInfo = jbImage.getPdfImageInformation(); Image img = Image.getInstance(jbImageInfo.getWidth(), jbImageInfo.getHeight(), jbImage.getImageData(), imagesData.getGlobalData()); PdfReader.killIndirect(obj); Image maskImage = img.getImageMask(); if (maskImage != null) { writer.addDirectImageSimple(maskImage); } writer.addDirectImageSimple(img, (PRIndirectReference) obj); } } } } } catch (IOException ioEx) { throw new PdfRecompressionException(ioEx); } catch (DocumentException dEx) { throw new PdfRecompressionException(dEx); } finally { log.debug("Deleting temporary files created during process of PDF recompression"); for (Jbig2ForPdf imagesData : imagesDataList) { Tools.deleteFilesFromList(imagesData.getJbFiles().toArray(new File[0])); } try { if (stp != null) { stp.close(); } } catch (DocumentException ex) { log.error("Exception thrown while closing stream", ex); } catch (IOException ex) { log.error("Exception thrown while closing stream", ex); } } }
From source file:de.gbv.marginalia.Annotation.java
License:Open Source License
/** * Constructs a new Annotation from a given PdfDictionary. * Of course the PdfDictionary should contain an annotation. *///from w w w.j a v a 2 s. c o m // public Annotation(PdfDictionary annot) { this.Annotation(annot,0); } public Annotation(PdfDictionary annot, int pageNum) { this.pageNum = pageNum; this.subtype = annot.getAsName(PdfName.SUBTYPE); // text | caret | freetext | fileattachment | highlight | ink | line | link | circle | square | // polygon | polyline | sound | squiggly | stamp | strikeout | underline this.content = annot.getAsString(PdfName.CONTENTS); this.popup = getAsDictionary(annot, PdfName.POPUP); // TODO: skipped fields: // getAsDictionary(annot,PdfName.AP); // alternative to coords! // annot.getAsName(PdfName.AS); // getAsDictionary(annot,PdfName.A); // action // getAsDictionary(annot,PdfName.A); // additional action // annot.getAsNumber(PdfName.STRUCTPARENT); // Since PDF 1.5: // RC = contents-richtext this.dict = annot; }
From source file:de.gbv.marginalia.Annotation.java
License:Open Source License
/** * Serialize the annotation in XML format. * The annotation is emitted as stream of SAX events to a ContentHandler. * The XML is XFDF with additional Marginalia elements in its own namespace. *//* w w w. ja v a2 s. c o m*/ public void serializeXML(ContentHandler handler) throws SAXException { SimpleXMLCreator xml = new SimpleXMLCreator(handler, namespaces); Set<PdfName> allkeys = this.dict.getKeys(); allkeys.remove(PdfName.TYPE); allkeys.remove(PdfName.SUBTYPE); allkeys.remove(PdfName.PARENT); allkeys.remove(PdfName.CONTENTS); allkeys.remove(PdfName.POPUP); Map<String, String> attrs = new HashMap<String, String>(); for (String aName : this.FIELDS.keySet()) { Field f = this.FIELDS.get(aName); String value = f.getFrom(this.dict); if (value != null) { // TODO: encoding & exception attrs.put(aName, value); // allkeys.remove( f.name ); } } PdfDictionary pg = getAsDictionary(this.dict, PdfName.P); allkeys.remove(PdfName.P); //CropBox=[0, 0, 595, 842] //Rotate //MediaBox=[0, 0, 595, 842] // TODO: find out where page number is stored if (attrs.get("page") == null) attrs.put("page", "" + this.pageNum); String element = subtypes.get(this.subtype); if (element == null) { // TODO element = this.subtype.toString(); } xml.startElement(element, attrs); if (element.equals("ink")) { PdfArray inklist = this.dict.getAsArray(new PdfName("InkList")); if (inklist != null) { xml.startElement("inklist"); for (int i = 0; i < inklist.size(); i++) { PdfArray pathArray = inklist.getAsArray(i); String s = ""; for (int j = 0; j < pathArray.size(); j += 2) { if (j > 0) s += ";"; s += "" + pathArray.getAsNumber(j).floatValue() + ","; s += "" + pathArray.getAsNumber(j + 1).floatValue(); } xml.contentElement("gesture", s); } xml.endElement(); } } if (attrs.get("rect") != null) { Map<String, String> a = new HashMap<String, String>(); RectField rf = (RectField) this.FIELDS.get("rect"); PdfRectangle r = null; if (rf != null) r = (PdfRectangle) rf.getObjectFrom(this.dict); if (r != null) { a.put("left", "" + r.left()); a.put("bottom", "" + r.bottom()); a.put("right", "" + r.right()); a.put("top", "" + r.top()); xml.emptyElement("m", "rect", a); } } if (this.content != null && !this.content.equals("")) { // TODO: encode content if not UTF-8 ? xml.contentElement("content", content.toString()); } // TODO: contents-richtext // TODO: popup /* if ( this.popup != null ) { out.println("<!--popup>"); for ( PdfName n : this.popup.getKeys() ) { out.println( n + "=" + this.popup.getDirectObject(n) ); } out.println("</popup-->"); } */ // remaining dictionary elements /* for ( PdfName name : allkeys ) { Map<String,String> a = new HashMap<String,String>(); a.put("name",name.toString()); a.put("value",this.dict.getDirectObject(name).toString()); xml.emptyElement( "m","unknown", a ); } */ xml.endElement(); }
From source file:mkl.testarea.itext5.pdfcleanup.PdfCleanUpContentOperator.java
License:Open Source License
public void invoke(PdfContentStreamProcessor pdfContentStreamProcessor, PdfLiteral operator, ArrayList<PdfObject> operands) throws Exception { String operatorStr = operator.toString(); PdfContentByte canvas = cleanUpStrategy.getContext().getCanvas(); PRStream xFormStream = null;//from w w w . j a v a2 s . c o m boolean disableOutput = pathConstructionOperators.contains(operatorStr) || pathPaintingOperators.contains(operatorStr) || clippingPathOperators.contains(operatorStr); GraphicsState gs = pdfContentStreamProcessor.gs(); // key - number of a string in the TJ operator, value - number following the string; the first number without string (if it's presented) is stored under 0. // BE AWARE: zero-length strings are ignored!!! Map<Integer, Float> structuredTJoperands = null; if ("Do".equals(operatorStr)) { if (operands.size() == 2 && operands.get(0).isName()) { PdfDictionary xObjResources = cleanUpStrategy.getContext().getResources() .getAsDict(PdfName.XOBJECT); if (xObjResources != null) { PdfStream xObj = xObjResources.getAsStream((PdfName) operands.get(0)); if (xObj instanceof PRStream && xObj.getAsName(PdfName.SUBTYPE) != null && xObj.getAsName(PdfName.SUBTYPE).compareTo(PdfName.FORM) == 0) { xFormStream = (PRStream) xObj; cleanUpStrategy.registerNewContext(xObj.getAsDict(PdfName.RESOURCES), null); } } } } originalContentOperator.invoke(pdfContentStreamProcessor, operator, operands); List<PdfCleanUpContentChunk> chunks = cleanUpStrategy.getChunks(); if (xFormStream != null) { xFormStream.setData(cleanUpStrategy.getContext().getCanvas() .toPdf(cleanUpStrategy.getContext().getCanvas().getPdfWriter())); cleanUpStrategy.popContext(); canvas = cleanUpStrategy.getContext().getCanvas(); } if ("Do".equals(operatorStr)) { if (chunks.size() > 0 && chunks.get(0) instanceof PdfCleanUpContentChunk.Image) { PdfCleanUpContentChunk.Image chunk = (PdfCleanUpContentChunk.Image) chunks.get(0); if (chunk.isVisible()) { PdfDictionary xObjResources = cleanUpStrategy.getContext().getResources() .getAsDict(PdfName.XOBJECT); PRStream imageStream = (PRStream) xObjResources.getAsStream((PdfName) operands.get(0)); updateImageStream(imageStream, chunk.getNewImageData()); } else { disableOutput = true; } } } else if (lineStyleOperators.contains(operatorStr)) { disableOutput = true; } else if (textShowingOperators.contains(operatorStr) && !allChunksAreVisible(cleanUpStrategy.getChunks())) { disableOutput = true; if ("'".equals(operatorStr)) { canvas.getInternalBuffer().append(TStar); } else if ("\"".equals(operatorStr)) { operands.get(0).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer()); canvas.getInternalBuffer().append(Tw); operands.get(1).toPdf(canvas.getPdfWriter(), canvas.getInternalBuffer()); canvas.getInternalBuffer().append(TcTStar); } else if ("TJ".equals(operatorStr)) { structuredTJoperands = structureTJarray((PdfArray) operands.get(0)); } writeTextChunks(structuredTJoperands, chunks, canvas, gs.getCharacterSpacing(), gs.getWordSpacing(), gs.getFontSize(), gs.getHorizontalScaling()); } else if (pathPaintingOperators.contains(operatorStr)) { writePath(operatorStr, canvas, gs.getColorSpaceStroke()); } else if (strokeColorOperators.contains(operatorStr)) { // Replace current color with the new one. cleanUpStrategy.getContext().popStrokeColor(); cleanUpStrategy.getContext().pushStrokeColor(operands); } else if ("q".equals(operatorStr)) { cleanUpStrategy.getContext().pushStrokeColor(cleanUpStrategy.getContext().peekStrokeColor()); } else if ("Q".equals(operatorStr)) { cleanUpStrategy.getContext().popStrokeColor(); } if (!disableOutput) { writeOperands(canvas, operands); } cleanUpStrategy.clearChunks(); }
From source file:mkl.testarea.itext5.pdfcleanup.StrictPdfCleanUpProcessor.java
License:Open Source License
/** * Extracts locations from the redact annotations contained in the document and applied to the given page. *//*from w w w .j a v a2s . c o m*/ private List<PdfCleanUpLocation> extractLocationsFromRedactAnnots(int page, PdfDictionary pageDict) { List<PdfCleanUpLocation> locations = new ArrayList<PdfCleanUpLocation>(); if (pageDict.contains(PdfName.ANNOTS)) { PdfArray annotsArray = pageDict.getAsArray(PdfName.ANNOTS); for (int i = 0; i < annotsArray.size(); ++i) { PdfIndirectReference annotIndirRef = annotsArray.getAsIndirectObject(i); PdfDictionary annotDict = annotsArray.getAsDict(i); PdfName annotSubtype = annotDict.getAsName(PdfName.SUBTYPE); if (annotSubtype.equals(PdfName.REDACT)) { saveRedactAnnotIndirRef(page, annotIndirRef.toString()); locations.addAll(extractLocationsFromRedactAnnot(page, i, annotDict)); } } } return locations; }
From source file:org.gmdev.pdftrick.engine.CheckFiles.java
License:Open Source License
/** * Check the number of images contained in the file's selection, if == 0 return false. * @param filesVett/* w ww .j a v a 2 s. c o m*/ * @param messages * @return TRUE if the there is at least one image in the PDF files selection. */ private boolean checkNumberImages(ArrayList<File> filesVett, Properties messages) { boolean checkNumImg = false; Iterator<File> ite = filesVett.iterator(); while (ite.hasNext()) { File item = ite.next(); PdfReader reader = null; try { if (namePwd.containsKey(item.getName())) { reader = new PdfReader(item.getPath(), namePwd.get(item.getName()).getBytes()); } else { reader = new PdfReader(item.getPath()); } for (int i = 0; i < reader.getXrefSize(); i++) { PdfObject pdfobj = reader.getPdfObject(i); if (pdfobj == null || !pdfobj.isStream()) { continue; } PdfStream stream = (PdfStream) pdfobj; PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE); if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) { checkNumImg = true; break; } } if (checkNumImg) { break; } } catch (IOException e) { logger.error("Exception", e); PdfTrickMessages.append("ERROR", Consts.SENDLOG_MSG); } } if (!checkNumImg) { PdfTrickMessages.append("WARNING", messages.getProperty("tmsg_21")); } return checkNumImg; }
From source file:org.h819.commons.file.MyPDFUtils.java
/** * pdf ? pdf// w ww.jav a 2s. c o 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(); }