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

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

Introduction

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

Prototype

public void showTextAligned(int alignment, String text, float x, float y, float rotation) 

Source Link

Document

Shows text right, left or center aligned with rotation.

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  www.  ja va2  s.  c o m*/
    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:br.gov.jfrj.itextpdf.Documento.java

License:Open Source License

private static void showTextOnArc(PdfContentByte cb, String text, BaseFont font, float textHeight,
        float xCenter, float yCenter, float radius, boolean top) {
    float fTotal = 0;
    float aPos[] = new float[text.length()];
    for (int i = 0; i < text.length(); i++) {
        float f = font.getWidthPoint(text.substring(i, i + 1), textHeight);
        aPos[i] = f / 2 + fTotal;/*  ww  w  . j  ava2s .c  o  m*/
        fTotal += f;
    }
    float fAscent = font.getAscentPoint(text, textHeight);

    for (int i = 0; i < text.length(); i++) {
        float theta;
        if (top)
            theta = (float) ((aPos[i] - fTotal / 2) / radius);
        else
            theta = (float) (-1 * (aPos[i] - fTotal / 2) / (radius - fAscent) + Math.PI);
        cb.showTextAligned(Element.ALIGN_CENTER, text.substring(i, i + 1),
                xCenter + radius * (float) Math.sin(theta), yCenter + radius * (float) Math.cos(theta),
                (float) ((-theta + (top ? 0 : Math.PI)) * 180 / Math.PI));
    }
    return;
}

From source file:br.org.archimedes.io.pdf.elements.TextExporter.java

License:Open Source License

public void exportElement(Text text, Object outputObject) throws IOException {

    PDFWriterHelper helper = (PDFWriterHelper) outputObject;
    PdfContentByte cb = helper.getPdfContentByte();

    Point lowerLeft = text.getLowerLeft();
    Point docPoint = helper.modelToDocument(lowerLeft);

    BaseFont font = null;//from ww w  .j  a v a  2s.  com
    try {
        font = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    } catch (DocumentException e) {
        // Problems creating the font. This means the current
        // platform does not support this encoding or font.
        System.err.println(Messages.TextExporter_FontCreatingError);
        e.printStackTrace();
    }
    cb.setFontAndSize(font, (float) text.getSize());
    cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
    cb.beginText();
    cb.moveText((float) docPoint.getX(), (float) docPoint.getY());
    double angle = 0;
    try {
        angle = Geometrics.calculateAngle(new Point(0, 0), text.getDirection().getPoint());
    } catch (NullArgumentException e) {
        // Shouldn't happen since the text MUST have a direction to exists
        // and the point 0,0 is valid
        e.printStackTrace();
    }
    float degreeAngle = (float) (angle * 180 / Math.PI);
    cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text.getText(), (float) docPoint.getX(),
            (float) docPoint.getY(), degreeAngle);
    cb.endText();
}

From source file:classroom.filmfestival_c.Movies19.java

protected static void drawGrid(PdfWriter writer, List<String> places, String day, float left,
        float column_width, float top, float row_height) {

    // CANVAS//  ww  w. j  a va2s  .c o  m
    PdfContentByte directcontent = writer.getDirectContent();
    Rectangle art = writer.getBoxSize("art");

    // LINES

    directcontent.setLineWidth(1);
    float bottom = art.getTop();

    // rows
    int rows = places.size();
    for (int i = 0; i <= rows; i++) {
        directcontent.moveTo(art.getLeft(), art.getTop() - (i * row_height));
        directcontent.lineTo(art.getRight(), art.getTop() - (i * row_height));
        bottom = art.getTop() - (i * row_height);
    }

    // Rectangle
    directcontent.moveTo(art.getLeft(), art.getTop());
    directcontent.lineTo(art.getLeft(), bottom);
    directcontent.moveTo(left, art.getTop());
    directcontent.lineTo(left, bottom);
    directcontent.moveTo(art.getLeft() + (COLUMNS * column_width), art.getTop());
    directcontent.lineTo(art.getLeft() + (COLUMNS * column_width), bottom);
    directcontent.stroke();

    // columns
    directcontent.saveState();
    directcontent.setLineWidth(0.3f);
    directcontent.setColorStroke(SILVER);
    directcontent.setLineDash(3, 1);
    for (int i = 2; i < COLUMNS; i++) {
        directcontent.moveTo(art.getLeft() + (i * column_width), art.getTop());
        directcontent.lineTo(art.getLeft() + (i * column_width), bottom);
    }
    directcontent.stroke();
    directcontent.restoreState();

    // TEXT

    // date
    directcontent.beginText();
    directcontent.setFontAndSize(FONT, 12);
    directcontent.showTextAligned(Element.ALIGN_RIGHT, day, art.getLeft() - 5, art.getTop(), 90);
    directcontent.endText();

    // time
    for (int i = 1; i < COLUMNS; i++) {
        directcontent.beginText();
        directcontent.setFontAndSize(FONT, 8);
        directcontent.showTextAligned(Element.ALIGN_LEFT, TIME[i - 1], art.getLeft() + (i * column_width) + 5,
                top + 5, 90);
        directcontent.endText();
    }

    // places
    for (int i = 0; i < rows; i++) {
        directcontent.beginText();
        directcontent.setFontAndSize(FONT, 12);
        directcontent.showTextAligned(Element.ALIGN_CENTER, places.get(i), art.getLeft() + 16,
                art.getTop() - ((i + 0.5f) * row_height), 90);
        directcontent.endText();
    }
}

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;/*w w w. j  a  v  a  2s  . co 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 ww .  ja  va 2 s .c  om
    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:classroom.intro.HelloWorld07.java

public static void main(String[] args) {
    // step 1/*  w w w  .  ja  v  a2s.  co m*/
    Document document = new Document();
    try {
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.beginText();
        cb.setFontAndSize(bf, 12);
        cb.showTextAligned(Element.ALIGN_LEFT, "Hello World", 36, 788, 0);
        cb.endText();
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    // step 5
    document.close();
}

From source file:classroom.newspaper_a.Newspaper03.java

public static void putText(PdfContentByte canvas, String p, BaseFont bf, float llx, float lly, float urx,
        float ury) throws DocumentException {
    float x = (llx + urx) / 2f + 5;
    float y = (lly + ury) / 2f - 5;
    float w = urx - llx;
    float h = ury - lly;
    float angle = (float) (180 * Math.atan(h / w) / Math.PI);
    canvas.beginText();// www  .  ja  va2s. com
    canvas.setFontAndSize(bf, 10);
    canvas.showTextAligned(Element.ALIGN_CENTER, p, x, y, angle);
    canvas.endText();
}

From source file:com.actelion.research.spiritapp.print.CagePrinterPDF.java

License:Open Source License

public static void printCages(List<Container> cages, boolean printGroupsTreatments, boolean printTreatmentDesc,
        boolean whiteBackground) throws Exception {
    final int margin = 15;
    File f = File.createTempFile("cages__", ".pdf");
    Document doc = new Document(PageSize.A4.rotate());
    Image maleImg, femaleImg, nosexImg;
    try {/*from   w w w  .  j  av a  2s  . c om*/
        maleImg = Image.getInstance(CagePrinterPDF.class.getResource("male.png"));
        femaleImg = Image.getInstance(CagePrinterPDF.class.getResource("female.png"));
        nosexImg = Image.getInstance(CagePrinterPDF.class.getResource("nosex.png"));
    } catch (Exception e) {
        throw new Exception("Could not find images in the classpath: " + e);
    }

    FileOutputStream os = new FileOutputStream(f);
    PdfWriter writer = PdfWriter.getInstance(doc, os);
    doc.open();

    PdfContentByte canvas = writer.getDirectContentUnder();

    float tileW = (doc.getPageSize().getWidth()) / 4;
    float tileH = (doc.getPageSize().getHeight()) / 2;
    for (int i = 0; i < cages.size(); i++) {
        Container cage = cages.get(i);

        Study study = cage.getStudy();
        Set<Group> groups = cage.getGroups();
        Group group = cage.getGroup();
        Set<Biosample> animals = new TreeSet<>(Biosample.COMPARATOR_NAME);
        animals.addAll(cage.getBiosamples());

        //Find the treatments applied to this group
        Set<NamedTreatment> allTreatments = new LinkedHashSet<>();
        for (Group gr : groups) {
            allTreatments.addAll(gr.getAllTreatments(-1));
        }

        //Draw
        if (i % 8 == 0) {
            if (i > 0)
                doc.newPage();
            drawCageSeparation(doc, canvas);
        }

        int col = (i % 8) % 4;
        int row = (i % 8) / 4;

        float x = margin + tileW * col;
        float x2 = x + tileW - margin;
        float baseY = tileH * row;
        float y;

        //Display Sex
        canvas.moveTo(tileW * col - 50, doc.getPageSize().getHeight() - (tileH * row + 50));
        Image img = null;
        String sex = getMetadata(animals, "Sex");
        if (study.isBlindAll()) {
            img = nosexImg;
        } else if (sex.equals("M")) {
            img = maleImg;
        } else if (sex.equals("F")) {
            img = femaleImg;
        } else if (sex.length() > 0) {
            img = nosexImg;
        }
        if (img != null) {
            img.scaleToFit(20, 20);
            img.setAbsolutePosition(tileW * (col + 1) - 33,
                    doc.getPageSize().getHeight() - (tileH * row + 12 + margin));
            doc.add(img);
        }
        if (group != null && group.getColor() != null && (study != null && !study.isBlind())
                && !whiteBackground) {
            Color c = group.getColor();
            canvas.saveState();
            canvas.setRGBColorFill(c.getRed() / 3 + 170, c.getGreen() / 3 + 170, c.getBlue() / 3 + 170);
            canvas.rectangle(x - margin + 1, doc.getPageSize().getHeight() - baseY - tileH + 1, tileW - 2,
                    tileH - 2);
            canvas.fill();
            canvas.restoreState();
        }
        Color treatmentColor = Color.BLACK;
        if (allTreatments.size() > 0 && !study.isBlind() && printGroupsTreatments) {
            int offset = 0;
            for (NamedTreatment t : allTreatments) {
                if (t.getColor() != null) {
                    if (allTreatments.size() == 1)
                        treatmentColor = new Color(t.getColor().getRed() / 2, t.getColor().getGreen() / 2,
                                t.getColor().getBlue() / 2);
                    canvas.saveState();
                    canvas.setColorStroke(Color.BLACK);
                    canvas.setRGBColorFill(t.getColor().getRed(), t.getColor().getGreen(),
                            t.getColor().getBlue());
                    y = baseY + 42 + 15 + 86 + 13 + 22 + 14 + 23 + 28;
                    canvas.rectangle(x + 20 + offset * 5, doc.getPageSize().getHeight() - y - (offset % 2) * 4,
                            22, 22);
                    canvas.fillStroke();
                    canvas.restoreState();
                    offset++;
                }
            }
        }

        canvas.beginText();
        canvas.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA_BOLD, "Cp1252", false), 16f);
        canvas.showTextAligned(Element.ALIGN_LEFT, cage.getContainerId(), x,
                doc.getPageSize().getHeight() - (baseY + 23), 0);

        canvas.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, "Cp1252", false), 11f);
        y = 42 + baseY;
        canvas.showTextAligned(Element.ALIGN_LEFT, "Type: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 15;
        canvas.showTextAligned(Element.ALIGN_LEFT, "Animals_ID: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 86;
        canvas.showTextAligned(Element.ALIGN_LEFT, "Delivery date: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 13;
        canvas.showTextAligned(Element.ALIGN_LEFT, "PO Number: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 22;
        canvas.showTextAligned(Element.ALIGN_LEFT, "Study: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 14;
        if (study != null && !study.isBlind() && printGroupsTreatments)
            canvas.showTextAligned(Element.ALIGN_LEFT, "Group: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 23;
        if (study != null && !study.isBlind() && printGroupsTreatments)
            canvas.showTextAligned(Element.ALIGN_LEFT, "Treatment: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 50;
        canvas.showTextAligned(Element.ALIGN_LEFT, "License: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 13;
        canvas.showTextAligned(Element.ALIGN_LEFT, "Experimenter: ", x, doc.getPageSize().getHeight() - y, 0);
        canvas.endText();

        y = 42 + baseY;
        print(canvas, study.isBlindAll() ? "Blinded" : getMetadata(animals, "Type"), x + 65,
                doc.getPageSize().getHeight() - y, x2, 11, 11, FontFactory.HELVETICA, Color.BLACK, 11f);
        y += 15;

        if (animals.size() <= 6) {
            int n = 0;
            for (Biosample animal : animals) {
                print(canvas, animal.getSampleId(), x + 75, doc.getPageSize().getHeight() - y - 12 * n, x2 - 50,
                        12, 12, FontFactory.HELVETICA, Color.BLACK, 11f);
                if (animal.getSampleName() != null && animal.getSampleName().length() > 0) {
                    print(canvas, "[ " + animal.getSampleName() + " ]", x2 - 60,
                            doc.getPageSize().getHeight() - y - 12 * n, x2, 12, 12, FontFactory.HELVETICA_BOLD,
                            Color.BLACK, 11f);
                }
                n++;
            }
        } else {
            int nPerRow = animals.size() / 2;
            int n = 0;
            for (Biosample animal : animals) {
                int nx = n / nPerRow;
                int ny = n % nPerRow;
                print(canvas, animal.getSampleId(), x + nx * (x2 - x) / 2,
                        doc.getPageSize().getHeight() - y - 12 * ny - 12, x + (1 + nx) * (x2 - x) / 2, 12, 12,
                        FontFactory.HELVETICA, Color.BLACK, 10f);
                if (animal.getSampleName() != null && animal.getSampleName().length() > 0) {
                    print(canvas, "[ " + animal.getSampleName() + " ]", x + (1 + nx) * (x2 - x) / 2 - 35,
                            doc.getPageSize().getHeight() - y - 12 * ny - 12, x + (1 + nx) * (x2 - x) / 2, 12,
                            12, FontFactory.HELVETICA_BOLD, Color.BLACK, 10f);
                }
                n++;
            }
        }

        y += 86;
        print(canvas, getMetadata(animals, "Delivery Date"), x + 75, doc.getPageSize().getHeight() - y, x2, 0,
                10, FontFactory.HELVETICA, Color.BLACK, 10f);
        y += 13;
        print(canvas, getMetadata(animals, "PO Number"), x + 75, doc.getPageSize().getHeight() - y, x2, 0, 10,
                FontFactory.HELVETICA, Color.BLACK, 10f);
        y += 22;
        print(canvas, study.getStudyIdAndInternalId(), x + 40, doc.getPageSize().getHeight() - y, x2, 0, 11,
                BaseFont.HELVETICA_BOLD, Color.BLACK, 11f);
        y += 14;
        if (!study.isBlind() && printGroupsTreatments)
            print(canvas, getGroups(animals), x + 40, doc.getPageSize().getHeight() - y, x2, 22, 11,
                    BaseFont.HELVETICA_BOLD, Color.BLACK, 11f);
        y += 23;
        if (!study.isBlind() && printGroupsTreatments)
            print(canvas, getTreatments(animals, printTreatmentDesc), x + 62, doc.getPageSize().getHeight() - y,
                    x2, 50, printTreatmentDesc ? 9 : 12, FontFactory.HELVETICA, treatmentColor,
                    printTreatmentDesc ? 9f : 10f);
        y += 50;
        print(canvas, study.getMetadataMap().get("LICENSENO"), x + 74, doc.getPageSize().getHeight() - y, x2,
                15, 10, FontFactory.HELVETICA, Color.BLACK, 10f);
        y += 13;
        print(canvas, study.getMetadataMap().get("EXPERIMENTER"), x + 74, doc.getPageSize().getHeight() - y, x2,
                20, 10, FontFactory.HELVETICA, Color.BLACK, 10f);
    }

    doc.close();
    os.close();
    Desktop.getDesktop().open(f);
    try {
        Thread.sleep(500);
    } catch (Exception e) {
    }

}

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

public void draw(Document doc, int iconNum, String pageNum, String toolName) {
    try {/*from  w w  w  .j  a  v a  2  s  .c  om*/
        PdfContentByte cb = writer.getDirectContentUnder();
        BaseFont fontBold = BaseFont.createFont(Locations.getFontLocation() + "timesbd.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        BaseFont font = BaseFont.createFont(Locations.getFontLocation() + "times.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        Rectangle rct = new Rectangle(doc.getPageSize());
        float iconBase = (1.25f * 72); // This is the base of the icons on
        // the page
        Image icon = Image.getInstance(Locations.getImageLocation() + icons[iconNum]);
        // Image box = Image.getInstance(Locations.ImageLocation() +
        // "blueBOX.png");
        icon.scalePercent(23);
        float scale = .23f;
        float iconLeft = (icon.getWidth() / 2) * scale;
        float boxSize = (.1875f * 72);

        // Adjust the top
        rct.setTop(rct.getTop() - (.5f * 72));

        // Place the Icon
        icon.setAbsolutePosition((1.25f * 72) - iconLeft, rct.getTop() - iconBase);
        doc.add(icon);

        // Set our line color
        cb.setRGBColorStroke(0, 72, 117);

        cb.setLineWidth(.75f);

        // do the bottom line
        cb.moveTo(1.25f * 72, (.5f * 72));
        cb.lineTo(rct.getRight() - (.5f * 72), (.5f * 72));

        cb.moveTo(1.25f * 72, (.5f * 72));
        cb.lineTo(1.25f * 72, rct.getTop());

        // stroke the lines
        cb.stroke();

        // Do the lower left box
        cb.rectangle((1.25f - 0.09375f) * 72, (.5f - 0.09375f) * 72, boxSize, boxSize);
        cb.setRGBColorFill(0, 72, 117);
        cb.closePathFillStroke();

        // Do the lower right box
        Rectangle pnRect = new Rectangle(0, 0);
        pnRect.setLeft(rct.getRight() - ((.5f + 0.09375f) * 72));
        pnRect.setTop((.5f - 0.09375f) * 72);
        pnRect.setRight(pnRect.getLeft() + boxSize);
        pnRect.setBottom(pnRect.getTop() - boxSize);

        // cb.rectangle(rct.getRight() - ((.5f + 0.09375f) * 72), (.5f -
        // 0.09375f) * 72, (.1875f * 72), (.1875f * 72));
        cb.rectangle(pnRect.getLeft(), pnRect.getTop(), boxSize, boxSize);
        cb.setRGBColorFill(0, 72, 117);
        cb.closePathFillStroke();

        // Now we do the page number if one is supplied.
        if (pageNum.length() > 0) {
            float pnHeight = fontBold.getAscentPoint(pageNum, 9) - fontBold.getDescentPoint(pageNum, 9);
            float pnWidth = fontBold.getWidthPoint(pageNum, 9);

            float l = pnRect.getLeft() + ((boxSize - pnWidth) / 2);
            float b = pnRect.getTop() + ((boxSize - pnHeight) / 2);

            cb.beginText();
            cb.setFontAndSize(fontBold, 9);
            cb.setRGBColorFill(255, 255, 255);
            cb.setTextMatrix(l, b);
            cb.showText(pageNum);
            cb.endText();

        }

        // Display the copyright
        SimpleDateFormat df = new SimpleDateFormat("yyyy");
        char cs = 0x00a9; // Unicode for the copyright symbol
        String copyRight = com.estate.constants.StringConstants.copyRight + cs + " " + df.format(new Date());
        float crWidth;
        float crLeft;

        crWidth = font.getWidthPoint(copyRight, 8);
        cb.beginText();

        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(0, 0, 0);

        crLeft = (doc.getPageSize().getRight() - crWidth) / 2;
        cb.setTextMatrix(crLeft, .375f * 72); // Place the base of the
        // copyright at 3/8" up from
        // the bottom
        cb.showText(copyRight);
        cb.endText();

        if (toolName.length() > 0) {
            cb.beginText();

            cb.setFontAndSize(font, 8);
            cb.setRGBColorFill(0, 0, 0);

            cb.setTextMatrix((1.25f * 72) + boxSize, .375f * 72);
            cb.showText(toolName);
            cb.endText();
        }

        // Fix a licensee at left
        cb.beginText();
        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(0, 0, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, " Licensee: " + getLicense(), (10.2f * 72), .375f * 72,
                0);
        cb.endText();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}