Example usage for com.itextpdf.text Phrase add

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

Introduction

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

Prototype

@Override
public boolean add(final Element element) 

Source Link

Document

Adds a Chunk, Anchor or another Phrase to this Phrase.

Usage

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

private static void createTable1(Paragraph preface, String[] Header, String[] Text, String[] Value)
        throws BadElementException {

    Context _con = null;//from  w  w  w  .j a  v  a 2  s .c  o  m

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

    table.setHeaderRows(1);

    PdfPCell[] cells = table.getRow(0).getCells();
    for (int j = 0; j < cells.length; j++) {
        cells[j].setBackgroundColor(new BaseColor(0, 85, 133));

        if (j == 0) {
            cells[j].setHorizontalAlignment(Element.ALIGN_LEFT);
        } else {
            cells[j].setHorizontalAlignment(Element.ALIGN_CENTER);
        }
    }

    dataprovider = new DataProvider(_con);

    if (Text.length == Value.length) {
        for (int i = 0; i < Value.length; i++) {
            Phrase phrase = new Phrase();
            phrase.add(new Chunk(Text[i], subFont));
            table.addCell(phrase);
            table.addCell(Value[i]);
            PdfPCell[] cells1 = table.getRow(i + 1).getCells();
            cells1[0].setHorizontalAlignment(Element.ALIGN_LEFT);
            cells1[1].setHorizontalAlignment(Element.ALIGN_CENTER);
        }
    } else {
        for (int i = 0; i < Value.length; i++) {
            Phrase phrase = new Phrase();
            phrase.add(new Chunk(Text[i], subFont));
            table.addCell(phrase);
            table.addCell("");
            PdfPCell[] cells1 = table.getRow(i + 1).getCells();
            cells1[0].setHorizontalAlignment(Element.ALIGN_LEFT);
        }
    }

    preface.add(table);

}

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

private static void createTable2(Paragraph preface, String[] Header, String[] Text, String[] Source,
        String[] Value) throws BadElementException {

    Context _con = null;/*w  w  w.jav a 2s  .c o  m*/

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

    table.setHeaderRows(1);

    PdfPCell[] cells = table.getRow(0).getCells();
    for (int j = 0; j < cells.length; j++) {
        cells[j].setBackgroundColor(new BaseColor(0, 85, 133));

        if (j == 0) {
            cells[j].setHorizontalAlignment(Element.ALIGN_LEFT);
        } else {
            cells[j].setHorizontalAlignment(Element.ALIGN_CENTER);
        }
    }

    dataprovider = new DataProvider(_con);

    if (Text.length == Value.length) {
        for (int i = 0; i < Value.length; i++) {
            Phrase phrase = new Phrase();
            phrase.add(new Chunk(Text[i], subFont));
            table.addCell(phrase);
            table.addCell(Source[i]);
            table.addCell(Value[i]);
            PdfPCell[] cells1 = table.getRow(i + 1).getCells();
            cells1[0].setHorizontalAlignment(Element.ALIGN_LEFT);
            cells1[1].setHorizontalAlignment(Element.ALIGN_CENTER);
            cells1[2].setHorizontalAlignment(Element.ALIGN_CENTER);
        }
    } else {
        for (int i = 0; i < Value.length; i++) {
            Phrase phrase = new Phrase();
            phrase.add(new Chunk(Text[i], subFont));
            table.addCell(phrase);
            table.addCell("");
            table.addCell("");
            PdfPCell[] cells1 = table.getRow(i + 1).getCells();
            cells1[0].setHorizontalAlignment(Element.ALIGN_LEFT);
        }
    }

    preface.add(table);

}

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

private static void createTable4(Paragraph preface, String[] Header, String Text, String Value)
        throws BadElementException {

    Context _con = null;/*w ww .  j a  v  a 2  s  .  c  o  m*/

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

    table.setHeaderRows(1);

    PdfPCell[] cells = table.getRow(0).getCells();
    for (int j = 0; j < cells.length; j++) {
        cells[j].setBackgroundColor(new BaseColor(0, 85, 133));

        if (j == 0) {
            cells[j].setHorizontalAlignment(Element.ALIGN_LEFT);
        } else {
            cells[j].setHorizontalAlignment(Element.ALIGN_CENTER);
        }
    }

    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);
        PdfPCell[] cells1 = table.getRow(1).getCells();
        cells1[0].setHorizontalAlignment(Element.ALIGN_LEFT);
        cells1[1].setHorizontalAlignment(Element.ALIGN_CENTER);
    } else {
        Phrase phrase = new Phrase();
        phrase.add(new Chunk(Text, subFont));
        table.addCell(phrase);
        table.addCell("");
        PdfPCell[] cells1 = table.getRow(1).getCells();
        cells1[0].setHorizontalAlignment(Element.ALIGN_LEFT);
    }

    preface.add(table);

}

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

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

    Context _con = null;/*from   w  ww.  java  2  s.  c  o  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 {//from  w  w  w  .  j a  va2  s.  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);/* w  ww  . j av  a 2  s  .co m*/
    return frase;

}

From source file:com.thelinh.gui.PreviewExam.java

private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed
    if (this.txtExamCode.getText().equals("")) {
        JOptionPane.showMessageDialog(this, "Hy nhp m ?");
    } else {/*  www. j  a  v a 2  s. c  o m*/
        JFileChooser fc = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF files (*.pdf)", "pdf");
        fc.setFileFilter(filter);
        int rt = fc.showSaveDialog(this);
        if (rt == JFileChooser.APPROVE_OPTION) {
            String filepath = fc.getSelectedFile().getPath();
            if (filepath.indexOf(".") == -1) {
                filepath = filepath + ".pdf";
            }
            String dafilepath = (new StringBuffer(filepath)).insert(filepath.length() - 4, ".da").toString();
            try {
                Document document = new Document();
                PdfWriter.getInstance(document, new FileOutputStream(filepath));
                document.open();

                // Add title
                Paragraph p = new Paragraph("Tr?ng ?i h?c Bch Khoa H Ni", timesBold_25);
                p.setAlignment(Element.ALIGN_CENTER);
                p.setSpacingAfter(5);
                document.add(p);

                p = new Paragraph("?? thi mn " + this.lbSubject.getText(), timesBold_25);
                p.setAlignment(Element.ALIGN_CENTER);
                p.setSpacingAfter(25);
                document.add(p);

                p = new Paragraph(
                        "Ng?i ra ?: " + Controller.getCurrentAdmin().getAdminName()
                                + ", Ngy ra ?: "
                                + (new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())),
                        times_15);
                p.setAlignment(Element.ALIGN_LEFT);
                p.setSpacingAfter(5);
                document.add(p);

                p = new Paragraph("M ?: " + this.txtExamCode.getText() + "    Th?i gian lm bi: "
                        + spTime.getValue().toString() + " pht", timesBold_15);
                p.setSpacingAfter(25);
                document.add(p);

                for (int i = 0; i < this.questionList.size(); i++) {
                    Question question = this.questionList.get(i);
                    ArrayList<Answer> answerList = AnswerSql
                            .getAnswersByQuestionId(question.getQuestionId().trim());
                    Phrase questionNumber = new Phrase("Cu " + (i + 1) + ": ", timesBold_15);
                    Phrase questionContent = new Phrase(question.getQuestion(), times_15);

                    Paragraph questionTitle = new Paragraph();
                    questionTitle.add(questionNumber);
                    questionTitle.add(questionContent);

                    document.add(questionTitle);
                    PdfPTable table = new PdfPTable(2);

                    for (int j = 0; j < answerList.size(); j++) {
                        Answer ans = answerList.get(j);
                        Phrase cap = new Phrase(Character.toString((char) (j + 65)) + ". ", timesBold_15);
                        Phrase answerContent = new Phrase(ans.getAnswer(), times_15);
                        Phrase elem = new Phrase();
                        elem.add(cap);
                        elem.add(answerContent);
                        PdfPCell cell = new PdfPCell();

                        cell.setBorder(Rectangle.NO_BORDER);
                        cell.setPhrase(elem);
                        cell.setFixedHeight(25);
                        table.addCell(cell);
                    }
                    document.add(table);
                }
                document.close();
                //                    if (Desktop.isDesktopSupported()) {
                //                        try {
                //                            File myFile = new File(filepath);
                //                            Desktop.getDesktop().open(myFile);
                //                        } catch (IOException ex) {
                //                            // no application registered for PDFs
                //                            System.out.println(ex.toString());
                //                        }
                //                    }

                document = new Document();
                PdfWriter.getInstance(document, new FileOutputStream(dafilepath));
                document.open();

                // Add title
                p = new Paragraph("Tr?ng ?i h?c Bch Khoa H Ni", timesBold_25);
                p.setAlignment(Element.ALIGN_CENTER);
                p.setSpacingAfter(5);
                document.add(p);

                p = new Paragraph("?? thi mn " + this.lbSubject.getText(), timesBold_25);
                p.setAlignment(Element.ALIGN_CENTER);
                p.setSpacingAfter(25);
                document.add(p);

                p = new Paragraph(
                        "Ng?i ra ?: " + Controller.getCurrentAdmin().getAdminName()
                                + ", Ngy ra ?: "
                                + (new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())),
                        times_15);
                p.setAlignment(Element.ALIGN_LEFT);
                p.setSpacingAfter(5);
                document.add(p);

                p = new Paragraph("M ?: " + this.txtExamCode.getText() + "    Th?i gian lm bi: "
                        + spTime.getValue().toString() + " pht", timesBold_15);
                p.setSpacingAfter(25);
                document.add(p);

                for (int i = 0; i < this.questionList.size(); i++) {
                    Question question = this.questionList.get(i);
                    ArrayList<Answer> answerList = AnswerSql
                            .getAnswersByQuestionId(question.getQuestionId().trim());
                    Phrase questionNumber = new Phrase("Cu " + (i + 1) + ": ", timesBold_15);
                    Phrase questionContent = new Phrase(question.getQuestion(), times_15);

                    Paragraph questionTitle = new Paragraph();
                    questionTitle.add(questionNumber);
                    questionTitle.add(questionContent);

                    document.add(questionTitle);
                    PdfPTable table = new PdfPTable(2);

                    for (int j = 0; j < answerList.size(); j++) {
                        Answer ans = answerList.get(j);
                        Phrase cap = new Phrase(Character.toString((char) (j + 65)) + ". ", timesBold_15);
                        Phrase answerContent = null;
                        if (ans.getYesNo()) {
                            answerContent = new Phrase(ans.getAnswer(), timesBold_15);
                        } else {
                            answerContent = new Phrase(ans.getAnswer(), times_15);
                        }
                        Phrase elem = new Phrase();
                        elem.add(cap);
                        elem.add(answerContent);
                        PdfPCell cell = new PdfPCell();

                        cell.setBorder(Rectangle.NO_BORDER);
                        cell.setPhrase(elem);
                        cell.setFixedHeight(25);
                        table.addCell(cell);
                    }
                    document.add(table);
                }
                document.close();

            } catch (FileNotFoundException | DocumentException ex) {
                Logger.getLogger(PreviewExam.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

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 w w.j  a  v a2 s  .  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//www  .j a va  2s .  c  o m
 * @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 {//  ww w  .  j ava2s.co m
        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);
    }
}