Example usage for com.lowagie.text FontFactory getFont

List of usage examples for com.lowagie.text FontFactory getFont

Introduction

In this page you can find the example usage for com.lowagie.text FontFactory getFont.

Prototype


public static Font getFont(String fontname, float size, int style, Color color) 

Source Link

Document

Constructs a Font-object.

Usage

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFTitlePage.java

License:Apache License

/************************************************************************************
 * get font as {@link Font} from given font name and size
 * //from  ww  w .ja v  a  2s  . c o  m
 * @param fontname name of font
 * @param fontsize size of font
 * 
 * @throws PDFManagerException
 ************************************************************************************/
private Font getPDFFont(int fontsize) throws PDFManagerException {
    Font resultfont = null;

    // set the base font
    try {
        if (this.ttffontpath == null) {
            // don't use TTF

            LOGGER.debug("Do not use TrueType Font... instead standard Arial is used");
            resultfont = FontFactory.getFont("Arial", BaseFont.CP1252, BaseFont.EMBEDDED, fontsize);

            // String[] codePages = basefont.getCodePagesSupported();
            // System.out.println("All available encodings for font:\n\n");
            // for (int i = 0; i < codePages.length; i++) {
            // System.out.println(codePages[i]);
            // }
        } else {
            // load font, embedd it - use unicode
            LOGGER.debug("Use TrueType Font... at:" + this.ttffontpath);

            BaseFont bf = BaseFont.createFont(this.ttffontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            resultfont = new Font(bf, fontsize);
        }

    } catch (Exception e) {
        LOGGER.error("DocumentException while creating title page for PDF", e);
        throw new PDFManagerException("Exception while creating Titlepage for PDF", e);
    }

    return resultfont;
}

From source file:ec.edu.chyc.manejopersonal.managebean.PDFCustomExporter.java

License:Apache License

@Override
public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle,
        boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, boolean subTable) throws IOException {
    try {//from  ww  w.  jav  a  2 s. c o  m
        Document document = new Document();
        if (orientation.equalsIgnoreCase("Landscape")) {
            document.setPageSize(PageSize.A4.rotate());
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        StringTokenizer st = new StringTokenizer(tableId, ",");
        while (st.hasMoreElements()) {
            String tableName = (String) st.nextElement();
            UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(),
                    tableName);
            if (component == null) {
                throw new FacesException("Cannot find component \"" + tableName + "\" in view.");
            }
            if (!(component instanceof DataTable || component instanceof DataList)) {
                throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName()
                        + "\", exporter must target a PrimeFaces DataTable/DataList.");
            }

            if (preProcessor != null) {
                preProcessor.invoke(context.getELContext(), new Object[] { document });
            }

            if (!document.isOpen()) {
                document.open();
            }
            if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) {

                Font tableTitleFont = FontFactory.getFont(FontFactory.TIMES, encodingType, Font.DEFAULTSIZE,
                        Font.BOLD);
                Paragraph title = new Paragraph(tableTitle, tableTitleFont);
                document.add(title);

                Paragraph preface = new Paragraph();
                addEmptyLine(preface, 3);
                document.add(preface);
            }
            PdfPTable pdf;
            DataList list = null;
            DataTable table = null;
            if (component instanceof DataList) {
                list = (DataList) component;
                pdf = exportPDFTable(context, list, pageOnly, encodingType);
            } else {
                table = (DataTable) component;
                pdf = exportPDFTable(context, table, pageOnly, selectionOnly, encodingType, subTable);
            }

            if (pdf != null) {
                document.add(pdf);
            }
            // add a couple of blank lines
            Paragraph preface = new Paragraph();
            addEmptyLine(preface, datasetPadding);
            document.add(preface);

            if (postProcessor != null) {
                postProcessor.invoke(context.getELContext(), new Object[] { document });
            }
        }
        document.close();

        writePDFToResponse(context.getExternalContext(), baos, filename);

    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:ec.edu.uce.erp.web.common.util.CustomPDFExporter.java

@Override
protected void addColumnFacets(DataTable table, PdfPTable pdfTable, ColumnType columnType) {

    for (UIColumn col : table.getColumns()) {
        if (!col.isRendered()) {
            continue;
        }/*from w  ww  .  jav a  2 s . co m*/
        if (col instanceof DynamicColumn) {
            ((DynamicColumn) col).applyModel();
        }
        if (col.isExportable()) {
            addHeaderValue(pdfTable, col.getFacet(columnType.facet()),
                    FontFactory.getFont(FontFactory.TIMES, "iso-8859-1", Font.DEFAULTSIZE, Font.BOLD));
        }
    }
}

From source file:mitm.common.pdf.MessagePDFBuilder.java

License:Open Source License

private FontSelector createFontSelector(String fontName, float size, int style, Color color) {
    FontSelector selector = new FontSelector();

    selector.addFont(FontFactory.getFont(fontName, size, style, color));

    /*// w ww  .j  ava 2 s  .  c  o m
     * Add extra fonts provided by the FontProvider
     */
    if (fontProvider != null) {
        Collection<Font> extraFonts = fontProvider.getFonts();

        for (Font extraFont : extraFonts) {
            selector.addFont(extraFont);
        }
    }

    /*
     * Supported CJK (Chinese, Japanse, Korean)
     * 
     * his is the list of fonts supported in the iTextAsian.jar:
     * Chinese Simplified:
     *      STSong-Light and STSongStd-Light with the encodings UniGB-UCS2-H and UniGB-UCS2-V
     * Chinese Traditional:
     *      MHei-Medium, MSung-Light and MSungStd-Light with the encodings UniCNS-UCS2-H and UniCNS-UCS2-V
     * Japanese:
     *      HeiseiMin-W3, HeiseiKakuGo-W5 and KozMinPro-Regular with the encodings UniJIS-UCS2-H, UniJIS-UCS2-V, UniJIS-UCS2-HW-H and UniJIS-UCS2-HW-V
     * Korean:
     *      HYGoThic-Medium, HYSMyeongJo-Medium and HYSMyeongJoStd with the encodings UniKS-UCS2-H and UniKS-UCS2-V
     * 
     * Need to find out which fonts we should add to the selector and in which order
     */
    selector.addFont(FontFactory.getFont("KozMinPro-Regular", "UniJIS-UCS2-H", BaseFont.NOT_EMBEDDED, size,
            style, color));
    selector.addFont(
            FontFactory.getFont("MSung-Light", "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED, size, style, color));
    selector.addFont(
            FontFactory.getFont("HYGoThic-Medium", "UniKS-UCS2-H", BaseFont.NOT_EMBEDDED, size, style, color));

    return selector;
}

From source file:mx.avanti.siract.ui.RACTBeanUI.java

public void postProcessPDF(Object document) throws IOException, DocumentException {
    final Document pdf = (Document) document;
    TreeNode[] selectedNodesPDF = selectedNodes;

    if (selectedNodes != null) {
        for (TreeNode nodo : selectedNodes) {
            System.out.println("*********************" + ((NodoMultiClass) nodo.getData()).getNombre());
        }/*from  w  w w .j  av a2 s  . co  m*/
    }
    pdf.setPageSize(PageSize.A4.rotate());
    pdf.open();
    String nombrep = profesor.getPronombre() + " " + profesor.getProapellidoPaterno() + " "
            + profesor.getProapellidoMaterno();
    String numEmpPro = Integer.toString(profesor.getPronumeroEmpleado());
    String porAv = Float.toString(porcentajeAvance);
    SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");

    //Obtener el nombre del programa educativo seleccionado
    String nombreProgEdu = "";
    int programaEducativoSeleccionado2 = Integer.parseInt(programaEducativoSeleccionado);
    for (int x = 0; x < programasEducativos.size(); x++) {
        if (programasEducativos.get(x).getPedid() == programaEducativoSeleccionado2) {
            nombreProgEdu = programasEducativos.get(x).getPednombre();
        }
    }
    //----------------------------------------------------------------------------------

    //Obtener el nombre de la unidad de aprendizaje y clave seleccionada
    String nombreUniApr = "";
    String nombreclave = "";
    int uniAprselec2 = Integer.parseInt(unidadAprendizajeSeleccionada);
    for (int x = 0; x < unidadesaprendisaje.size(); x++) {
        if (unidadesaprendisaje.get(x).getUapclave() == uniAprselec2) {
            nombreUniApr = unidadesaprendisaje.get(x).getUapnombre();
            nombreclave = Integer.toString(unidadesaprendisaje.get(x).getUapclave());
        }
    }
    //----------------------------------------------------------------------

    // rutaImagen es la ruta para acceder a la imagen guardada en el folder resources del proyecto
    try {
        //            Image imagenLogo = Image.getInstance("C:\\Users\\Y\\Desktop\\RACT 22-01-2015\\RACT\\build\\web\\resources\\imagenes\\logo.jpg");
        Image imagenLogo = Image.getInstance(RACTBeanUI.class.getResource("imagenes/logo.jpg"));

        //Posicion de imagen (Horizontal, Vertiacal)
        imagenLogo.setAbsolutePosition(120f, 460f);

        //Tamao de imagen (Ancho, largo)
        imagenLogo.scaleAbsolute(90, 120);
        //imagenLogo.scaleAbsoluteWidth(100f);
        //imagenLogo.scaleAbsoluteHeight(150f);
        //imagenLogo.scaleToFit(100f, 120f); Esta es la buena
        //Image imagenLogo = Image.getInstance("http://ed.uabc.mx/sed/images/logo.jpg");
        //imagenLogo.scaleAbsolute(70f, 90f);
        pdf.add(imagenLogo);
    } catch (Exception exception) {
        System.out.println("****NO SE ENCONTRO LA RUTA DE IMAGEN ESPECIFICADA");
    }
    //Tabla con UABC y Nombre del profesor(a)
    PdfPTable pdfTabletitulo = new PdfPTable(2);
    pdfTabletitulo.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    PdfPTable pdfTabletitulo2 = new PdfPTable(2);
    pdfTabletitulo2.getDefaultCell().setBorder(PdfPCell.NO_BORDER);

    Paragraph UABC = new Paragraph("Universidad Autnoma de Baja California",
            FontFactory.getFont(FontFactory.TIMES, 22, Font.BOLD, new Color(0, 113, 65)));
    UABC.setAlignment(Element.ALIGN_CENTER);
    Paragraph esp = new Paragraph(" ");
    pdf.add(UABC);
    pdf.add(esp);
    pdf.add(esp);
    pdf.add(esp);
    pdf.add(esp);
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));

    pdfTabletitulo.addCell(new Paragraph("Profesor(a): ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdfTabletitulo.addCell(new Paragraph(nombrep));

    pdfTabletitulo2.addCell(new Paragraph("Num. de Empleado: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdfTabletitulo2.addCell(new Paragraph(numEmpPro));

    pdfTabletitulo.setHorizontalAlignment(25);
    //pdfTabletitulo.setHorizontalAlignment(Element.ALIGN_CENTER);
    //document.add(table);
    float[] columnWidthsss = new float[] { 4f, 28 };
    pdfTabletitulo.setWidths(columnWidthsss);
    pdf.add(pdfTabletitulo);

    float[] columnWidthss = new float[] { 10f, 38 };
    pdfTabletitulo2.setWidths(columnWidthss);
    pdf.add(pdfTabletitulo2);

    pdf.add(new Phrase(" "));

    //----------------------------------------------------------------------
    //Tabla Cabezera
    PdfPTable pdftablecabezera = new PdfPTable(4);
    pdftablecabezera.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    PdfPTable pdftablecabezera2 = new PdfPTable(5);
    pdftablecabezera2.getDefaultCell().setBorder(PdfPCell.NO_BORDER);

    pdftablecabezera.addCell(new Paragraph("Programa educativo: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera.addCell(new Paragraph("Fecha: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera.addCell(new Paragraph("Ciclo Escolar: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera.addCell(new Paragraph("Avance Global: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera.addCell(new Paragraph(nombreProgEdu));
    pdftablecabezera.addCell(new Paragraph(formato.format(new Date())));
    pdftablecabezera.addCell(new Paragraph("        " + cicloEscolar));
    pdftablecabezera.addCell(new Paragraph("        " + porAv));

    pdftablecabezera.addCell(new Paragraph(" "));
    pdftablecabezera.addCell(new Paragraph(" "));
    pdftablecabezera.addCell(new Paragraph(" "));
    pdftablecabezera.addCell(new Paragraph(" "));

    pdftablecabezera2.addCell(new Paragraph("Unidad de Aprendizaje: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera2.addCell(new Paragraph("Clave: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera2.addCell(new Paragraph("Grupo: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera2.addCell(new Paragraph("Subgrupo: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera2.addCell(new Paragraph("Tipo Grupo: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera2.addCell(new Paragraph(nombreUnidadSeleccionado));
    pdftablecabezera2.addCell(new Paragraph(claveUnidadAprendizajeSeleccionada));
    pdftablecabezera2.addCell(new Paragraph("   " + grupo));
    pdftablecabezera2.addCell(new Paragraph("       " + subGrupo));
    String tipoGrupo = "";
    switch (this.tipoUnidadAprendizaje) {
    case "C":
        tipoGrupo = "Clase";
        break;
    case "L":
        tipoGrupo = "Laboratorio";
        break;
    case "T":
        tipoGrupo = "Taller";
        break;
    case "P":
        tipoGrupo = "Practica";
        break;
    case "CL":
        tipoGrupo = "Practicas Clinica";
        break;
    }
    pdftablecabezera2.addCell(new Paragraph("       " + tipoGrupo));
    pdftablecabezera2.addCell(new Paragraph(" "));

    pdftablecabezera.setHorizontalAlignment(25);
    float[] columnWidths = new float[] { 38f, 10f, 14f, 18f };
    pdftablecabezera.setWidths(columnWidths);
    pdf.add(pdftablecabezera);

    pdftablecabezera2.setHorizontalAlignment(25);
    float[] columnWidthss2 = new float[] { 38f, 10f, 8f, 11f, 14f };
    pdftablecabezera2.setWidths(columnWidthss2);
    pdf.add(pdftablecabezera2);

    pdf.add(new Phrase(" "));

    //----------------------------------------------------------------------
    Paragraph numrep = new Paragraph("Reporte # " + numeroReporte,
            FontFactory.getFont(FontFactory.TIMES, 16, Font.BOLD, new Color(0, 0, 0)));
    numrep.setAlignment(Element.ALIGN_CENTER);
    pdf.add(numrep);
    pdf.add(new Paragraph(" "));
    //Tabla con Datos 
    PdfPTable pdfTable = new PdfPTable(3);
    pdfTable.addCell(new Phrase("Nombre",
            FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0))));
    pdfTable.addCell(new Phrase("Porcentaje",
            FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0))));
    pdfTable.addCell(new Phrase("Observaciones",
            FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0))));

    //Evitar Null pointer exception por no tener nodoes en selectedNodes
    //Se utiliza un auxiliar de selectedNodes por que hay posibilidad de que selectedNodes se modifique durante el proceso de generacion del PDF
    if (selectedNodesPDF != null && selectedNodesPDF.length > 0) {

        //Regresar a lo basicoString
        int nns = selectedNodesPDF.length;
        String[] ns = new String[nns];
        for (int x = 0; x < selectedNodesPDF.length; x++) {
            ns[x] = ((NodoMultiClass) selectedNodesPDF[x].getData()).getNumero() + "--"
                    + ((NodoMultiClass) selectedNodes[x].getData()).getNombre() + "--"
                    + ((NodoMultiClass) selectedNodes[x].getData()).getPorcentajeAvance() + "--"
                    + ((NodoMultiClass) selectedNodes[x].getData()).getObservaciones() + " -- ";
        }
        String[] filas = new String[4];
        String[] nstr = new String[3];

        String[] filas2 = new String[4];
        String[] nstr2 = new String[3];

        for (int x = 1; x < ns.length; x++) {
            for (int y = 0; y < ns.length - x; y++) {
                //Obtengo los valores para hacer las comparaciones
                int[] n = new int[3];
                int[] n2 = new int[3];
                filas = ns[y].split("--");
                nstr = filas[0].split("\\.");
                for (int z = 0; z < nstr.length; z++) {
                    if (nstr == null) {
                        n[z] = 0;
                    } else {
                        n[z] = Integer.parseInt(nstr[z]);
                    }
                }
                filas2 = ns[y + 1].split("--");
                nstr2 = filas2[0].split("\\.");
                for (int z = 0; z < nstr2.length; z++) {
                    if (nstr2 == null) {
                        n2[z] = 0;
                    } else {
                        n2[z] = Integer.parseInt(nstr2[z]);
                    }
                }
                //-------------------------------------------------comparacion
                if (n[0] == n2[0]) {
                    if (n[1] == n2[1]) {
                        if (n[2] > n2[2]) {
                            String aux = ns[y];
                            ns[y] = ns[y + 1];
                            ns[y + 1] = aux;
                        }
                    } else {
                        if (n[1] > n2[1]) {
                            String aux = ns[y];
                            ns[y] = ns[y + 1];
                            ns[y + 1] = aux;
                        }
                    }
                } else {
                    if (n[0] > n2[0]) {
                        String aux = ns[y];
                        ns[y] = ns[y + 1];
                        ns[y + 1] = aux;
                    }
                }
                //-------------------------------------------------------------
            }
        }

        String[] auxNum = new String[4];
        for (int x = 0; x < ns.length; x++) {

            filas = ns[x].split("--");
            num = filas[0].split("\\.");

            //Auxiliar para agregar padre de tema/subtema
            int auxMargen = 1;
            //Agregar unidad a la que pertenece el tema/subtema

            String[] auxNum2 = auxNum;
            int tamanoArbol = root.getChildCount();
            //AGREGAR A TEMA
            if (Integer.parseInt(num[0]) > tamanoArbol) {
                auxMargen = Integer.parseInt(num[0]) - tamanoArbol;
            }
            if (num.length >= 2 && auxNum2[0] != null && !auxNum2[0].equals(num[0])) {
                if (!num[1].equals("0")) {
                    while (!num[0].equals(auxNum2[0]) && auxMargen > 0) {
                        System.out.println("XXXXXXIteracion  para encontrar padre XXXXXXX 0" + auxMargen);
                        auxNum2 = (((NodoMultiClass) root.getChildren()
                                .get(Integer.parseInt(num[0]) - auxMargen).getData()).getNumero()).split("\\.");
                        //if(auxNum[0]!=null&&Integer.parseInt(num[0])>Integer.parseInt(auxNum[0])){
                        if (num[0].equals(auxNum2[0])) {

                        } else {
                            auxMargen--;
                        }

                    }
                    System.out.println("***Unidad Padre" + ((NodoMultiClass) root.getChildren()
                            .get(Integer.parseInt(num[0]) - auxMargen).getData()).getNombre());
                    NodoMultiClass auxNodo = ((NodoMultiClass) root.getChildren()
                            .get(Integer.parseInt(num[0]) - auxMargen).getData());
                    //UTIL PARA PONER TEXTO TACHADO
                    //                     Chunk strikethrough = new Chunk("Strikethrough.");
                    //                      strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location
                    //                     document.add(strikethrough);
                    pdfTable.addCell(new Phrase(auxNodo.getNumero() + ".- " + auxNodo.getNombre(), FontFactory
                            .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(new Phrase(auxNodo.getPorcentajeAvance(), FontFactory
                            .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(auxNodo.getObservaciones());

                }
            } else {
                if (auxNum2[0] == null && num.length >= 2) {
                    auxNum2 = (((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[0]) - auxMargen)
                            .getData()).getNumero()).split("\\.");
                    while (!num[0].equals(auxNum2[0]) && auxMargen > 0) {
                        System.out.println("XXXXXXIteracion  para encontrar padre XXXXXXX 0" + auxMargen);
                        auxNum2 = (((NodoMultiClass) root.getChildren()
                                .get(Integer.parseInt(num[0]) - auxMargen).getData()).getNumero()).split("\\.");
                        //if(auxNum[0]!=null&&Integer.parseInt(num[0])>Integer.parseInt(auxNum[0])){
                        if (num[0].equals(auxNum2[0])) {

                        } else {
                            auxMargen--;
                        }
                    }
                    System.out.println("***Unidad Padre" + ((NodoMultiClass) root.getChildren()
                            .get(Integer.parseInt(num[0]) - auxMargen).getData()).getNombre());
                    NodoMultiClass auxNodo = ((NodoMultiClass) root.getChildren()
                            .get(Integer.parseInt(num[0]) - auxMargen).getData());
                    //UTIL PARA PONER TEXTO TACHADO
                    //                     Chunk strikethrough = new Chunk("Strikethrough.");
                    //                      strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location
                    //                     document.add(strikethrough);
                    pdfTable.addCell(new Phrase(auxNodo.getNumero() + ".- " + auxNodo.getNombre(), FontFactory
                            .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(new Phrase(auxNodo.getPorcentajeAvance(), FontFactory
                            .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(auxNodo.getObservaciones());

                }
            }

            //AGREGAR A SUBTEMA
            String[] auxNumeroUnidad = new String[4];
            int auxMargen2 = 1;
            if (num.length == 3 && auxNum[1] != null && !auxNum[1].equals(num[1])) {
                if (!num[2].equals("0")) {
                    while (!num[0].equals(auxNum[0]) && auxMargen >= 0) {
                        NodoMultiClass auxNodoUnidad = ((NodoMultiClass) root.getChildren()
                                .get(Integer.parseInt(num[0]) - auxMargen).getData());
                        auxNumeroUnidad = auxNodoUnidad.getNumero().split("\\.");
                        tamanoArbol = root.getChildren().get(Integer.parseInt(num[0])).getChildCount();
                        if (Integer.parseInt(num[1]) > tamanoArbol) {
                            auxMargen2 = Integer.parseInt(num[1]) - tamanoArbol;
                        }

                        while (auxNumeroUnidad[0].equals(num[0]) && !num[1].equals(auxNum[1])
                                && auxMargen > 0) {
                            System.out.println("XXXXXXIteracion  para encontrar padre XXXXXXX 0" + auxMargen);
                            auxNum = (((NodoMultiClass) root.getChildren()
                                    .get(Integer.parseInt(num[0]) - auxMargen).getChildren()
                                    .get(Integer.parseInt(num[1]) - auxMargen2).getData()).getNumero())
                                            .split("\\.");
                            //if(auxNum[0]!=null&&Integer.parseInt(num[0])>Integer.parseInt(auxNum[0])){
                            if (num[1].equals(auxNum[1])) {

                            } else {
                                auxMargen2--;
                            }

                        }
                        //                            auxNum = (((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[1]) - auxMargen).getData()).getNumero()).split("\\.");
                        if (num[0].equals(auxNum[0])) {
                        } else {
                            auxMargen--;
                        }
                    }

                    System.out.println("*****Unidad Padre(SUBTEMA)"
                            + ((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[0]) - auxMargen)
                                    .getChildren().get(Integer.parseInt(num[1]) - auxMargen2).getData())
                                            .getNombre());
                    NodoMultiClass auxNodo = ((NodoMultiClass) root.getChildren()
                            .get(Integer.parseInt(num[0]) - auxMargen).getChildren()
                            .get(Integer.parseInt(num[1]) - auxMargen2).getData());
                    //UTIL PARA PONER TEXTO TACHADO
                    //                     Chunk strikethrough = new Chunk("Strikethrough.");
                    //                      strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location
                    //                     document.add(strikethrough);
                    pdfTable.addCell(
                            new Phrase("   " + auxNodo.getNumero() + ".- " + auxNodo.getNombre(), FontFactory
                                    .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(new Phrase(auxNodo.getPorcentajeAvance(), FontFactory
                            .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(auxNodo.getObservaciones());

                }
            } else {
                if (auxNum[0] == null && num.length == 3) {
                    auxNum = (((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[0]) - auxMargen)
                            .getData()).getNumero()).split("\\.");
                    while (!num[0].equals(auxNum[0]) && auxMargen > 0) {
                        NodoMultiClass auxNodoUnidad = ((NodoMultiClass) root.getChildren()
                                .get(Integer.parseInt(num[0]) - auxMargen).getData());
                        auxNumeroUnidad = auxNodoUnidad.getNumero().split("\\.");
                        tamanoArbol = root.getChildren().get(Integer.parseInt(num[0])).getChildCount();
                        if (Integer.parseInt(num[1]) > tamanoArbol) {
                            auxMargen2 = Integer.parseInt(num[1]) - tamanoArbol;
                        }
                        while (auxNumeroUnidad[0].equals(num[0]) && !num[1].equals(auxNum[1])
                                && auxMargen > 0) {
                            System.out.println("Iteracion  para encontrar padre XXXXXXX 0" + auxMargen);
                            auxNum = (((NodoMultiClass) root.getChildren()
                                    .get(Integer.parseInt(num[0]) - auxMargen).getChildren()
                                    .get(Integer.parseInt(num[1]) - auxMargen2).getData()).getNumero())
                                            .split("\\.");
                            //if(auxNum[0]!=null&&Integer.parseInt(num[0])>Integer.parseInt(auxNum[0])){
                            if (num[1].equals(auxNum[1])) {

                            } else {
                                auxMargen2--;
                            }
                        }
                        //                            auxNum = (((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[1]) - auxMargen).getData()).getNumero()).split("\\.");
                        if (num[0].equals(auxNum[0])) {
                        } else {
                            auxMargen--;
                        }
                    }

                    System.out.println("***Unidad Padre(SUBTEMA)"
                            + ((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[0]) - auxMargen)
                                    .getChildren().get(Integer.parseInt(num[1]) - auxMargen2).getData())
                                            .getNombre());
                    NodoMultiClass auxNodo = ((NodoMultiClass) root.getChildren()
                            .get(Integer.parseInt(num[0]) - auxMargen).getChildren()
                            .get(Integer.parseInt(num[1]) - auxMargen2).getData());
                    //UTIL PARA PONER TEXTO TACHADO
                    //                     Chunk strikethrough = new Chunk("Strikethrough.");
                    //                      strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location
                    //                     document.add(strikethrough);
                    pdfTable.addCell(
                            new Phrase("   " + auxNodo.getNumero() + ".- " + auxNodo.getNombre(), FontFactory
                                    .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(new Phrase(auxNodo.getPorcentajeAvance(), FontFactory
                            .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(auxNodo.getObservaciones());

                }
            }

            auxNum = num;
            //FIN AGREGAR PADRE DE TEMA/SUBTEMA 
            boolean banpor = true;
            if (num.length == 1) {
                pdfTable.addCell(new Phrase(filas[0] + ".- " + filas[1],
                        FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0))));
                pdfTable.addCell(new Phrase(String.valueOf(dosDecimales(Float.parseFloat(filas[2]))),
                        FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0))));
                banpor = false;
            }
            if (num.length == 2) {
                pdfTable.addCell(new Phrase("   " + filas[0] + ".- " + filas[1]));
            }
            if (num.length == 3) {
                pdfTable.addCell(new Phrase("       " + filas[0] + ".- " + filas[1],
                        FontFactory.getFont(FontFactory.TIMES_ITALIC, 12)));
                pdfTable.addCell(new Phrase(String.valueOf(dosDecimales(Float.parseFloat(filas[2]))),
                        FontFactory.getFont(FontFactory.TIMES_ITALIC, 12)));
                banpor = false;
            }
            if (banpor) {
                pdfTable.addCell(String.valueOf(dosDecimales(Float.parseFloat(filas[2]))));
                pdfTable.addCell(filas[3]);
            } else {
                pdfTable.addCell(filas[3]);
            }
        }

    } else {
        pdfTable.addCell("No hay nada seleccionado");
        pdfTable.addCell("");
        pdfTable.addCell("");
    }

    pdfTable.setHorizontalAlignment(15);
    float[] columnWidths2 = new float[] { 32f, 8f, 14f };
    pdfTable.setWidths(columnWidths2);
    pdf.add(pdfTable);
    //----------------------------------------------------------------------
}

From source file:mx.randalf.digital.ocr.hocrtopdf.HocrToPdf.java

License:Open Source License

public void hocrToPdf(File fImg, File fHtml, File fPdf) throws IOException, DocumentException, Exception {
    URL inputHOCRFile = null;/* w w w. ja  va  2s . co  m*/
    FileOutputStream outputPDFStream = null;
    // The resolution of a PDF file (using iText) is 72pt per inch
    float pointsPerInch = 72.0f;
    Source source = null;
    StartTag pageTag = null;
    Pattern imagePattern = null;
    Matcher imageMatcher = null;
    // Load the image
    Image pageImage = null;
    float dotsPerPointX;
    float dotsPerPointY;
    float pageImagePixelHeight;
    Document pdfDocument = null;
    PdfWriter pdfWriter = null;
    Font defaultFont = null;
    PdfContentByte cb = null;
    Pattern bboxPattern = null;
    Pattern bboxCoordinatePattern = null;
    StartTag ocrLineTag = null;

    try {
        try {
            inputHOCRFile = new URL("file://" + fHtml.getAbsolutePath());
        } catch (MalformedURLException e) {
            throw e;
        }
        try {
            outputPDFStream = new FileOutputStream(fPdf);
        } catch (FileNotFoundException e) {
            throw e;
        }

        // Using the jericho library to parse the HTML file
        source = new Source(inputHOCRFile);

        // Find the tag of class ocr_page in order to load the scanned image
        pageTag = source.findNextStartTag(0, "class", "ocr_page", false);
        imagePattern = Pattern.compile("image\\s+([^;]+)");
        imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title"));
        if (!imageMatcher.find()) {
            throw new Exception("Could not find a tag of class \"ocr_page\", aborting.");
        }

        try {
            pageImage = Image.getInstance(new URL("file://" + fImg.getAbsolutePath()));
        } catch (MalformedURLException e) {
            throw e;
        }
        dotsPerPointX = pageImage.getDpiX() / pointsPerInch;
        dotsPerPointY = pageImage.getDpiY() / pointsPerInch;
        pageImagePixelHeight = pageImage.getHeight();
        pdfDocument = new Document(
                new Rectangle(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY));
        pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream);
        pdfDocument.open();

        // first define a standard font for our text
        defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK);

        // Put the text behind the picture (reverse for debugging)
        cb = pdfWriter.getDirectContentUnder();
        //PdfContentByte cb = pdfWriter.getDirectContent();

        pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);
        pageImage.setAbsolutePosition(0, 0);
        // Put the image in front of the text (reverse for debugging)
        pdfWriter.getDirectContent().addImage(pageImage);
        //pdfWriter.getDirectContentUnder().addImage(pageImage);

        // In order to place text behind the recognised text snippets we are interested in the bbox property      
        bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}");
        // This pattern separates the coordinates of the bbox property
        bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
        // Only tags of the ocr_line class are interesting
        ocrLineTag = source.findNextStartTag(0, "class", "ocr_line", false);
        while (ocrLineTag != null) {
            au.id.jericho.lib.html.Element lineElement = ocrLineTag.getElement();
            Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title"));
            if (bboxMatcher.find()) {
                // We found a tag of the ocr_line class containing a bbox property
                Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group());
                bboxCoordinateMatcher.find();
                int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))),
                        Integer.parseInt((bboxCoordinateMatcher.group(2))),
                        Integer.parseInt((bboxCoordinateMatcher.group(3))),
                        Integer.parseInt((bboxCoordinateMatcher.group(4))) };
                String line = lineElement.getContent().extractText();
                //               float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
                float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;

                // Put the text into the PDF
                cb.beginText();
                // Comment the next line to debug the PDF output (visible Text)
                cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                // TODO: Scale the text width to fit the OCR bbox
                cb.setFontAndSize(defaultFont.getBaseFont(), Math.round(bboxHeightPt));
                cb.moveText((float) (coordinates[0] / dotsPerPointX),
                        (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY));
                cb.showText(line);
                cb.endText();
            }
            ocrLineTag = source.findNextStartTag(ocrLineTag.getEnd(), "class", "ocr_line", false);
        }
    } catch (NumberFormatException e) {
        throw e;
    } catch (MalformedURLException e) {
        throw e;
    } catch (FileNotFoundException e) {
        throw e;
    } catch (BadElementException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } catch (DocumentException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    } finally {
        if (pdfDocument != null) {
            pdfDocument.close();
        }
        if (outputPDFStream != null) {
            outputPDFStream.close();
        }
    }
}

From source file:net.nosleep.superanalyzer.Share.java

License:Open Source License

public static void saveAnalysisPdf(JFrame window, Analysis analysis, JProgressBar progressBar) {

    File pdfFile = askForFile(window, "pdf");
    if (pdfFile == null)
        return;//from  w w w  .j  av  a 2s. c o  m

    Misc.printMemoryInfo("pdfstart");

    DateFormat dateFormat = new SimpleDateFormat().getDateInstance(DateFormat.SHORT);
    String infoString = Misc.getString("CREATED_ON") + " "
            + dateFormat.format(Calendar.getInstance().getTime());

    int viewCount = 15;
    int viewsDone = 0;

    progressBar.setMinimum(0);
    progressBar.setMaximum(viewCount);

    Dimension d = new Dimension(500, 400);

    try {

        String tmpPath = System.getProperty("java.io.tmpdir") + "/image.png";

        // create the pdf document object
        Document document = new Document();

        // create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(pdfFile));

        // we open the document
        document.open();

        Font titleFont = FontFactory.getFont(FontFactory.HELVETICA, 18, Font.NORMAL,
                new Color(0x00, 0x00, 0x00));

        Paragraph p = new Paragraph(Misc.getString("MY_MUSIC_COLLECTION"), titleFont);
        p.setSpacingAfter(4);
        document.add(p);

        Font subtitleFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL,
                new Color(0x88, 0x88, 0x88));

        p = new Paragraph("The Super Analyzer by Nosleep Software", subtitleFont);
        p.setSpacingAfter(-2);
        document.add(p);

        p = new Paragraph(infoString, subtitleFont);
        p.setSpacingAfter(30);
        document.add(p);

        PdfPTable table = new PdfPTable(2);
        table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
        table.setTotalWidth(500f);
        table.setLockedWidth(true);

        Font statNameFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL,
                new Color(0x66, 0x66, 0x66));

        Font statValueFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL,
                new Color(0x00, 0x00, 0x00));

        Vector<StringTriple> statPairs = SummaryView.createStatPairs(analysis);
        Paragraph statParagraph = new Paragraph();

        Font summaryTitleFont = FontFactory.getFont(FontFactory.HELVETICA, 11, Font.BOLD,
                new Color(0x00, 0x00, 0x00));
        Paragraph titleParagraph = new Paragraph(Misc.getString("SUMMARY"), summaryTitleFont);
        statParagraph.add(titleParagraph);

        Paragraph spaceParagraph = new Paragraph("", statNameFont);
        statParagraph.add(spaceParagraph);

        for (int i = 0; i < statPairs.size(); i++) {
            Paragraph statLine = new Paragraph();
            StringTriple triple = statPairs.elementAt(i);
            Phrase namePhrase = new Phrase(triple.Name + ": ", statNameFont);
            Phrase valuePhrase = new Phrase(triple.Value, statValueFont);
            statLine.add(namePhrase);
            statLine.add(valuePhrase);
            statParagraph.add(statLine);
        }
        table.addCell(statParagraph);

        viewsDone++;
        progressBar.setValue(viewsDone);

        GenreView genreView = new GenreView(analysis);
        genreView.saveImage(new File(tmpPath), d);
        genreView = null;

        Image img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        LikesView likesView = new LikesView(analysis);
        likesView.saveImage(new File(tmpPath), d);
        likesView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        YearView yearView = new YearView(analysis);
        yearView.saveImage(new File(tmpPath), d);
        yearView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        RatingView ratingView = new RatingView(analysis);
        ratingView.saveImage(new File(tmpPath), d);
        ratingView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        TimeView timeView = new TimeView(analysis);
        timeView.saveImage(new File(tmpPath), d);
        timeView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        QualityView qualityView = new QualityView(analysis);
        qualityView.saveImage(new File(tmpPath), d);
        qualityView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        PlayCountView playCountView = new PlayCountView(analysis);
        playCountView.saveImage(new File(tmpPath), d);
        playCountView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        MostPlayedAAView mostPlayedAAView = new MostPlayedAAView(analysis);

        mostPlayedAAView.saveImage(new File(tmpPath), d);
        img = Image.getInstance(tmpPath);
        table.addCell(img);

        mostPlayedAAView.saveImageExtra(new File(tmpPath), d);
        img = Image.getInstance(tmpPath);
        table.addCell(img);

        mostPlayedAAView = null;

        viewsDone++;
        progressBar.setValue(viewsDone);

        MostPlayedDGView mostPlayedDGView = new MostPlayedDGView(analysis);

        mostPlayedDGView.saveImage(new File(tmpPath), d);
        img = Image.getInstance(tmpPath);
        table.addCell(img);

        mostPlayedDGView.saveImageExtra(new File(tmpPath), d);
        img = Image.getInstance(tmpPath);
        table.addCell(img);

        mostPlayedDGView = null;

        viewsDone++;
        progressBar.setValue(viewsDone);

        EncodingKindView encodingKindView = new EncodingKindView(analysis);
        encodingKindView.saveImage(new File(tmpPath), d);
        encodingKindView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        GrowthView growthView = new GrowthView(analysis);
        growthView.saveImage(new File(tmpPath), d);
        growthView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        WordView wordView = new WordView(analysis);
        wordView.saveImage(new File(tmpPath), d);
        wordView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        table.addCell("");

        viewsDone++;
        progressBar.setValue(viewsDone);
        Misc.printMemoryInfo("pdfend");

        document.add(table);

        // step 5: we close the document
        document.close();

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:net.nosleep.superanalyzer.Share.java

License:Open Source License

public static void saveListOfAlbumsAsPdf(JFrame window, Analysis analysis, JProgressBar progressBar) {
    File file = askForFile(window, "pdf");
    if (file == null)
        return;/*from w w  w . j  a  va 2s .  c  o m*/

    Hashtable albums = analysis.getHash(Analysis.KIND_ALBUM);

    DecimalFormat timeFormat = new DecimalFormat("0.0");

    StringPair list[] = new StringPair[albums.size()];
    Enumeration keys = albums.keys();
    Integer index = 0;
    String regex = Album.SeparatorRegEx;
    while (keys.hasMoreElements()) {
        String albumartist = (String) keys.nextElement();
        String[] parts = albumartist.split(regex);
        StringPair pair = new StringPair(parts[1], parts[0]);
        list[index] = pair;
        index++;
    }

    Arrays.sort(list, new StringPairComparator());

    int done = 0;
    progressBar.setMinimum(0);
    progressBar.setMaximum(list.length);

    String infoString = NumberFormat.getInstance().format(list.length) + " ";
    if (list.length == 1)
        infoString += Misc.getString("ALBUM") + ", ";
    else
        infoString += Misc.getString("ALBUMS") + ", ";
    DateFormat dateFormat = new SimpleDateFormat().getDateInstance(DateFormat.SHORT);
    infoString += "created on " + dateFormat.format(Calendar.getInstance().getTime());

    try {
        String tmpPath = System.getProperty("java.io.tmpdir") + "/image.png";

        // create the pdf document object
        Document document = new Document();

        // create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(file));

        // we open the document
        document.open();

        Font titleFont = FontFactory.getFont(FontFactory.HELVETICA, 18, Font.NORMAL,
                new Color(0x00, 0x00, 0x00));
        Paragraph p = new Paragraph(Misc.getString("MY_ALBUMS"), titleFont);
        p.setSpacingAfter(4);
        document.add(p);

        Font subtitleFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL,
                new Color(0x88, 0x88, 0x88));
        p = new Paragraph("The Super Analyzer by Nosleep Software", subtitleFont);
        p.setSpacingAfter(-2);
        document.add(p);

        p = new Paragraph(infoString, subtitleFont);
        p.setSpacingAfter(30);
        document.add(p);

        FontSelector albumSelector = new FontSelector();
        Color albumColor = new Color(0x55, 0x55, 0x55);
        albumSelector.addFont(FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, albumColor));
        Font albumAsianFont = FontFactory.getFont("MSung-Light", "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED);
        albumAsianFont.setSize(8);
        albumAsianFont.setColor(albumColor);
        albumSelector.addFont(albumAsianFont);

        FontSelector artistSelector = new FontSelector();
        Color artistColor = new Color(0x77, 0x77, 0x77);
        artistSelector.addFont(FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, artistColor));
        Font artistAsianFont = FontFactory.getFont("MSung-Light", "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED);
        artistAsianFont.setSize(8);
        artistAsianFont.setColor(artistColor);
        artistSelector.addFont(artistAsianFont);

        for (index = 0; index < list.length; index++) {
            p = new Paragraph();
            p.setLeading(9);

            // separate the string into the album and artist parts

            Phrase phrase = albumSelector.process(list[index].Value);
            p.add(phrase);

            phrase = artistSelector.process(" " + Misc.getString("BY") + " " + list[index].Name);
            p.add(phrase);

            document.add(p);

            done++;
            progressBar.setValue(done);
        }

        // step 5: we close the document
        document.close();

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

}

From source file:org.areasy.common.doclet.document.Fonts.java

License:Open Source License

public static Font getFont(int faceType, int style, int size) {
    Font font = null;/*  ww  w .  j  a v a2s .com*/
    String lookup = String.valueOf(faceType);
    String fontFile = fontTable.getProperty(lookup);

    int fontStyle = Font.NORMAL;
    Color color = COLOR_BLACK;

    if ((style & LINK) != 0) {
        fontStyle += Font.UNDERLINE;
        color = COLOR_LINK;
    } else if ((style & UNDERLINE) != 0)
        fontStyle += Font.UNDERLINE;

    if ((style & STRIKETHROUGH) != 0)
        fontStyle += Font.STRIKETHRU;

    if (fontFile != null) {

        File file = new File(DefaultConfiguration.getWorkDir(), fontFile);
        if (file.exists() && file.isFile()) {

            try {
                String encoding = encTable.getProperty(lookup, BaseFont.CP1252);
                BaseFont bfComic = BaseFont.createFont(file.getAbsolutePath(), encoding, BaseFont.EMBEDDED);

                if ((style & AbstractConfiguration.ITALIC) > 0) {
                    if ((style & AbstractConfiguration.BOLD) > 0)
                        fontStyle += Font.BOLDITALIC;
                    else
                        fontStyle += Font.ITALIC;
                } else if ((style & AbstractConfiguration.BOLD) > 0)
                    fontStyle += Font.BOLD;

                if (fontStyle != Font.NORMAL)
                    font = new Font(bfComic, size, fontStyle, color);
                else
                    font = new Font(bfComic, size);

                if (font == null)
                    throw new IllegalArgumentException("Font null: " + fontFile);
            } catch (Exception e) {
                e.printStackTrace();
                throw new IllegalArgumentException("Font unusable");
            }
        } else
            DocletUtility.error("Font file not found: " + fontFile);
    } else {
        // Use predefined font
        String face = "";

        if (faceType == TEXT_FONT) {
            face = FontFactory.HELVETICA;

            if ((style & AbstractConfiguration.ITALIC) > 0) {
                if ((style & AbstractConfiguration.BOLD) > 0)
                    face = FontFactory.HELVETICA_BOLDOBLIQUE;
                else
                    face = FontFactory.HELVETICA_OBLIQUE;
            } else if ((style & AbstractConfiguration.BOLD) > 0)
                face = FontFactory.HELVETICA_BOLD;
        } else {
            face = FontFactory.COURIER;
            if ((style & ITALIC) > 0) {
                if ((style & BOLD) > 0)
                    face = FontFactory.COURIER_BOLDOBLIQUE;
                else
                    face = FontFactory.COURIER_OBLIQUE;
            } else if ((style & BOLD) > 0)
                face = FontFactory.COURIER_BOLD;
        }

        if (fontStyle != Font.NORMAL)
            font = FontFactory.getFont(face, size, fontStyle, color);
        else
            font = FontFactory.getFont(face, size);
    }

    return font;
}

From source file:org.cyberoam.iview.charts.Chart.java

License:Open Source License

/**
 * Function to write a given ChartID to pdf file
 * @param pdfFileName specifies the pdf where chart is written.Please specify full path with the filename.
 * @param reportGroup id specifies the chart to be generated
 * @param startdate specifies start date 
 * @param enddate specifies end date/*from  ww  w.  j  a  va2 s .  c  om*/
 * @param limit specifies number of records per record to be written in report
 */
public static void generatePDFReportGroup(OutputStream out, int reportGroupID, String applianceID,
        String startDate, String endDate, String limit, int[] deviceIDs, HttpServletRequest request,
        LinkedHashMap paramMap) throws Exception {
    float width = 768;
    float height = 1024;
    float rec_hieght = 470;
    Rectangle pagesize = new Rectangle(768, 1024);
    Document document = new Document(pagesize, 30, 30, 30, 30);

    JFreeChart chart = null;
    SqlReader sqlReader = new SqlReader(false);
    //CyberoamLogger.sysLog.debug("pdf:"+pdfFileName);
    CyberoamLogger.sysLog.debug("reportGroupID:" + reportGroupID);
    CyberoamLogger.sysLog.debug("applianceID:" + applianceID);
    CyberoamLogger.sysLog.debug("startDate:" + startDate);
    CyberoamLogger.sysLog.debug("endDate:" + endDate);
    CyberoamLogger.sysLog.debug("limit:" + limit);
    try {
        //PdfWriter writer = PdfWriter.getInstance(document, response!=null ? response.getOutputStream():new FileOutputStream(pdfFileName));
        PdfWriter writer = PdfWriter.getInstance(document, out);
        writer.setPageEvent(new Chart());
        document.addAuthor("iView");
        document.addSubject("iView Report");
        document.open();
        PdfContentByte contentByte = writer.getDirectContent();
        ReportGroupBean reportGroupBean = ReportGroupBean.getRecordbyPrimarykey(reportGroupID);
        ArrayList reportList = reportGroupBean.getReportIdByReportGroupId(reportGroupID);
        ReportBean reportBean;
        ResultSetWrapper rsw = null;

        String seperator = System.getProperty("file.separator");

        //String path=System.getProperty("catalina.home") +seperator+"webapps" +seperator+"ROOT" + seperator + "images" + seperator + "iViewPDF.jpg";
        String path = InitServlet.contextPath + seperator + "images" + seperator + "iViewPDF.jpg";

        Image iViewImage = Image.getInstance(path);
        iViewImage.scaleAbsolute(750, 900);
        //iViewImage.scaleAbsolute(600,820);
        iViewImage.setAbsolutePosition(10, 10);
        document.add(iViewImage);

        document.add(new Paragraph("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"));

        /*
         *   Generating Table on the First Page of Report providing summary of Content 
         */
        PdfPTable frontPageTable = new PdfPTable(2);
        PdfPCell dataCell;
        ReportGroupRelationBean reportGroupRelationBean;
        String reportName = "";

        Color tableHeadBackColor = new Color(150, 174, 190);
        Color tableContentBackColor = new Color(229, 232, 237);
        Color tableBorderColor = new Color(229, 232, 237);

        dataCell = new PdfPCell(new Phrase(new Chunk("Report Profile",
                FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16, Font.PLAIN, new Color(255, 255, 255)))));
        dataCell.setBackgroundColor(tableHeadBackColor);
        dataCell.setBorderColor(tableBorderColor);
        frontPageTable.addCell(dataCell);

        /**
         * Getting dynamic title.
         */
        String title = "";
        if (paramMap != null) {
            title = paramMap.get("title").toString();

            paramMap.remove("title");
        }
        if (request != null)
            title = getFormattedTitle(request, reportGroupBean, true);

        dataCell = new PdfPCell(new Phrase(new Chunk(title,
                FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16, Font.PLAIN, new Color(255, 255, 255)))));
        dataCell.setBackgroundColor(tableHeadBackColor);
        dataCell.setBorderColor(tableBorderColor);
        frontPageTable.addCell(dataCell);

        dataCell = new PdfPCell(new Phrase(new Chunk("Start Date",
                FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0)))));
        dataCell.setBackgroundColor(tableContentBackColor);
        dataCell.setBorderColor(tableBorderColor);
        frontPageTable.addCell(dataCell);

        dataCell = new PdfPCell(new Phrase(startDate));
        dataCell.setBackgroundColor(tableContentBackColor);
        dataCell.setBorderColor(tableBorderColor);
        frontPageTable.addCell(dataCell);

        dataCell = new PdfPCell(new Phrase(new Chunk("End Date",
                FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0)))));
        dataCell.setBackgroundColor(tableContentBackColor);
        dataCell.setBorderColor(tableBorderColor);
        frontPageTable.addCell(dataCell);

        dataCell = new PdfPCell(new Phrase(endDate));
        dataCell.setBackgroundColor(tableContentBackColor);
        dataCell.setBorderColor(tableBorderColor);
        frontPageTable.addCell(dataCell);

        dataCell = new PdfPCell(new Phrase(new Chunk("iView Server Time",
                FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0)))));
        dataCell.setBackgroundColor(tableContentBackColor);
        dataCell.setBorderColor(tableBorderColor);
        frontPageTable.addCell(dataCell);

        java.util.Date currentDate = new java.util.Date();
        dataCell = new PdfPCell(new Phrase(currentDate.toString()));
        dataCell.setBackgroundColor(tableContentBackColor);
        dataCell.setBorderColor(tableBorderColor);
        frontPageTable.addCell(dataCell);

        dataCell = new PdfPCell(new Phrase(new Chunk("Reports",
                FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0)))));
        dataCell.setBackgroundColor(tableContentBackColor);
        dataCell.setBorderColor(tableBorderColor);
        frontPageTable.addCell(dataCell);

        int len = reportList.size();
        for (int k = 0; k < len; k++) {
            reportGroupRelationBean = (ReportGroupRelationBean) reportList.get(k);
            reportName += " " + (k + 1) + ". "
                    + ReportBean.getRecordbyPrimarykey(reportGroupRelationBean.getReportId()).getTitle() + "\n";
        }
        dataCell = new PdfPCell(new Phrase("\n" + reportName + "\n"));
        dataCell.setBackgroundColor(tableContentBackColor);
        dataCell.setBorderColor(tableBorderColor);

        frontPageTable.addCell(dataCell);

        dataCell = new PdfPCell(new Phrase(new Chunk("Device Names (IP Address)",
                FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0)))));
        dataCell.setBackgroundColor(tableContentBackColor);
        dataCell.setBorderColor(tableBorderColor);
        frontPageTable.addCell(dataCell);

        DeviceBean deviceBean = null;
        String deviceNameWithIP = "";
        if (deviceIDs != null) {
            for (int i = 0; i < deviceIDs.length; i++) {
                deviceBean = DeviceBean.getRecordbyPrimarykey(deviceIDs[i]);
                if (deviceBean != null) {
                    deviceNameWithIP += " " + (i + 1) + ". " + deviceBean.getName() + " (" + deviceBean.getIp()
                            + ")\n";
                }
            }
        }
        dataCell = new PdfPCell(new Phrase("\n" + deviceNameWithIP + "\n"));
        dataCell.setBackgroundColor(tableContentBackColor);
        dataCell.setBorderColor(tableBorderColor);
        frontPageTable.addCell(dataCell);

        /*
         * Adding Table to PDF      
         */
        document.add(frontPageTable);

        /*
         * Adding Charts and Table to PDF 
         */
        for (int i = 0; i < reportList.size(); i++) {
            document.newPage();
            reportBean = ReportBean
                    .getRecordbyPrimarykey(((ReportGroupRelationBean) reportList.get(i)).getReportId());
            String query = null;
            if (request == null) {
                query = PrepareQuery.getQuery(reportBean, startDate, endDate, applianceID, null, null, "0",
                        limit, paramMap);
            } else {
                PrepareQuery prepareQuery = new PrepareQuery();
                query = prepareQuery.getQuery(reportBean, request);
            }
            CyberoamLogger.sysLog.debug("PDF:ReportID:" + reportBean.getReportId() + "Query->" + query);

            try {
                rsw = sqlReader.getInstanceResultSetWrapper(query);
            } catch (org.postgresql.util.PSQLException e) {
                if (query.indexOf("5min_ts_20") > -1) {
                    query = query.substring(0, query.indexOf("5min_ts_20")) + "4hr"
                            + query.substring(query.indexOf("5min_ts_20") + 16, query.length());
                    CyberoamLogger.appLog.debug("New query : " + query);
                    rsw = sqlReader.getInstanceResultSetWrapper(query);

                } else {
                    CyberoamLogger.appLog.error("Exeption in AjaxController.java " + e, e);
                }
            } catch (Exception e) {
                CyberoamLogger.appLog.error("Exeption in AjaxController.java " + e, e);
                rsw.close();
            }

            /*
             * PDF Rendering work starts here
             */

            for (int j = 0; j < (int) (rec_hieght / 16) + 1; j++) {
                document.add(new Paragraph("\n"));
            }
            // This fix is to resolve the problems associated with reports which don't have graphs.
            // If there is no graph associated with the report than no need to generate 
            //a chart for it.
            GraphBean graphBean = GraphBean.getRecordbyPrimarykey(reportBean.getReportId());
            //if(graphBean!=null)
            if (reportBean.getReportFormatId() != 2) {
                chart = Chart.getChart(reportBean.getReportId(), rsw, null);
                PdfTemplate pdfTemplate = contentByte.createTemplate(width, height);
                Graphics2D graphics2D = pdfTemplate.createGraphics(width, height);
                Rectangle2D rectangle = new Rectangle2D.Double(100, 85, 540, rec_hieght);
                chart.draw(graphics2D, rectangle);
                graphics2D.dispose();
                contentByte.addTemplate(pdfTemplate, 0, 0);
            } else {
                Paragraph p = new Paragraph(reportBean.getTitle() + "\n\n",
                        FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
                p.setAlignment("center");
                document.add(p);
            }

            // Retrieving PdfPTable
            PdfPTable pdfTable = getPdfPTable(reportBean, rsw);
            rsw.close();

            /*
             * Adding Table to PDF
             */

            document.add(pdfTable);
        }
        CyberoamLogger.appLog.info("*************Finishing Chart****************");
    } catch (Exception e) {
        CyberoamLogger.sysLog.debug("Chart.writeChartToPDF.e" + e.getMessage(), e);
    } finally {
        sqlReader.close();
    }

    document.close();
}