Example usage for com.itextpdf.text Phrase Phrase

List of usage examples for com.itextpdf.text Phrase Phrase

Introduction

In this page you can find the example usage for com.itextpdf.text Phrase Phrase.

Prototype

public Phrase() 

Source Link

Document

Constructs a Phrase without specifying a leading.

Usage

From source file:com.microware.intrahealth.Createpdfall.java

private static void createTable7(Paragraph preface, String Text, String Value) throws BadElementException {

    Context _con = null;/*  ww  w .j  a va2 s .  co  m*/

    PdfPTable table = new PdfPTable(new float[] { 1, 2 });
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
    for (int i = 0; i < 2; i++) {
        //      table.addCell(new PdfPCell(new Phrase(Header[i], smallBold)));
        PdfPCell c1 = new PdfPCell(new Phrase());
        table.addCell(c1);
    }
    PdfPCell[] cells = table.getRow(0).getCells();
    //        for (int j=0;j<cells.length;j++){
    cells[0].setHorizontalAlignment(Element.ALIGN_LEFT);
    //        }

    dataprovider = new DataProvider(_con);

    if (Text.length() > 0 && Value.length() > 0) {
        Phrase phrase = new Phrase();
        phrase.add(new Chunk(Text, subFont));
        table.addCell(phrase);
        table.addCell(Value);
    } else {
        Phrase phrase = new Phrase();
        phrase.add(new Chunk(Text, subFont));
        table.addCell(phrase);
        table.addCell("");
    }

    preface.add(table);

}

From source file:com.pdi.util.PdfGenerator.java

public static void generarPresupuesto(String lugar, Date fecha, float cantidad, String tipo, Cliente cliente,
        float precio, Aliado aliado, String path) {

    try {/*w  w  w.  j av a 2s  .  co m*/

        NEGRITA_12_VERDE.setColor(145, 189, 57);

        long miliSemana = System.currentTimeMillis() + (86400 * 7 * 1000);
        Date vtoPresup = new Date(miliSemana);
        float precioPers = precio / cantidad;
        int precioTotalInt = Math.round(precio);
        int precioPersInt = Math.round(precioPers);
        int cantPersonasInt = Math.round(cantidad);

        //Referencia al objeto Doc
        Document document = new Document(PageSize.A4, //Dimensiones
                36, //margIzq
                36, //margDer
                36, //margenSup
                36); // margenInf

        //Creamos el archivo fisico
        FileOutputStream salida = new FileOutputStream(path);

        //Referencia e inicializacion del objeto que "escribe" el PDF
        PdfWriter writer = PdfWriter.getInstance(document, salida);
        writer.setInitialLeading(0);

        //Imagen Logo
        Image logoPDI = Image.getInstance("Logo PDI.png");
        logoPDI.scaleToFit(215, 205);
        logoPDI.setAlignment(Chunk.ALIGN_LEFT);
        //image.setAbsolutePosition(200, 200);

        //Imagen QR
        Image qr = Image.getInstance("QR PDI.png");
        qr.scaleToFit(211, 165);
        qr.setAbsolutePosition(295, PageSize.A4.getHeight() - 390);

        //Parrafo info evento
        Paragraph infoEvento = new Paragraph();
        infoEvento.add(new Chunk("Informacin del Evento", NEGRITA_SUB_12));
        infoEvento.add(Chunk.NEWLINE);
        infoEvento.add(negritaNormal("Solicitante: ", cliente.toString()));
        infoEvento.add(negritaNormal("Evento: ", tipo));
        infoEvento.add(negritaNormal("Cantidad de personas: ", Integer.toString(cantPersonasInt)));
        infoEvento.add(negritaNormal("Fecha: ", General.formatoFecha.format(fecha)));
        infoEvento.add(negritaNormal("Lugar:  ", lugar));
        infoEvento.add(Chunk.NEWLINE);
        infoEvento.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Modalidad del Servicio
        Paragraph modalidadServicio = new Paragraph();
        modalidadServicio.add(new Chunk("Modalidad Servicio Integral", NEGRITA_SUB_12));
        modalidadServicio.add(Chunk.NEWLINE);
        modalidadServicio.add(new Chunk("Nuestro servicio incluye la totalidad de lo referido a"
                + " los elementos necesarios para el despacho de bebidas: Barras, Bartenders,"
                + " Artculos de Coctelera, Insumos de calidad para los tragos y Mucha Buena Onda."
                + " Con esta modalidad aseguramos la expedicin de "
                + "los tragos desde las 00hs hasta las 05hs, para que se desentiendan del asunto "
                + "y disfruten al mximo.", NORMAL_12));
        modalidadServicio.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Ver Carta
        Paragraph verCarta = new Paragraph();
        verCarta.add(negritaNormal("\u2022 Carta de Tragos: ", "Ver archivo adjunto."));
        verCarta.setIndentationLeft(20);
        verCarta.add(Chunk.NEWLINE);
        verCarta.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Titulo Info Contratacion
        Paragraph infoContratacionTitulo = new Paragraph();
        infoContratacionTitulo.add(new Chunk("Informacin de Contratacin", NEGRITA_SUB_12));
        infoContratacionTitulo.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Inf de Contratacion
        Paragraph infoContratacion = new Paragraph();
        infoContratacion.add(negritaNormal("\u2022 Mtodo de contratacin y reserva de la fecha: ",
                "A travs de contrato firmado por ambas partes. "));
        Phrase lineaCosto = new Phrase();
        lineaCosto.add(new Chunk("\u2022 Costo: ", NEGRITA_12));
        lineaCosto.add(new Chunk("$" + Integer.toString(precioPersInt) + " ", NEGRITA_14));
        lineaCosto.add(new Chunk("por persona ", NEGRITA_12));
        lineaCosto.add(new Chunk("(Total: $" + Integer.toString(precioTotalInt) + ")", NEGRITA_14));
        infoContratacion.add(lineaCosto);
        infoContratacion.add(Chunk.NEWLINE);
        infoContratacion.add(negritaNormal("\u2022 Forma de Pago : ",
                "50% al momento de la firma del contrato y 50% como mximo una semana antes del evento. "));
        infoContratacion.add(Chunk.NEWLINE);
        infoContratacion.setIndentationLeft(20);
        infoContratacion.setFirstLineIndent(0);
        infoContratacion.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Despedida
        Paragraph despedida = new Paragraph();
        despedida.add(new Phrase("Quedamos al aguardo de tus comentarios,", NEGRITA_14));
        despedida.add(Chunk.NEWLINE);
        despedida.add(new Phrase("Muchas Gracias.", NEGRITA_14));
        despedida.add(Chunk.NEWLINE);
        despedida.add(Chunk.NEWLINE);
        despedida.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Firma
        Paragraph firma = new Paragraph();
        firma.add(new Phrase("Piel de Iguana Tragos.-", NEGRITA_CUR_14));
        firma.add(Chunk.NEWLINE);
        firma.add(new Phrase("Cel.: 3462-15337860", NEGRITA_12_VERDE));
        firma.setAlignment(Paragraph.ALIGN_RIGHT);

        float llxLink = 279;
        float llyLink = PageSize.A4.getHeight() - 145;
        float anchoLink = 199;
        float altoLink = 16;

        //Link al facebook
        URL urlPDI = new URL("https://www.facebook.com/pieldeiguanatragos.vt");
        PdfAction irAlFace = new PdfAction(urlPDI);
        Rectangle linkLocation = new Rectangle(llxLink, llyLink, llxLink + anchoLink, llyLink + altoLink);
        PdfAnnotation link = PdfAnnotation.createLink(writer, linkLocation, PdfAnnotation.HIGHLIGHT_NONE,
                irAlFace);
        link.setBorder(new PdfBorderArray(0, 0, 0));
        writer.addAnnotation(link);

        //Espacios Vacios
        Paragraph dosEspacios = new Paragraph();
        dosEspacios.add(Chunk.NEWLINE);
        dosEspacios.add(Chunk.NEWLINE);

        //Hay que abrir el Documento, llenarlo con los elemntos creados
        //en el orden que queremos y cerrarlo
        document.open();

        PdfContentByte cb = writer.getDirectContent();

        ColumnText ct = new ColumnText(cb);
        Phrase recuadro = new Phrase();
        recuadro.add(new Chunk("Piel de Iguana Tragos", NEGRITA_SUB_14));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("Servicio de tragos para eventos", NEGRITA_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("\"Piel de Iguana, para que tu noche nica sea inigualable.\"", NORMAL_CUR_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        Image logoFB = Image.getInstance("Icono FB.png");
        logoFB.scaleToFit(13, 13);
        recuadro.add(new Chunk(logoFB, 0, -3));
        recuadro.add(new Chunk("/pieldeiguanatragos.vt  -> Click Aqu!", NORMAL_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("Vencimiento del Prepuesto " + General.formatoFecha.format(vtoPresup),
                NORMAL_SUB_12));

        float llx = 279;
        float lly = PageSize.A4.getHeight() - 185;
        float ancho = 228;
        float alto = 150;

        ct.setSimpleColumn(recuadro, //Texto
                llx, //punta inf izquierda (x)
                lly, //punta inf izquierda (y) PageSize.A4.getHeight() - 185
                llx + ancho, //ancho del cuadro
                lly + alto, // alto del cuadro
                15, //espaciado
                Element.ALIGN_LEFT // Alineacion
        );

        ct.go();

        document.add(logoPDI);
        document.add(qr);
        document.add(dosEspacios);
        document.add(infoEvento);
        document.add(modalidadServicio);
        document.add(verCarta);
        document.add(infoContratacionTitulo);
        document.add(infoContratacion);
        document.add(despedida);
        document.add(firma);
        document.close();
        System.out.println("Archivo creado");
        int rta = JOptionPane.showConfirmDialog(VentanaMaestra.eventosCurrent,
                "Se guard el presupesto en:\n" + path + "\nDesea abrirlo?", "Presupuesto guardado",
                JOptionPane.YES_NO_OPTION);

        if (rta == JOptionPane.YES_OPTION) {
            if (Desktop.isDesktopSupported()) {
                try {
                    File myFile = new File(path);
                    Desktop.getDesktop().open(myFile);
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(VentanaMaestra.eventosCurrent,
                            "No se puede abrir el archivo. Ubiquelo en su equipo" + "y abralo manualmente.",
                            "Error al abrir el archivo", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(VentanaMaestra.eventosCurrent,
                        "No se puede abrir el archivo. Ubiquelo en su equipo" + "y abralo manualmente.",
                        "Error al abrir el archivo", JOptionPane.ERROR_MESSAGE);
            }

        }

    } catch (FileNotFoundException ex) {
        System.out.println("Error: " + ex.toString());
    } catch (DocumentException ex) {
        System.out.println("Error: " + ex.toString());
    } catch (IOException ex) {
        System.out.println("Error: " + ex.toString());
    }

}

From source file:com.pdi.util.PdfGenerator.java

public static Phrase negritaNormal(String negrita, String normal) {
    Phrase frase = new Phrase();
    frase.add(new Chunk(negrita, NEGRITA_12));
    frase.add(new Chunk(normal, NORMAL_12));
    frase.add(Chunk.NEWLINE);//from  w  w  w . jav a2 s  .  c o  m
    return frase;

}

From source file:de.beimax.talenttree.AbstractPageGenerator.java

License:Open Source License

/**
 * Parse a string to PDF/itext phrase to be rendered later
 * @param key language key//from   w ww  .  ja  v a2s.c  om
 * @param fontSize size of font
 * @param narrowFonts use narrow fonts?
 * @return
 * @throws Exception
 */
protected Phrase parseTextProperty(String key, float fontSize, boolean narrowFonts) throws Exception {
    // define fonts
    Font fontRegular, fontBold;
    if (narrowFonts) {
        fontRegular = new Font(generator.getFontCondensedRegular(), fontSize);
        fontBold = new Font(generator.getFontCondensedBold(), fontSize);
    } else {
        fontRegular = new Font(generator.getFontRegular(), fontSize);
        fontBold = new Font(generator.getFontBold(), fontSize);
    }
    Font fontSymbol = new Font(generator.getFontSymbol(), fontSize);

    Phrase phrase = new Phrase();
    phrase.setLeading(fontSize * 1.2f);

    // get localized element
    String localized = getLocalizedString(key);
    for (String part : localized.split("\\|")) {
        if (part.length() == 0)
            continue; // make sure to not fire index out of range
        char first = part.charAt(0);
        char last = part.charAt(part.length() - 1);
        switch (first) {
        case '*': // bold
            part = part.substring(1); // remove first char
            if (last == ' ')
                part = part.substring(0, part.length() - 1);
            phrase.add(new Chunk(part, fontBold));
            if (last == ' ')
                phrase.add(new Chunk(" ", fontRegular));
            break;
        case '#': // symbol font
            part = part.substring(1); // remove first char
            if (last == ' ')
                part = part.substring(0, part.length() - 1);
            phrase.add(new Chunk(part, fontSymbol));
            if (last == ' ')
                phrase.add(new Chunk(" ", fontRegular));
            break;
        default: // all other cases
            phrase.add(new Chunk(part, fontRegular));
        }
    }

    return phrase;
}

From source file:de.beimax.talenttree.PageGeneratorCareer.java

License:Open Source License

/**
 * Add skill data/*from  w ww .j  a va 2  s. c om*/
 * @param prefix translated prefix (printed bold) without :
 * @param dataKey data key in YAML file, skills/bonus_skills
 * @throws Exception
 */
protected void addSkillData(String prefix, String dataKey) throws Exception {
    Font fontRegular = new Font(generator.getFontRegular(), 10.5f);
    Font fontBold = new Font(generator.getFontBold(), 10.5f);

    // add career skills
    Phrase phrase = new Phrase();
    phrase.add(new Chunk(prefix + ": ", fontBold));
    ArrayList<String> skills = new ArrayList<String>();
    //noinspection unchecked
    for (String key : (Iterable<String>) data.get(dataKey))
        skills.add(getLocalizedString(key));
    // sort localized
    Collections.sort(skills, Collator.getInstance());
    // build skill list
    StringBuilder sb = new StringBuilder();
    for (String skill : skills) {
        if (sb.length() != 0)
            sb.append(", ");
        sb.append(skill);
    }
    phrase.add(new Chunk(sb.toString(), fontRegular));
    Paragraph p = new Paragraph(phrase);
    p.setAlignment(Element.ALIGN_JUSTIFIED);
    p.setIndentationRight(getUsablePageWidth() - PDFGenerator.headerTextMaxWidth);
    p.setLeading(13.2f);
    document.add(p);
}

From source file:de.domjos.schooltools.core.utils.fileUtils.PDFBuilder.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    try {/*from  w ww .j  av a  2s. com*/
        Rectangle rect = writer.getBoxSize("art");
        Image img = Image.getInstance(Converter.convertDrawableToByteArray(this.context, R.drawable.icon));
        Phrase phrase = new Phrase();
        phrase.add(new Chunk(img, 0, 0));
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, phrase, rect.getLeft(),
                rect.getBottom(), 0);
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
                new Phrase(String
                        .valueOf(this.context.getString(R.string.api_page) + " " + document.getPageNumber())),
                rect.getRight(), rect.getBottom(), 0);
    } catch (Exception ex) {
        Helper.printException(context, ex);
    }
}

From source file:de.extra.xtt.util.pdf.PdfCreatorImpl.java

License:Apache License

/**
 * Fr die angegebenen Kindlemente wird ein Listeneintrag fr das PDF
 * erzeugt./*from   w  ww . ja  v a 2s .c o m*/
 * 
 * @param childs
 *            Kindelemente
 * @param schemaQueues
 *            Queues mit allen Elementen fr die einzelnen Schemas
 * @param strBullet
 *            Zeichen, das als Aufzhlunsgzeichen fr die Liste verwendet
 *            wird
 * @return PDF-Liste mit den Kindelementen
 */
private List erzeugeListeFuerKindElemente(XSParticle[] childs, Map<String, Queue<XSElementDecl>> schemaQueues,
        String strBullet) {

    List currList = new List(false, 12);
    currList.setListSymbol(strBullet);

    for (XSParticle currChild : childs) {

        if (currChild.getTerm() instanceof ElementDecl) {
            // Elemente von sequence bzw. choice abarbeiten
            XSElementDecl currElement = currChild.getTerm().asElementDecl();

            Phrase currPhrase = new Phrase();

            // Name, inkl. Referenz auf das Element
            currPhrase.add(getChunkTextBoldWithReference(getNameWithPrefix(currElement),
                    getReferenceForElement(currElement)));

            // Auftreten (direkt hinter dem Namen)
            currPhrase.add(getChunkText(" (" + getMinMaxStr(currChild) + ")\n"));

            // Beschreibung
            XSAnnotation currAnn = currChild.getAnnotation();
            if ((currAnn == null) && currElement.isLocal() && (currElement.getAnnotation() != null)) {
                currAnn = currElement.getAnnotation();
            }
            if (currAnn != null) {
                currPhrase.add(getChunkTextItalic(currAnn.getAnnotation().toString() + "\n"));
            }

            currList.add(new ListItem(currPhrase));

            // Element in Queue einfgen
            String currPrefix = getNsPref(currElement.getTargetNamespace());
            schemaQueues.get(currPrefix).add(currElement);

        } else if (currChild.getTerm() instanceof XSModelGroup) {
            // Element von sequence/choice kann wieder eine ModelGroup
            // (sequence/choice) sein
            XSModelGroup mg = currChild.getTerm().asModelGroup();
            XSParticle[] childChilds = mg.getChildren();
            if ((childChilds != null) && (childChilds.length > 0)) {

                // Art der Gruppe
                String strCompositor = "";
                Compositor compositor = mg.getCompositor();
                if (compositor.equals(com.sun.xml.xsom.XSModelGroup.Compositor.SEQUENCE)) {
                    strCompositor = "Sequence:";
                } else if (compositor.equals(com.sun.xml.xsom.XSModelGroup.Compositor.CHOICE)) {
                    strCompositor = "Choice:";
                }
                currList.add(new ListItem(getPhraseTextBold(strCompositor)));

                // neue Liste fr aktuelle Kindelemente erzeugen
                List subList = erzeugeListeFuerKindElemente(childChilds, schemaQueues, bulletSub);

                // Als Subliste hinzufgen
                currList.add(subList);
            }

        } else if (currChild.getTerm() instanceof XSWildcard) {
            // Element von sequence/choice kann ein Wildcard-Objekt sein,
            // z.B. 'xs:any'
            XSWildcard wildCard = currChild.getTerm().asWildcard();
            String currNamespaceStr = wildCard.apply(MySchemaWriter.WILDCARD_NS);

            Phrase currPhrase = new Phrase();
            currPhrase.add(getChunkTextBold("any"));
            currPhrase.add(getChunkText(" (" + getMinMaxStr(currChild) + ")\n"));
            if (currNamespaceStr.length() > 0) {
                currPhrase.add(getChunkText(currNamespaceStr));
            }
            currList.add(new ListItem(currPhrase));
        }
    }
    return currList;
}

From source file:EplanPrinter.PDFPrint.java

License:Open Source License

public Phrase composePhrase(String str, BaseFont normalFont, BaseFont boldFont)
        throws DocumentException, IOException {
    ArrayList<Chunk> chunks = new ArrayList();

    // unescape all HTML encode i.e &lt; = <
    str = HtmlDecoder.unescapeHTML(str);

    // replace all <li> with bullet symbol
    str = Pattern.compile("\\<li*?\\>", Pattern.CASE_INSENSITIVE).matcher(str)
            .replaceAll(new Character('\u2022') + " ");

    String words[] = str.split(" ");
    for (int i = 0; i < words.length; i++) {
        String noHtml = words[i];
        BaseFont font = boldFont;//from   ww w  .  j  av  a2 s  .  c om
        if (hasHtmlTag(noHtml, REGEX_B)) {
            noHtml = removeHtmlTag(words[i]);
        } else if (hasHtmlTag(noHtml, REGEX_I)) {
            noHtml = removeHtmlTag(words[i]);
        } else if (hasHtmlTag(noHtml, REGEX_EM)) {
            noHtml = removeHtmlTag(words[i]);
        } else if (hasHtmlTag(noHtml, REGEX_STRONG)) {
            noHtml = removeHtmlTag(words[i]);
        } else if (hasHtmlTag(noHtml, REGEX_LI)) {
            noHtml = new Character('\u2022') + " " + removeHtmlTag(words[i]);
            font = normalFont;
        } else if (hasHtmlTag(noHtml, REGEX_DT)) {
            noHtml = new Character('\u2022') + " " + removeHtmlTag(words[i]);
            font = normalFont;
        } else if (hasHtmlTag(noHtml, REGEX_DD)) {
            noHtml = new Character('\u2022') + " " + removeHtmlTag(words[i]);
            font = normalFont;
        } else {
            noHtml = removeHtmlTag(words[i]);
            font = normalFont;
        }

        chunks.add(new Chunk(noHtml + " ", new Font(font, fontSize)));
    }

    Phrase phrase = new Phrase();
    for (Chunk chunk : chunks) {
        phrase.add(chunk);
    }

    return phrase;
}

From source file:eu.aniketos.wp1.ststool.report.pdfgenerator.AbstractContentFactory.java

License:Open Source License

protected PdfPCell getHeaderCell(String[] header) {

    Phrase p = new Phrase();
    p.setFont(TABLE_HEADER);// w w  w.j a  v a 2s.c o  m
    for (String s : header) {
        p.add(new Chunk(s));
        p.add(Chunk.NEWLINE);
    }
    PdfPCell cell = new PdfPCell(p);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBorder(Rectangle.BOTTOM | Rectangle.TOP);
    cell.setBorderWidthTop(1.5f);
    cell.setBorderWidthBottom(1.5f);
    cell.setPaddingBottom(7);
    cell.setPaddingTop(2);
    return cell;
}

From source file:femr.ui.controllers.PDFController.java

License:Open Source License

private Phrase getStyledPhrase(String title, String value) {
    Phrase phrase = new Phrase();
    phrase.add(new Chunk(title, getTitleFont()));
    phrase.add(new Chunk(value, getValueFont()));
    return phrase;
}