Example usage for com.lowagie.text.pdf PdfContentByte setColorFill

List of usage examples for com.lowagie.text.pdf PdfContentByte setColorFill

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfContentByte setColorFill.

Prototype

public void setColorFill(Color color) 

Source Link

Document

Sets the fill color.

Usage

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 w  w  w  .j  a  v a  2  s.  com*/
    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:classroom.filmfestival_c.Movies19.java

protected static void drawMovie(PdfWriter writer, FestivalScreening screening, List<String> places,
        float minute, float left, float top, float row_height) throws DocumentException {
    FilmTitle movie = screening.getFilmTitle();
    // defining the rectangle
    int place = places.indexOf(screening.getId().getPlace());
    float llx, urx, lly, ury;
    llx = left + minute * getMinutesAfter930(screening);
    urx = llx + minute * (screening.getShortfilm() + movie.getDuration());
    ury = top - place * row_height;/*from   w  w w . j  a  v  a  2  s.c  o  m*/
    lly = top - ((place + 1) * row_height);

    // FOREGROUND
    PdfContentByte foreground = writer.getDirectContent();

    // rectangle
    foreground.setColorStroke(BLACK);
    foreground.setLineWidth(1);
    foreground.moveTo(urx, lly);
    foreground.lineTo(llx, lly);
    foreground.lineTo(llx, ury);
    foreground.lineTo(urx, ury);
    foreground.closePathStroke();
    // title
    ColumnText ct = new ColumnText(foreground);
    ct.setSimpleColumn(new Phrase(movie.getTitle(), SMALLEST), llx, lly, urx, ury, 14, Element.ALIGN_CENTER);
    ct.go();

    // BACKGROUND
    PdfContentByte background = writer.getDirectContentUnder();

    // draw background
    background.setColorFill(getColor(movie));
    background.moveTo(urx, lly);
    background.lineTo(llx, lly);
    background.lineTo(llx, ury);
    background.lineTo(urx, ury);
    background.fill();

    // draw a white P for press screenings
    if (screening.getPress() == 1) {
        background.saveState();
        background.beginText();
        background.setFontAndSize(FONT, 24);
        background.setColorFill(WHITE);
        background.showTextAligned(Element.ALIGN_CENTER, "P", (llx + urx) / 2f, (lly + ury) / 2f - 12, 0);
        background.endText();
        background.restoreState();
    }

    // draw shortfilm
    background.setColorStroke(WHITE);
    if (screening.getShortfilm() > 0) {
        background.moveTo(llx + (minute * screening.getShortfilm()), lly);
        background.lineTo(llx + (minute * screening.getShortfilm()), ury);
        background.stroke();
    }
}

From source file:classroom.filmfestival_c.Movies22.java

public static void main(String[] args) {
    // step 1//from w w  w .ja va 2 s .  c  o m
    Document document = new Document(new Rectangle(WIDTH, HEIGHT));
    try {
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FORM));
        writer.setViewerPreferences(PdfWriter.PageLayoutSinglePage);
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();

        // top part of the card
        cb.setColorFill(RED);
        cb.rectangle(0, mm2pt(57f), WIDTH, HEIGHT - mm2pt(57f));
        cb.fill();
        cb.setColorFill(BLACK);
        cb.rectangle(0, mm2pt(61), WIDTH, mm2pt(21f));
        cb.fill();
        cb.setColorFill(WHITE);

        Image kubrick = Image.getInstance(KUBRICK);
        kubrick.scaleToFit(WIDTH, mm2pt(21));
        kubrick.setAbsolutePosition(0, mm2pt(61));
        cb.addImage(kubrick);

        Image logo = Image.getInstance(LOGO);
        logo.scaleToFit(mm2pt(14), mm2pt(14));
        logo.setAbsolutePosition(mm2pt(37), mm2pt(65));
        cb.addImage(logo);

        cb.beginText();
        cb.setFontAndSize(FONT, 7);
        cb.showTextAligned(Element.ALIGN_CENTER, "Flanders International Film Festival-Ghent", WIDTH / 2,
                mm2pt(58.5f), 0);
        cb.endText();

        // bottom part of the card

        TextField filmfestival = new TextField(writer, new Rectangle(0, 0, WIDTH, mm2pt(9)), "filmfestival");
        filmfestival.setBackgroundColor(GRAY);
        filmfestival.setTextColor(WHITE);
        filmfestival.setText("www.filmfestival.be");
        filmfestival.setFontSize(14);
        filmfestival.setOptions(TextField.READ_ONLY);
        filmfestival.setAlignment(Element.ALIGN_CENTER);
        writer.addAnnotation(filmfestival.getTextField());

        cb.beginText();
        cb.moveText(mm2pt(1.5f), mm2pt(12));
        cb.setFontAndSize(FONT, 21);
        cb.setColorFill(RED);
        cb.showText("10");
        cb.setColorFill(BLUE);
        cb.showText("/");
        cb.setColorFill(RED);
        cb.showText("21");
        cb.setColorFill(BLUE);
        cb.showText("OCT");
        cb.setColorFill(GREEN);
        cb.showText("2006");
        cb.endText();
        cb.setColorStroke(BLUE);
        cb.moveTo(mm2pt(24.5f), mm2pt(29));
        cb.lineTo(mm2pt(24.5f), mm2pt(36));
        cb.moveTo(mm2pt(24.5f), mm2pt(48));
        cb.lineTo(mm2pt(24.5f), mm2pt(54));
        cb.stroke();

        // central part of the card
        PushbuttonField photo = new PushbuttonField(writer,
                new Rectangle(mm2pt(3), mm2pt(29), mm2pt(24), mm2pt(54)), "photo");
        PdfTemplate t1 = cb.createTemplate(mm2pt(21), mm2pt(25));
        t1.setColorFill(GRAY);
        t1.rectangle(0, 0, mm2pt(21), mm2pt(25));
        t1.fill();
        photo.setTemplate(t1);
        photo.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
        writer.addAnnotation(photo.getField());

        TextField type = new TextField(writer,
                new Rectangle(mm2pt(26), mm2pt(46), WIDTH - mm2pt(1.5f), mm2pt(54)), "type");
        type.setTextColor(GRAY);
        type.setText("TYPE");
        type.setFontSize(0);
        writer.addAnnotation(type.getTextField());

        TextField number = new TextField(writer,
                new Rectangle(mm2pt(26), mm2pt(44), WIDTH - mm2pt(1.5f), mm2pt(48)), "number");
        number.setText("N\u00b0 0000000");
        number.setFontSize(8);
        writer.addAnnotation(number.getTextField());

        TextField name = new TextField(writer,
                new Rectangle(mm2pt(26), mm2pt(28), WIDTH - mm2pt(1.5f), mm2pt(40)), "name");
        name.setText("Name");
        name.setFontSize(8);
        name.setOptions(TextField.MULTILINE);
        writer.addAnnotation(name.getTextField());

        PushbuttonField barcode = new PushbuttonField(writer,
                new Rectangle(mm2pt(3), mm2pt(23), WIDTH - mm2pt(3), mm2pt(28)), "barcode");
        PdfTemplate t2 = cb.createTemplate(WIDTH - mm2pt(6), mm2pt(5));
        t2.setColorFill(GRAY);
        t2.rectangle(0, 0, WIDTH - mm2pt(6), mm2pt(5));
        t2.fill();
        barcode.setTemplate(t2);
        barcode.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
        writer.addAnnotation(barcode.getField());

    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // step 4
    document.close();
}

From source file:com.estate.pdf.Page.java

protected void drawFilledRect(Rectangle rct, Color color) {
    PdfContentByte cb = writer.getDirectContentUnder();
    // Do the lower left box
    cb.setLineWidth(0);//from   w  w w . j a v  a2s  .c o  m
    cb.setRGBColorStroke(255, 255, 255);
    cb.rectangle(rct.getLeft(), rct.getBottom(), rct.getWidth(), rct.getHeight());
    cb.setColorFill(color);
    cb.closePathFillStroke();
}

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 www .  j  a  va  2s  .  com
    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   ww w  . j  a v  a 2 s .  com
 * @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.qcadoo.report.api.pdf.PdfPageNumbering.java

License:Open Source License

private void buildFooter(final PdfWriter writer, final Document document) {
    PdfContentByte cb = writer.getDirectContent();

    cb.saveState();/*from ww w .  ja v a 2  s .co m*/

    String text = footer.getPage() + " " + writer.getPageNumber() + " " + footer.getIn() + " ";

    float textBase = document.bottom() - 25;
    float textSize = FontUtils.getDejavu().getWidthPoint(text, 7);

    cb.setColorFill(ColorUtils.getLightColor());
    cb.setColorStroke(ColorUtils.getLightColor());
    cb.setLineWidth(1);
    cb.setLineDash(2, 2, 1);
    cb.moveTo(document.left(), document.bottom() - 10);
    cb.lineTo(document.right(), document.bottom() - 10);
    cb.stroke();
    cb.beginText();
    cb.setFontAndSize(FontUtils.getDejavu(), 7);

    float adjust = FontUtils.getDejavu().getWidthPoint("0", 7);

    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);

    textSize = FontUtils.getDejavu().getWidthPoint(footer.getGeneratedBy(), 7);

    cb.setTextMatrix(document.right() - textSize, textBase - 10);
    cb.showText(footer.getGeneratedBy());

    textSize = FontUtils.getDejavu().getWidthPoint(generationDate, 7);

    cb.setTextMatrix(document.right() - textSize, textBase - 20);
    cb.showText(generationDate);
    cb.endText();

    try {
        textSize = FontUtils.getDejavu().getWidthPoint(footer.getAdditionalText(), 7);

        ColumnText ct = new ColumnText(cb);

        ct.setSimpleColumn(new Phrase(footer.getAdditionalText(), FontUtils.getDejavuRegular7Light()),
                document.left() + 240, textBase + 10, document.left() + 390, textBase - 25, 10,
                Element.ALIGN_LEFT);
        ct.go();
    } catch (DocumentException e) {
        LOG.warn("Problem with additional text generation in report footer.");
    }

    try {
        ColumnText ct = new ColumnText(cb);

        ct.setSimpleColumn(document.left(), textBase + 10, document.left() + 230, textBase - 25, 10,
                Element.ALIGN_LEFT);
        ct.addText(new Phrase(footer.getCompanyName() + "\n", FontUtils.getDejavuRegular7Light()));

        if (!"".equals(footer.getAddress())) {
            ct.addText(new Phrase(footer.getAddress() + "\n", FontUtils.getDejavuRegular7Light()));
        }
        if (!"".equals(footer.getPhoneEmail())) {
            ct.addText(new Phrase(footer.getPhoneEmail(), FontUtils.getDejavuRegular7Light()));
        }

        ct.go();
    } catch (DocumentException e) {
        LOG.warn("Problem with company text generation in report footer.");
    }

    cb.addTemplate(total, document.right() - adjust, textBase);
    cb.restoreState();

}

From source file:com.qcadoo.report.api.pdf.PdfPageNumbering.java

License:Open Source License

private void buildHeader(final PdfWriter writer, final Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();/* w  w  w.  j a va2s  . c o  m*/
    String text = footer.getPage() + " " + writer.getPageNumber() + " " + footer.getIn() + " ";

    float textBase = document.top() + 22;
    float textSize = FontUtils.getDejavu().getWidthPoint(text, 7);

    cb.setColorFill(ColorUtils.getLightColor());
    cb.setColorStroke(ColorUtils.getLightColor());
    cb.beginText();
    cb.setFontAndSize(FontUtils.getDejavu(), 7);

    float adjust = FontUtils.getDejavu().getWidthPoint("0", 7);

    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(total, document.right() - adjust, textBase);
    cb.setLineWidth(1);
    cb.setLineDash(2, 2, 1);
    cb.moveTo(document.left(), document.top() + 12);
    cb.lineTo(document.right(), document.top() + 12);
    cb.stroke();
    cb.restoreState();

}

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   www  . j av a  2  s .  com
    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:de.cuseb.bilderbuch.pdf.PdfController.java

License:Open Source License

@RequestMapping(value = "/pdf", method = RequestMethod.GET)
public void generatePdf(HttpSession session, HttpServletResponse httpServletResponse) {

    try {//  w  ww.ja va  2s. c  o m
        PdfRequest pdfRequest = (PdfRequest) session.getAttribute("pdfRequest");
        httpServletResponse.setContentType("application/pdf");

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, httpServletResponse.getOutputStream());
        writer.setDefaultColorspace(PdfName.COLORSPACE, PdfName.DEFAULTRGB);

        //document.addAuthor(pdfRequest.getAuthor());
        //document.addTitle(pdfRequest.getTitle());
        document.setPageSize(
                new Rectangle(Utilities.millimetersToPoints(156), Utilities.millimetersToPoints(148)));
        document.open();

        FontFactory.defaultEmbedding = true;
        FontFactory.register("IndieRock.ttf", "IndieRock");
        Font font = FontFactory.getFont("IndieRock");
        BaseFont baseFont = font.getBaseFont();
        PdfContentByte cb = writer.getDirectContent();

        Iterator<PdfPage> pages = pdfRequest.getPages().iterator();
        while (pages.hasNext()) {

            PdfPage page = pages.next();
            if (page.getImage() != null) {

                Image image = Image.getInstance(new URL(page.getImage().getUrl()));
                image.setDpi(300, 300);
                image.setAbsolutePosition(0f, 0f);
                image.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight());
                document.add(image);

                cb.saveState();
                cb.beginText();
                cb.setColorFill(Color.WHITE);
                cb.moveText(10f, 10f);
                cb.setFontAndSize(baseFont, 18);
                cb.showText(page.getSentence());
                cb.endText();
                cb.restoreState();

                if (pages.hasNext()) {
                    document.newPage();
                }
            }
        }
        document.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}