Example usage for com.lowagie.text.pdf PdfStamper getOverContent

List of usage examples for com.lowagie.text.pdf PdfStamper getOverContent

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfStamper getOverContent.

Prototype

public PdfContentByte getOverContent(int pageNum) 

Source Link

Document

Gets a PdfContentByte to write over the page of the original document.

Usage

From source file:com.ikon.util.PDFUtils.java

License:Open Source License

public static void stampImage(InputStream input, byte[] image, int layer, float opacity, String exprX,
        String exprY, OutputStream output)
        throws FileNotFoundException, DocumentException, EvalError, IOException {
    log.debug("stampImage({}, {}, {}, {}, {}, {}, {})", new Object[] { input, image, Integer.valueOf(layer),
            Float.valueOf(opacity), exprX, exprY, output });
    Image img = Image.getInstance(image);
    PdfReader reader = new PdfReader(input);
    PdfStamper stamper = new PdfStamper(reader, output);
    PdfGState gs = new PdfGState();
    gs.setFillOpacity(opacity);//from   ww  w .jav a  2  s .c o m
    gs.setStrokeOpacity(opacity);
    int numPages = reader.getNumberOfPages();
    int count = 0;

    while (count++ < numPages) {
        int pageCenter = (int) reader.getPageSizeWithRotation(count).getWidth() / 2;
        int pageMiddle = (int) reader.getPageSizeWithRotation(count).getHeight() / 2;

        Interpreter i = new Interpreter();
        i.set("IMAGE_WIDTH", (int) img.getWidth());
        i.set("IMAGE_HEIGHT", (int) img.getHeight());
        i.set("PAGE_WIDTH", (int) reader.getPageSizeWithRotation(count).getWidth());
        i.set("PAGE_HEIGHT", (int) reader.getPageSizeWithRotation(count).getHeight());
        i.set("PAGE_CENTER", pageCenter);
        i.set("PAGE_MIDDLE", pageMiddle);
        Integer evalX = (Integer) i.eval(exprX);
        Integer evalY = (Integer) i.eval(exprY);

        if (evalX == null)
            evalX = Integer.valueOf(pageCenter);
        if (evalY == null) {
            evalY = Integer.valueOf(pageMiddle);
        }
        log.debug("evalX: {}", evalX);
        log.debug("evalY: {}", evalY);

        img.setAbsolutePosition(evalX.intValue(), evalY.intValue());
        PdfContentByte cb = null;

        if (layer == LAYER_UNDER_CONTENT)
            cb = stamper.getUnderContent(count);
        else if (layer == LAYER_OVER_CONTENT)
            cb = stamper.getOverContent(count);
        else {
            throw new IllegalArgumentException();
        }

        cb.saveState();
        cb.setGState(gs);
        cb.addImage(img);
        cb.restoreState();
    }

    stamper.close();
}

From source file:com.ikon.util.PDFUtils.java

License:Open Source License

public static void stampText(InputStream input, String text, int layer, float opacity, int size, Color color,
        int rotation, int align, String exprX, String exprY, OutputStream output)
        throws FileNotFoundException, DocumentException, EvalError, IOException {
    log.debug("stampText({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {})",
            new Object[] { input, text, Integer.valueOf(layer), Float.valueOf(opacity), Integer.valueOf(size),
                    color, Integer.valueOf(rotation), Integer.valueOf(align), exprX, exprY, output });

    BaseFont bf = getBaseFont();/*from  w ww .  j av  a2s.  co  m*/
    PdfReader reader = new PdfReader(input);
    PdfStamper stamper = new PdfStamper(reader, output);
    PdfGState gs = new PdfGState();
    gs.setFillOpacity(opacity);
    gs.setStrokeOpacity(opacity);
    int numPages = reader.getNumberOfPages();
    int count = 0;

    while (count++ < numPages) {
        int pageCenter = (int) reader.getPageSizeWithRotation(count).getWidth() / 2;
        int pageMiddle = (int) reader.getPageSizeWithRotation(count).getHeight() / 2;

        Interpreter i = new Interpreter();
        i.set("PAGE_WIDTH", (int) reader.getPageSizeWithRotation(count).getWidth());
        i.set("PAGE_HEIGHT", (int) reader.getPageSizeWithRotation(count).getHeight());
        i.set("PAGE_CENTER", pageCenter);
        i.set("PAGE_MIDDLE", pageMiddle);
        Integer evalX = (Integer) i.eval(exprX);
        Integer evalY = (Integer) i.eval(exprY);

        if (evalX == null)
            evalX = Integer.valueOf(pageCenter);
        if (evalY == null) {
            evalY = Integer.valueOf(pageMiddle);
        }
        log.debug("evalX: {}", evalX);
        log.debug("evalY: {}", evalY);

        PdfContentByte cb = null;

        if (layer == LAYER_UNDER_CONTENT)
            cb = stamper.getUnderContent(count);
        else if (layer == LAYER_OVER_CONTENT)
            cb = stamper.getOverContent(count);
        else {
            throw new IllegalArgumentException();
        }

        cb.saveState();
        cb.setColorFill(color);
        cb.setGState(gs);
        cb.beginText();
        cb.setFontAndSize(bf, size);
        cb.showTextAligned(align, text, evalX.intValue(), evalY.intValue(), rotation);
        cb.endText();
        cb.restoreState();
    }

    stamper.close();
    reader.close();
}

From source file:com.orange.atk.atkUI.corecli.utils.PdfUtilities.java

License:Apache License

/**
 * Adds a text in the given pdf file.//from www  . ja va  2  s  .  c  om
 * @param pdfFileName
 * @param text
 * @param x
 * @param y
 * @param rotation
 * @param page
 * @throws Exception
 */
public void addText(String pdfFileName, String text, int x, int y, int rotation, int page) throws Exception {
    // see example on http://itextdocs.lowagie.com/examples/com/lowagie/examples/general/copystamp/AddWatermarkPageNumbers.java
    // 1. copy
    File tmpPDFFile = new File(tmpDir, "tmpPDF.pdf");
    copyFile(new File(pdfFileName), tmpPDFFile);
    // 2. add text
    // we create a reader for a certain document
    PdfReader reader = new PdfReader(tmpPDFFile.getAbsolutePath());
    // we create a stamper that will copy the document to a new file
    PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(pdfFileName));
    // adding content to each page
    PdfContentByte over;
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
    over = stamp.getOverContent(page);
    over.beginText();
    over.setFontAndSize(bf, 32);
    over.setTextMatrix(30, 30);
    over.setColorFill(java.awt.Color.RED);
    over.showTextAligned(Element.ALIGN_LEFT, text, x, y, rotation);
    over.endText();
    // closing PdfStamper will generate the new PDF file
    stamp.close();
}

From source file:com.square.adherent.noyau.service.implementations.RelevePrestationServiceImpl.java

License:Open Source License

@Override
public FichierDto getRelevePrestationByteArray(Long idRelevePrestation, Long idPersonne, boolean duplicata) {
    logger.debug(messageSourceUtil.get(MessageKeyUtil.LOGGER_DEBUG_CONVERSION_RELEVE_PRESTATION,
            new String[] { String.valueOf(idRelevePrestation) }));
    final CritereSelectionRelevePrestationDto critereSelectionRelevePrestationDto = new CritereSelectionRelevePrestationDto();
    critereSelectionRelevePrestationDto.setRelevePrestationId(idRelevePrestation);
    if (idPersonne != null) {
        critereSelectionRelevePrestationDto.setIdPersonne(idPersonne);
    }//www  .jav a 2s  . c  o  m
    final List<RelevePrestation> lstReleves = relevePrestationDao
            .getListeReleveParCriteres(critereSelectionRelevePrestationDto, null);
    if (lstReleves.size() == 1) {
        final RelevePrestation releve = lstReleves.get(0);
        final String error = messageSourceUtil.get(MessageKeyUtil.ERROR_RECUPERATION_FICHIER);
        FichierDto fichier;
        final String cheminFichier = serveurEmcRepReleve + File.separator + releve.getNomFichier();
        try {
            fichier = new FichierDto();
            fichier.setNomFichier(releve.getNomFichierCommercial());
            if (duplicata) {
                // On appose la mention "DUPLICATA" sur toutes les pages du relev.
                try {
                    final PdfReader reader = new PdfReader(cheminFichier);
                    final int nombrePages = reader.getNumberOfPages();
                    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE, BaseFont.WINANSI,
                            BaseFont.EMBEDDED);
                    final PdfStamper stamp = new PdfStamper(reader,
                            new FileOutputStream(FICHIER_DUPLICATA_TEMP));
                    final int taillePolice = 56;
                    final int positionX = ((int) PageSize.A4.getWidth()) / 2;
                    final int positionY = ((int) PageSize.A4.getHeight()) / 2;
                    final int rotation = 30;
                    for (int i = 1; i <= nombrePages; i++) {
                        final PdfContentByte over = stamp.getOverContent(i);
                        over.beginText();
                        over.setColorFill(Color.GRAY);
                        final PdfGState gs1 = new PdfGState();
                        gs1.setFillOpacity(NIVEAU_TRANSPARENCE);
                        over.setGState(gs1);
                        over.setFontAndSize(bf, taillePolice);
                        over.showTextAligned(PdfContentByte.ALIGN_CENTER, "DUPLICATA", positionX, positionY,
                                rotation);
                        over.endText();
                    }
                    stamp.close();
                    reader.close();
                    fichier.setContenu(IOUtils.toByteArray(new FileInputStream(FICHIER_DUPLICATA_TEMP)));
                    final File file = new File(FICHIER_DUPLICATA_TEMP);
                    file.delete();
                } catch (DocumentException e) {
                    throw new TechnicalException(
                            messageSourceUtil.get(MessageKeyUtil.ERROR_IMPOSSIBLE_AJOUTER_MENTION_DUPLICATA,
                                    new String[] { releve.getNomFichier() }));
                }
            } else {
                fichier.setContenu(IOUtils.toByteArray(new FileInputStream(cheminFichier)));
            }
            fichier.setTypeMime(Magic.getMagicMatch(fichier.getContenu()).getMimeType());
        } catch (FileNotFoundException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        } catch (IOException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        } catch (MagicParseException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        } catch (MagicMatchNotFoundException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        } catch (MagicException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        }
        return fichier;
    } else {
        throw new TechnicalException(
                messageSourceUtil.get(MessageKeyUtil.ERROR_ABSCENCE_RELEVE_PRESTATION_PERSONNE));
    }
}

From source file:es.gob.afirma.signers.pades.PdfPreProcessor.java

License:Open Source License

/** Sobreimpone una imagen JPEG en un documento PDF.
 * @param jpegImage Imagen JPEG//from  w  ww  . j av a  2s.c  o  m
 * @param width Ancho de la imagen
 * @param height Alto de la imagen
 * @param left Distancia de la imagen al borde izquiero de la p&aacute;gina del PDF
 * @param bottom Distancia de la imagen al borde inferior de la p&aacute;gina del PDF
 * @param pageNum N&uacute;mero de p&aacute;gina del PDF donde insertar la imagen
 *                (la numeraci&oacute;n comienza en 1)
 * @param url URL a la que enlazar&aacute; la imagen si queremos que esta sea un hiperv&iacute;nculo
 *            (puede ser <code>null</code>)
 * @param stp Estampador PDF de iText
 * @throws IOException En caso de errores de entrada / salida */
public static void addImage(final byte[] jpegImage, final int width, final int height, final int left,
        final int bottom, final int pageNum, final String url, final PdfStamper stp) throws IOException {
    final PdfContentByte content = stp.getOverContent(pageNum);
    try {
        final Image image = new Jpeg(jpegImage);
        if (url != null) {
            image.setAnnotation(new Annotation(0, 0, 0, 0, url));
        }
        content.addImage(image, // Image
                width, // Image width
                0, 0, height, // Image height
                left, // Lower left X position of the image
                bottom, // Lower left Y position of the image
                false // Inline
        );
    } catch (final DocumentException e) {
        throw new IOException("Error durante la insercion de la imagen en el PDF: " + e, e); //$NON-NLS-1$
    }
}

From source file:gov.anl.aps.cdb.portal.plugins.support.icmsLink.IcmsWatermarkUtility.java

License:Open Source License

/**
 * Adds a stamp of some metadata to ICMS documents.
 *
 * Function Credit: Thomas Fors//from   w ww  .j a va  2s  .  com
 *     
 * @return byte array ologgerf the stamped PDF file
 * @throws DocumentException - Error loading pdfstamper or creating font
 * @throws IOException - Error performing IO operation 
 * @throws Base64DecodingException - Error converting downloadContent string to byte[]
 */
private byte[] addWatermarkToPDFFile() throws Base64DecodingException, DocumentException, IOException {
    byte[] pdfBytes = Base64.decode(downloadContentBase64Encoded);

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yy hh:mm:ss a");
    LocalDateTime now = LocalDateTime.now();
    String downloadTime = dtf.format(now);

    UserInfo user = (UserInfo) SessionUtility.getUser();
    String username = null;
    if (user != null) {
        username = user.getUsername();
    } else {
        username = "unknown user";
    }
    String bottomMessage = "Downloaded via APS CDB by: " + username + " at " + downloadTime;

    controlledRev = updateOptionalValue(controlledRev);
    dnsCollectionId = updateOptionalValue(dnsCollectionId);
    dnsDocNumber = updateOptionalValue(dnsDocNumber);

    String watermarkContents = "Content ID: " + docName;
    watermarkContents += "      Rev: " + controlledRev;
    watermarkContents += "      Released: " + date;
    watermarkContents += "      DNS Collection ID: " + dnsCollectionId;
    watermarkContents += "      DNS Document ID: " + dnsDocNumber;

    PdfReader pdfReader = new PdfReader(pdfBytes);
    int n = pdfReader.getNumberOfPages();

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PdfStamper stamp = new PdfStamper(pdfReader, out);

    PdfContentByte over;
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

    for (int i = 0; i < n; i++) {
        over = stamp.getOverContent(i + 1);
        over.beginText();
        over.setTextMatrix(30, 30);
        over.setFontAndSize(bf, 10);
        over.setColorFill(new Color(0x80, 0x80, 0x80));
        over.showTextAligned(Element.ALIGN_LEFT, watermarkContents, 25, 25, 90);
        over.showTextAligned(Element.ALIGN_LEFT, bottomMessage, 50, 10, 0);
        if (status.equals(ICMS_UNDER_REV_STATUS)) {
            over.setColorFill(new Color(0xFF, 0x00, 0x00));
        }
        //over.showTextAligned(Element.ALIGN_LEFT, status, 25, 25 + bf.getWidthPoint(watermarkContents + " - ", 10), 90);

        over.endText();
    }
    stamp.close();

    return out.toByteArray();
}

From source file:hornet.framework.export.fdf.FDF.java

License:CeCILL license

/**
 * Fusion d'un champ FDF.//from   w  ww.  jav a 2s  .  co  m
 *
 * @param data
 *            the data
 * @param stamper
 *            the stamper
 * @param res
 *            the res
 * @param form
 *            the form
 * @param nomField
 *            the nom field
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws DocumentException
 *             the document exception
 */
private static void fusionChamp(final Object data, final PdfStamper stamper, final FDFRes res,
        final AcroFields form, final Object nomField) throws IOException, DocumentException {

    // utilisation du ":" comme sparateur d'accs.
    // le "." tant remplac par "_" par openoffice lors
    // de la conversion PDF.
    final String nomFieldStr = nomField.toString().replace(':', '.');

    Object value = null;
    try {
        value = PropertyUtils.getProperty(data, nomFieldStr);
    } catch (final Exception ex) {
        res.getUnmerged().add(nomFieldStr);
    }

    String valueStr;

    if (value == null) {
        valueStr = ""; // itext n'accepte pas les valeurs
        // nulles
        form.setField(nomField.toString(), valueStr);
    } else if (value instanceof FDFImage) {
        final FDFImage imValue = (FDFImage) value;
        final float[] positions = form.getFieldPositions(nomField.toString());
        final PdfContentByte content = stamper.getOverContent(1);
        final Image im = Image.getInstance(imValue.getData());
        if (imValue.isFit()) {
            content.addImage(im,
                    positions[FieldBoxPositions.URX.ordinal()] - positions[FieldBoxPositions.LLX.ordinal()], 0,
                    0, positions[FieldBoxPositions.URY.ordinal()] - positions[FieldBoxPositions.LLY.ordinal()],
                    positions[FieldBoxPositions.LLX.ordinal()], positions[FieldBoxPositions.LLY.ordinal()]);
        } else {
            content.addImage(im, im.getWidth(), 0, 0, im.getHeight(), positions[1], positions[2]);
        }
    } else if (value instanceof Date) {
        // format par dfaut date
        valueStr = DateFormat.getDateInstance(DateFormat.SHORT).format(value);
        form.setField(nomField.toString(), valueStr);
    } else if (value instanceof Boolean) {
        // format par spcial pour Checkbox
        if (Boolean.TRUE.equals(value)) {
            valueStr = "Yes";
        } else {
            valueStr = "No";
        }
        form.setField(nomField.toString(), valueStr);
    } else {
        // format par dfaut
        valueStr = value.toString();
        form.setField(nomField.toString(), valueStr);
    }
}

From source file:lucee.runtime.tag.PDF.java

License:Open Source License

private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
        throw new ApplicationException(
                "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
        throw new ApplicationException("destination file [" + destination + "] already exists");

    // image//from   ww  w.ja va  2  s .  c o  m
    Image img = null;
    if (image != null) {
        lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext, image, false, false, true,
                null);
        img = Image.getInstance(ri.getBufferedImage(), null, false);
    }
    // copy From
    else {
        byte[] barr;
        try {
            Resource res = Caster.toResource(pageContext, copyFrom, true);
            barr = IOUtil.toBytes(res);
        } catch (ExpressionException ee) {
            barr = Caster.toBinary(copyFrom);
        }
        img = Image.getInstance(PDFUtil.toImage(barr, 1).getBufferedImage(), null, false);

    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!StringUtil.isEmpty(position)) {
        int index = position.indexOf(',');
        if (index == -1)
            throw new ApplicationException("attribute [position] has an invalid value [" + position + "],"
                    + "value should follow one of the following pattern [40,50], [40,] or [,50]");
        String strX = position.substring(0, index).trim();
        String strY = position.substring(index + 1).trim();
        if (!StringUtil.isEmpty(strX))
            x = Caster.toIntValue(strX);
        if (!StringUtil.isEmpty(strY))
            y = Caster.toIntValue(strY);

    }

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {

        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        if (len > 0) {
            if (x == UNDEFINED || y == UNDEFINED) {
                PdfImportedPage first = stamp.getImportedPage(reader, 1);
                if (y == UNDEFINED)
                    y = (first.getHeight() - img.getHeight()) / 2;
                if (x == UNDEFINED)
                    x = (first.getWidth() - img.getWidth()) / 2;
            }
            img.setAbsolutePosition(x, y);
            //img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

        }

        // rotation
        if (rotation != 0) {
            img.setRotationDegrees(rotation);
        }

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            //print.out("op:"+opacity);
            gs1.setFillOpacity(opacity);
            //gs1.setStrokeOpacity(opacity);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        IOUtil.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                IOUtil.copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination,
                        true);// MUST overwrite
            if (!StringUtil.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:lucee.runtime.tag.PDF.java

License:Open Source License

private void doActionRemoveWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "removeWatermark", "source", source);

    if (destination != null && destination.exists() && !overwrite)
        throw new ApplicationException("destination file [" + destination + "] already exists");

    lucee.runtime.img.Image ri = new lucee.runtime.img.Image(1, 1, BufferedImage.TYPE_INT_RGB, Color.BLACK);
    Image img = Image.getInstance(ri.getBufferedImage(), null, false);
    img.setAbsolutePosition(1, 1);/*from   w  ww  . j a v  a  2 s  .  co  m*/

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();

    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {
        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            gs1.setFillOpacity(0);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        IOUtil.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                IOUtil.copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination,
                        true);// MUST overwrite
            if (!StringUtil.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:mpv5.utils.export.PDFFile.java

License:Open Source License

private void setImage(PdfStamper stamper, String key, java.awt.Image oimg) {
    try {//from   w  w w.  j  av  a  2s .  c om
        Log.Debug(this, "Write Image.." + key);
        float[] photograph = acroFields.getFieldPositions(key);
        Rectangle rect = new Rectangle(photograph[1], photograph[2], photograph[3], photograph[4]);
        Image img = Image.getInstance(oimg, null);

        img.setAbsolutePosition(photograph[1] + (rect.getWidth() - img.getScaledWidth()) / 2,
                photograph[2] + (rect.getHeight() - img.getScaledHeight()) / 2);
        PdfContentByte cb = stamper.getOverContent((int) photograph[0]);
        cb.addImage(img);
    } catch (Exception iOException) {
        Log.Debug(iOException);
    }
}