Example usage for com.lowagie.text.pdf PdfGState setFillOpacity

List of usage examples for com.lowagie.text.pdf PdfGState setFillOpacity

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfGState setFillOpacity.

Prototype

public void setFillOpacity(float n) 

Source Link

Document

Sets the current stroking alpha constant, specifying the constant shape or constant opacity value to be used for nonstroking operations in the transparent imaging model.

Usage

From source file:appli_etudiants.ExportPDF.java

public static void main(Etudiants etudiant)
        throws SQLException, FileNotFoundException, BadElementException, IOException {
    try {//from  w  ww  .j av a 2  s  .  c  o  m
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("c:/tesPDF.pdf"));
        document.open();
        PdfContentByte canvas = writer.getDirectContentUnder();
        Image image = Image.getInstance("c:/fond_cv.jpg");
        image.setAbsolutePosition(0, 80);
        canvas.saveState();
        PdfGState state = new PdfGState();
        state.setFillOpacity(0.6f);
        canvas.setGState(state);
        canvas.addImage(image);
        canvas.restoreState();

        LineSeparator lineSepa = new LineSeparator();
        lineSepa.setLineColor(new Color(21, 96, 189));
        Paragraph para1 = new Paragraph();
        Paragraph para2 = new Paragraph(etudiant.getAdresse_rue());
        Paragraph para3 = new Paragraph(etudiant.getAdresse_cp() + " " + etudiant.getAdresse_ville());
        Paragraph para4 = new Paragraph(etudiant.getCourriel(),
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189)));
        Paragraph para5 = new Paragraph(etudiant.getTel_personnel());
        Paragraph para6 = new Paragraph(etudiant.getTel_professionnel());
        Paragraph para7 = new Paragraph(etudiant.getSite_web());
        para1.add(new Chunk(etudiant.getPrenom(),
                FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD, new Color(21, 96, 189))));
        para1.add(
                new Chunk(" " + etudiant.getNom(), FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD)));

        Image image1 = Image.getInstance(DaoS4.getPhoto());
        image1.scalePercent(50);
        image1.setAlignment(Image.RIGHT | Image.TEXTWRAP);
        image1.scaleAbsolute(94, 94);
        document.add(image1);

        document.add(para1);
        document.add(para2);
        document.add(para3);
        document.add(para4);
        document.add(para5);
        document.add(para6);
        para7.setSpacingAfter(25f);
        document.add(para7);
        Paragraph para8 = new Paragraph(DaoS4.getLibelleTitre());
        para8.setSpacingBefore(25f);
        para8.setSpacingAfter(20f);
        document.add(para8);

        Paragraph para9 = new Paragraph(new Chunk("EXPERIENCE PROFESSIONELLE",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para9.setSpacingBefore(15f);
        para9.setSpacingAfter(15f);
        document.add(para9);
        document.add(lineSepa);
        Paragraph para10 = new Paragraph(DaoS4.getLibelleExpPro());
        para10.setSpacingAfter(15f);
        document.add(para10);

        Paragraph para11 = new Paragraph(new Chunk("FORMATION",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para11.setSpacingBefore(15f);
        para11.setSpacingAfter(15f);
        document.add(para11);
        document.add(lineSepa);
        Paragraph para12 = new Paragraph(DaoS4.getLibelleFormation());
        para12.setSpacingAfter(15f);
        document.add(para12);

        Paragraph para13 = new Paragraph(new Chunk("INFORMATIQUE",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para13.setSpacingBefore(15f);
        para13.setSpacingAfter(15f);
        document.add(para13);
        document.add(lineSepa);
        Paragraph para14 = new Paragraph(DaoS4.getLibelleInformatique());
        para14.setSpacingAfter(15f);
        document.add(para14);

        Paragraph para15 = new Paragraph(new Chunk("LANGUE",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para15.setSpacingBefore(15f);
        para15.setSpacingAfter(15f);
        document.add(para15);
        document.add(lineSepa);
        Paragraph para16 = new Paragraph(DaoS4.getLibelleLangue());
        para16.setSpacingAfter(15f);
        document.add(para16);

        Paragraph para17 = new Paragraph(new Chunk("CENTRES D'INTERET",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para17.setSpacingBefore(15f);
        para17.setSpacingAfter(15f);
        document.add(para17);
        document.add(lineSepa);
        Paragraph para18 = new Paragraph(DaoS4.getLibelleInteret());
        para18.setSpacingAfter(15f);
        document.add(para18);

        document.close();
    } catch (DocumentException ex) {
        Logger.getLogger(ExportPDF.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:br.gov.jfrj.itextpdf.Documento.java

License:Open Source License

public static byte[] stamp(byte[] abPdf, String sigla, boolean rascunho, boolean cancelado, boolean semEfeito,
        boolean internoProduzido, String qrCode, String mensagem, Integer paginaInicial, Integer paginaFinal,
        Integer cOmitirNumeracao, String instancia, String orgaoUsu) throws DocumentException, IOException {

    PdfReader pdfIn = new PdfReader(abPdf);
    Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
    // final SimpleDateFormat sdf = new SimpleDateFormat(
    // "EEE MMM dd HH:mm:ss zzz yyyy");
    // doc.add(new Meta("creationdate", sdf.format(new Date(0L))));
    final ByteArrayOutputStream boA4 = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(doc, boA4);
    doc.open();/*from  www .  j a v  a2s.  c  om*/
    PdfContentByte cb = writer.getDirectContent();

    // Resize every page to A4 size
    //
    // double thetaRotation = 0.0;
    for (int i = 1; i <= pdfIn.getNumberOfPages(); i++) {
        int rot = pdfIn.getPageRotation(i);
        float left = pdfIn.getPageSize(i).getLeft();
        float bottom = pdfIn.getPageSize(i).getBottom();
        float top = pdfIn.getPageSize(i).getTop();
        float right = pdfIn.getPageSize(i).getRight();

        PdfImportedPage page = writer.getImportedPage(pdfIn, i);
        float w = page.getWidth();
        float h = page.getHeight();

        // Logger.getRootLogger().error("----- dimensoes: " + rot + ", " + w
        // + ", " + h);

        doc.setPageSize((rot != 0 && rot != 180) ^ (w > h) ? PageSize.A4.rotate() : PageSize.A4);
        doc.newPage();

        cb.saveState();

        if (rot != 0 && rot != 180) {
            float swap = w;
            w = h;
            h = swap;
        }

        float pw = doc.getPageSize().getWidth();
        float ph = doc.getPageSize().getHeight();
        double scale = Math.min(pw / w, ph / h);

        // do my transformations :
        cb.transform(AffineTransform.getScaleInstance(scale, scale));

        if (!internoProduzido) {
            cb.transform(AffineTransform.getTranslateInstance(pw * SAFETY_MARGIN, ph * SAFETY_MARGIN));
            cb.transform(AffineTransform.getScaleInstance(1.0f - 2 * SAFETY_MARGIN, 1.0f - 2 * SAFETY_MARGIN));
        }

        if (rot != 0) {
            double theta = -rot * (Math.PI / 180);
            if (rot == 180) {
                cb.transform(AffineTransform.getRotateInstance(theta, w / 2, h / 2));
            } else {
                cb.transform(AffineTransform.getRotateInstance(theta, h / 2, w / 2));
            }
            if (rot == 90) {
                cb.transform(AffineTransform.getTranslateInstance((w - h) / 2, (w - h) / 2));
            } else if (rot == 270) {
                cb.transform(AffineTransform.getTranslateInstance((h - w) / 2, (h - w) / 2));
            }
        }

        // Logger.getRootLogger().error(
        // "----- dimensoes: " + rot + ", " + w + ", " + h);
        // Logger.getRootLogger().error("----- page: " + pw + ", " + ph);

        // cb.transform(AffineTransform.getTranslateInstance(
        // ((pw / scale) - w) / 2, ((ph / scale) - h) / 2));

        // put the page
        cb.addTemplate(page, 0, 0);

        // draw a red rectangle at the page borders
        //
        // cb.saveState();
        // cb.setColorStroke(Color.red);
        // cb.rectangle(pdfIn.getPageSize(i).getLeft(), pdfIn.getPageSize(i)
        // .getBottom(), pdfIn.getPageSize(i).getRight(), pdfIn
        // .getPageSize(i).getTop());
        // cb.stroke();
        // cb.restoreState();

        cb.restoreState();
    }
    doc.close();

    abPdf = boA4.toByteArray();

    final ByteArrayOutputStream bo2 = new ByteArrayOutputStream();

    final PdfReader reader = new PdfReader(abPdf);

    final int n = reader.getNumberOfPages();
    final PdfStamper stamp = new PdfStamper(reader, bo2);

    // adding content to each page
    int i = 0;
    PdfContentByte under;
    PdfContentByte over;
    final BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);

    // Image img = Image.getInstance("watermark.jpg");
    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

    byte maskr[] = { (byte) 0xff };
    Image mask = Image.getInstance(1, 1, 1, 1, maskr);
    mask.makeMask();
    mask.setInverted(true);

    while (i < n) {
        i++;
        // watermark under the existing page
        under = stamp.getUnderContent(i);
        over = stamp.getOverContent(i);

        final Barcode39 code39 = new Barcode39();
        // code39.setCode(doc.getCodigo());
        code39.setCode(sigla.replace("-", "").replace("/", "").replace(".", ""));
        code39.setStartStopText(false);
        final Image image39 = code39.createImageWithBarcode(over, null, null);
        Rectangle r = stamp.getReader().getPageSizeWithRotation(i);

        image39.setInitialRotation((float) Math.PI / 2.0f);
        image39.setAbsolutePosition(
                r.getWidth() - image39.getHeight() + (STAMP_BORDER_IN_CM - PAGE_BORDER_IN_CM) * CM_UNIT,
                BARCODE_HEIGHT_IN_CM * CM_UNIT);

        image39.setBackgroundColor(Color.green);
        image39.setBorderColor(Color.RED);
        image39.setBorderWidth(0.5f * CM_UNIT);

        image39.setImageMask(mask);

        over.setRGBColorFill(255, 255, 255);
        mask.setAbsolutePosition(r.getWidth() - image39.getHeight() - (PAGE_BORDER_IN_CM) * CM_UNIT,
                (BARCODE_HEIGHT_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
        mask.scaleAbsolute(image39.getHeight() + 2 * STAMP_BORDER_IN_CM * CM_UNIT,
                image39.getWidth() + 2 * STAMP_BORDER_IN_CM * CM_UNIT);
        over.addImage(mask);

        over.setRGBColorFill(0, 0, 0);
        over.addImage(image39);

        // over.addImage(mask, mask.getScaledWidth() * 8, 0, 0,
        // mask.getScaledHeight() * 8, 100, 450);

        if (qrCode != null) {
            java.awt.Image imgQRCode = createQRCodeImage(qrCode);
            Image imageQRCode = Image.getInstance(imgQRCode, Color.BLACK, true);
            imageQRCode.scaleAbsolute(QRCODE_SIZE_IN_CM * CM_UNIT, QRCODE_SIZE_IN_CM * CM_UNIT);
            imageQRCode.setAbsolutePosition(QRCODE_LEFT_MARGIN_IN_CM * CM_UNIT, PAGE_BORDER_IN_CM * CM_UNIT);

            over.setRGBColorFill(255, 255, 255);
            mask.setAbsolutePosition((QRCODE_LEFT_MARGIN_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT,
                    (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
            mask.scaleAbsolute((QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT,
                    (QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT);
            over.addImage(mask);

            over.setRGBColorFill(0, 0, 0);
            over.addImage(imageQRCode);
        }

        if (mensagem != null) {
            PdfPTable table = new PdfPTable(1);
            table.setTotalWidth(r.getWidth() - image39.getHeight() - (QRCODE_LEFT_MARGIN_IN_CM
                    + QRCODE_SIZE_IN_CM + 4 * STAMP_BORDER_IN_CM + PAGE_BORDER_IN_CM) * CM_UNIT);
            PdfPCell cell = new PdfPCell(new Paragraph(mensagem,
                    FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.BLACK)));
            cell.setBorderWidth(0);
            table.addCell(cell);

            over.setRGBColorFill(255, 255, 255);
            mask.setAbsolutePosition(
                    (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + STAMP_BORDER_IN_CM) * CM_UNIT,
                    (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
            mask.scaleAbsolute(2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalWidth(),
                    2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalHeight());
            over.addImage(mask);

            over.setRGBColorFill(0, 0, 0);
            table.writeSelectedRows(0, -1,
                    (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT,
                    table.getTotalHeight() + PAGE_BORDER_IN_CM * CM_UNIT, over);
        }

        if (cancelado) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "CANCELADO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        } else if (rascunho) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "MINUTA", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        } else if (semEfeito) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "SEM EFEITO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        }

        // if (!rascunho
        // && request.getRequestURL().indexOf("http://laguna/") == -1) {

        if (!rascunho && !cancelado && !semEfeito && ((!Contexto.resource("isVersionTest").equals("false"))
                || (!Contexto.resource("isBaseTest").equals("false")))) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "INVLIDO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        }

        // Imprime um circulo com o numero da pagina dentro.

        if (paginaInicial != null) {
            String sFl = String.valueOf(paginaInicial + i - 1);
            // Se for a ultima pagina e o numero nao casar, acrescenta "-" e
            // pagina final
            if (n == i) {
                if (paginaFinal != paginaInicial + n - 1) {
                    sFl = sFl + "-" + String.valueOf(paginaFinal);
                }
            }
            if (i > cOmitirNumeracao) {

                // Raio do circulo interno
                final float radius = 18f;

                // Distancia entre o circulo interno e o externo
                final float circleInterspace = Math.max(helv.getAscentPoint(instancia, TEXT_HEIGHT),
                        helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT))
                        - Math.min(helv.getDescentPoint(instancia, TEXT_HEIGHT),
                                helv.getDescentPoint(orgaoUsu, TEXT_HEIGHT))
                        + 2 * TEXT_TO_CIRCLE_INTERSPACE;

                // Centro do circulo
                float xCenter = r.getWidth() - 1.8f * (radius + circleInterspace);
                float yCenter = r.getHeight() - 1.8f * (radius + circleInterspace);

                over.saveState();
                final PdfGState gs = new PdfGState();
                gs.setFillOpacity(1f);
                over.setGState(gs);
                over.setColorFill(Color.BLACK);

                over.saveState();
                over.setColorStroke(Color.black);
                over.setLineWidth(1f);
                over.setColorFill(Color.WHITE);

                // Circulo externo
                over.circle(xCenter, yCenter, radius + circleInterspace);
                over.fill();
                over.circle(xCenter, yCenter, radius + circleInterspace);
                over.stroke();

                // Circulo interno
                over.circle(xCenter, yCenter, radius);
                over.stroke();
                over.restoreState();

                {
                    over.saveState();
                    over.beginText();
                    over.setFontAndSize(helv, TEXT_HEIGHT);

                    // Escreve o texto superior do carimbo
                    float fDescent = helv.getDescentPoint(instancia, TEXT_HEIGHT);
                    showTextOnArc(over, instancia, helv, TEXT_HEIGHT, xCenter, yCenter,
                            radius - fDescent + TEXT_TO_CIRCLE_INTERSPACE, true);

                    // Escreve o texto inferior
                    float fAscent = helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT);
                    showTextOnArc(over, orgaoUsu, helv, TEXT_HEIGHT, xCenter, yCenter,
                            radius + fAscent + TEXT_TO_CIRCLE_INTERSPACE, false);
                    over.endText();
                    over.restoreState();
                }

                over.beginText();
                int textHeight = 23;

                // Diminui o tamanho do font ate que o texto caiba dentro do
                // circulo interno
                while (helv.getWidthPoint(sFl, textHeight) > (2 * (radius - TEXT_TO_CIRCLE_INTERSPACE)))
                    textHeight--;
                float fAscent = helv.getAscentPoint(sFl, textHeight) + helv.getDescentPoint(sFl, textHeight);
                over.setFontAndSize(helv, textHeight);
                over.showTextAligned(Element.ALIGN_CENTER, sFl, xCenter, yCenter - 0.5f * fAscent, 0);
                over.endText();
                over.restoreState();
            }
        }

    }
    stamp.close();
    return bo2.toByteArray();
}

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);
    gs.setStrokeOpacity(opacity);// w w w . j  ava  2s .co m
    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 a v  a  2  s. c om
    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.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);
    }//from w w w.j a  v a  2  s  .  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: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 w w w  .  j  a v a  2s . c om
    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  w w .j  a  v a2  s. c o  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:org.geomajas.plugin.print.component.PdfContext.java

License:Open Source License

/**
 * Draws the specified image with the first rectangle's bounds, clipping with the second one.
 *
 * @param img image/* w ww  .  j  ava 2  s  . c  o  m*/
 * @param rect rectangle
 * @param clipRect clipping bounds
 * @param opacity opacity of the image (1 = opaque, 0= transparent)
 */
public void drawImage(Image img, Rectangle rect, Rectangle clipRect, float opacity) {
    try {
        template.saveState();
        // opacity
        PdfGState state = new PdfGState();
        state.setFillOpacity(opacity);
        state.setBlendMode(PdfGState.BM_NORMAL);
        template.setGState(state);
        // clipping code
        if (clipRect != null) {
            template.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(),
                    clipRect.getHeight());
            template.clip();
            template.newPath();
        }
        template.addImage(img, rect.getWidth(), 0, 0, rect.getHeight(), origX + rect.getLeft(),
                origY + rect.getBottom());
    } catch (DocumentException e) {
        log.warn("could not draw image", e);
    } finally {
        template.restoreState();
    }
}

From source file:org.geomajas.plugin.print.component.PdfContext.java

License:Open Source License

private void setFill(Color color) {
    // Color and transparency
    PdfGState state = new PdfGState();
    state.setFillOpacity(color.getAlpha() / 255f);
    state.setBlendMode(PdfGState.BM_NORMAL);
    template.setGState(state);//from  w w  w. ja v a 2  s .  co m
    template.setColorFill(color);
}

From source file:org.jaffa.modules.printing.services.FormPrintEngineIText.java

License:Open Source License

/**
 * This will fill in the page with data,
 * m_currentPageData contains the details of the current page being printed
 * @throws FormPrintException Thrown if there is any form processing problems
 *//*from   ww w.ja va 2  s  . c  o  m*/
protected void fillPageFields() throws FormPrintException {
    log.debug("fillPageFields: Page=" + getCurrentPage());

    try {
        PdfContentByte cb = m_writer.getDirectContent();
        PageDetailsExtended page = (PageDetailsExtended) getCurrentPageData();

        //                // Test code to throw a barcode on the page...
        //                Barcode39 code39 = new Barcode39();
        //                code39.setCode("CODE39-1234567890");
        //                code39.setStartStopText(false);
        //                code39.setSize(0);
        //                Image image39 = code39.createImageWithBarcode(cb, null, null);
        //                com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(2);
        //                table.setWidthPercentage(100);
        //                table.getDefaultCell().setBorder(com.lowagie.text.Rectangle.NO_BORDER);
        //                table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        //                table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        //                table.getDefaultCell().setFixedHeight(70);
        //                table.addCell("CODE 39");
        //                table.addCell(new Phrase(new Chunk(image39, 0, 0)));
        //                m_generatedDoc.add(table);
        //                //--------------------------------------------------

        // Loop through each field to be inserted
        for (Iterator i = page.fieldList.iterator(); i.hasNext();) {
            String fieldname = (String) i.next();

            // Get the properties for displaying this field
            FieldProperties props = (FieldProperties) page.fieldProperties.get(fieldname);

            // Get the data to display
            FormPrintEngine.DomValue data = new FormPrintEngine.DomValue(fieldname, props.sampleData);

            // Caluclate Clipping Region
            float x1 = Math.min(props.x1, props.x2);
            float x2 = Math.max(props.x1, props.x2);
            float y1 = Math.min(props.y1, props.y2);
            float y2 = Math.max(props.y1, props.y2);
            float w = Math.abs(props.x1 - props.x2) + 1;
            float h = Math.abs(props.y1 - props.y2) + 1;

            if (log.isDebugEnabled())
                log.debug("Print Field " + fieldname + "=" + data.getObject() + " @ [(" + x1 + "," + y1 + ")->("
                        + x2 + "," + y2 + ")]");

            // Default the font if not specified
            String font = BaseFont.HELVETICA;
            if (props.fontFace != null)
                font = props.fontFace;

            // Handle Barcodes diffently withing iText, don't just use fonts
            if (font.startsWith("Barcode")) {
                String bcClassName = "com.lowagie.text.pdf." + font;
                Object bcode = null;
                String dataStr = data.getValue();
                if (dataStr != null) {
                    log.debug("Barcode Data String = " + dataStr);
                    // Try and create the correct Barcode Object
                    try {
                        Class bcClass = Class.forName(bcClassName);
                        bcode = bcClass.newInstance();
                    } catch (Exception e) {
                        String err = "Can't Create Barcode Object for barcode type '" + font + "' on field "
                                + fieldname;
                        log.error(err, e);
                    }

                    // Only continue if the barcode object was created
                    if (bcode != null) {

                        // Generate and Print barcode, based on common interface
                        if (bcode instanceof Barcode) {
                            Barcode b = (Barcode) bcode;
                            // Set some default output a barcode
                            b.setCode(dataStr);
                            if (props.fontSize <= 0) {
                                // Hide text if font size is 0, and make the barcode height the size of the box
                                b.setBarHeight(h);
                                b.setFont(null);
                            } else {
                                b.setSize(props.fontSize); // size of text under barcode
                                b.setBarHeight(h - props.fontSize - 5); // Adjust Bar Height to allow for font size
                            }
                            b.setN(2); // Wide Bars

                            // Set custom parameters
                            setBarcodeParams(fieldname, bcode, props.style);

                            // Print out barcode
                            Image image = ((Barcode) bcode).createImageWithBarcode(cb, null, null);
                            printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);

                        } else

                        // Print PDF417 barcode, not based on common interface
                        if (bcode instanceof BarcodePDF417) {
                            BarcodePDF417 b = (BarcodePDF417) bcode;
                            // Set some default output a barcode
                            b.setText(dataStr);
                            b.setErrorLevel(5);
                            // Set custom parameters
                            setBarcodeParams(fieldname, bcode, props.style);
                            log.debug("PDF417 Settings\n" + "BitColumns=" + b.getBitColumns() + "\n"
                                    + "CodeColumns=" + b.getCodeColumns() + "\n" + "CodeRows=" + b.getCodeRows()
                                    + "\n" + "ErrorLevel=" + b.getErrorLevel() + "\n" + "YHeight="
                                    + b.getYHeight() + "\n" + "AspectRatio=" + b.getAspectRatio() + "\n"
                                    + "Options=" + b.getOptions() + "\n" + "LenCodewords="
                                    + b.getLenCodewords());

                            // Print out barcode
                            //image = b.getImage();
                            printImage(b.getImage(), cb, x1, y1, x2, y2, props.align, props.fitMethod,
                                    props.rotate);

                        } else {
                            // Error, unknown barcode
                            String err = "Error, No print handler for barcode object "
                                    + bcode.getClass().getName();
                            log.error(err);
                            //throw new EngineProcessingException(err);
                        }
                    }
                } else
                    log.debug("SKIPPED BARCODE : No data for " + fieldname);

                // Handle Images differently within iText, native support for JFreeChart
            } else if ("image".equalsIgnoreCase(font)) {
                try {
                    java.awt.Image image = data.getDomImage();
                    // Add an image to the page
                    if (image != null) {
                        if (fieldname.startsWith("watermark")) {
                            // Add an image-based watermark to the under content layer
                            PdfContentByte contentUnder = m_writer.getDirectContentUnder();
                            if (props.opacity != 1f) {
                                PdfGState gs = new PdfGState();
                                gs.setFillOpacity(props.opacity);
                                contentUnder.setGState(gs);
                            }
                            printImage(image, contentUnder, x1, y1, x2, y2, props.align, props.fitMethod,
                                    props.rotate);
                        } else {
                            // Add an image to main page layer
                            printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);
                        }
                    }
                } catch (IOException e) {
                    // Add Error on page.
                    Phrase text = new Phrase("Image Error", FontFactory
                            .getFont(FontFactory.HELVETICA_BOLDOBLIQUE, 8f, 0, ColorHelper.getColor("red")));
                    ColumnText ct = new ColumnText(cb);
                    ct.setSimpleColumn(text, x1, y1, x2, y2, 8f, Element.ALIGN_LEFT);
                }
            } else if (fieldname.startsWith("watermark")) {
                // Add a text-based watermark
                String text = data.getValue();
                PdfContentByte contentUnder = m_writer.getDirectContentUnder();
                if (props.opacity != 1f) {
                    PdfGState gs = new PdfGState();
                    gs.setFillOpacity(props.opacity);
                    contentUnder.setGState(gs);
                }
                // The text aligns (left, center, right) on the pivot point.
                // Default to align left.
                float pivotX = x1;
                float pivotY = y1;
                if (Element.ALIGN_CENTER == props.align) {
                    pivotX = (x1 / 2) + (x2 / 2);
                    pivotY = y1;
                } else if (Element.ALIGN_RIGHT == props.align) {
                    pivotX = x2;
                    pivotY = y1;
                }
                Phrase watermark = new Phrase(text, FontFactory.getFont(props.fontFace, props.fontSize,
                        decodeFontStyle(props.style), ColorHelper.getColor(defaultWatermarkColor)));
                ColumnText.showTextAligned(contentUnder, props.align, watermark, pivotX, pivotY, props.rotate);
            } else {
                // Handle printing of basic Text
                float lineHeight = props.fontSize;
                String str = data.getValue();
                if (str != null) {
                    // Add a bounded column to add text to.
                    Phrase text = new Phrase(str, FontFactory.getFont(props.fontFace, props.fontSize,
                            decodeFontStyle(props.style), ColorHelper.getColor(props.color)));
                    ColumnText ct = new ColumnText(cb);
                    if (props.fitMethod == FIT_METHOD_CLIP)
                        // set up column with height/width restrictions
                        ct.setSimpleColumn(text, x1, y1, x2, y2, lineHeight, props.align);
                    else
                        // set up column without (i.e. large) height/width restrictions
                        ct.setSimpleColumn(text, x1, y1, 1000, 0, lineHeight, props.align);
                    ct.go();
                }
            }

            // Draw outline boxes arround fields
            if (isTemplateMode()) {
                cb.setLineWidth(0.5f);
                cb.setLineDash(4f, 2f);
                cb.setColorStroke(new Color(0xA0, 0xA0, 0xA0));
                cb.moveTo(x1, y1);
                cb.lineTo(x1, y2);
                cb.lineTo(x2, y2);
                cb.lineTo(x2, y1);
                cb.lineTo(x1, y1);
                cb.stroke();
            }
        } // end for-loop
    } catch (DocumentException e) {
        String err = "Error printing data - " + e.getMessage();
        log.error(err, e);
        throw new EngineProcessingException(err);
        //        } catch (IOException e) {
        //            String err = "Error printing data - " + e.getMessage();
        //            log.error(err ,e);
        //            throw new EngineProcessingException(err);
    }

}