Example usage for com.itextpdf.text Font Font

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

Introduction

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

Prototype


public Font(final FontFamily family) 

Source Link

Document

Constructs a Font.

Usage

From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java

License:Open Source License

private Phrase processHtmlCodes(String name, Font baseFont, Font symbol) {

    final Font italicFont = new Font(baseFont);
    italicFont.setStyle(Font.FontStyle.ITALIC.getValue());

    final Font normalFont = new Font(baseFont);

    Font usedFont = normalFont;/*from w w  w .  j  av  a 2  s.c  o m*/

    final Phrase phrase = new Phrase();

    if (!StringUtils.isEmpty(name)) {

        for (String[] alphabet : GreekAlphabet.getAlphabet()) {
            name = name.replaceAll(alphabet[0], DELIMETER + alphabet[0] + DELIMETER);
        }
        name = name.replaceAll("<sup>|<SUP>", DELIMETER + "<sup>");
        name = name.replaceAll("</sup>|</SUP>", DELIMETER);
        name = name.replaceAll("<i>|<I>|<em>|<EM>", DELIMETER + "<i>");
        name = name.replaceAll("</i>|</I>|</em>|</EM>", DELIMETER + "</i>");

        final String[] tokens = name.split(DELIMETER);
        for (String token : tokens) {

            String text = token;
            if (text.startsWith("<i>")) {
                usedFont = italicFont;
                text = text.substring(3);
            } else if (text.startsWith("</i>")) {
                usedFont = normalFont;
                text = text.substring(4);
            }

            usedFont.setSize(baseFont.getSize());

            if (text.startsWith("&")) {
                final char replacement = GreekAlphabet.getReplacement(text);
                if (!Character.isWhitespace(replacement)) {
                    phrase.add(SpecialSymbol.get(replacement, symbol));
                } else {
                    phrase.add(new Chunk(text, usedFont));
                }
            } else if (text.startsWith("<sup>")) {

                final Font superScriptFont = new Font(usedFont);
                superScriptFont.setSize(baseFont.getSize() - 1.5f);

                final Chunk superScript = new Chunk(text.substring(5), superScriptFont);
                superScript.setTextRise(4f);
                phrase.add(superScript);

            } else {
                phrase.add(new Chunk(text, usedFont));
            }

        }
    }

    return phrase;
}

From source file:bussiness.ReportHandler.java

private void BuildHeaderPrescription(Document veterinaryPrescription, String clientName, String petName)
        throws DocumentException, IOException {
    BaseFont baseFont = BaseFont.createFont("Cookie.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED);
    Font font = new Font(baseFont);
    font.setStyle(Font.BOLDITALIC);
    font.setSize(35);//from w w w.j  ava 2 s . co  m
    Doctor doctor = SessionManager.getLoggedDoctor();
    Paragraph p1 = new Paragraph("Dr. " + doctor.getName(), font);
    p1.setAlignment(Element.ALIGN_CENTER);
    veterinaryPrescription.add(p1);
    // veterinaryPrescription.add(new Chunk("\n"));

    Font font2 = new Font();
    font2.setSize(20);

    Paragraph p2 = new Paragraph("CEDULA PROFESIONAL  " + doctor.getIdentityCard(), font2);

    p2.setAlignment(Element.ALIGN_CENTER);

    veterinaryPrescription.add(p2);
    veterinaryPrescription.add(new Chunk("\n"));
    Paragraph p3 = new Paragraph("Nombre del cliente: " + clientName, font2);
    veterinaryPrescription.add(p3);
    Paragraph p4 = new Paragraph("Nombre de la mascota: " + petName, font2);
    veterinaryPrescription.add(p4);
}

From source file:classes.utils.crearPDF_Depreciacion.java

public String writePDF(String datos, Scene scene)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {

    javafx.scene.control.TextField projectName = (TextField) scene.lookup(CNodeID.TEXTFIELD_PROJECT_NAME);
    String project = projectName.getText();

    StringTokenizer st = new StringTokenizer(datos, "_");

    principal = st.nextToken();/*from   w ww.  jav  a 2 s . co  m*/
    salvageV = st.nextToken();
    period = st.nextToken();
    tax = st.nextToken();
    periodSalvage = st.nextToken();
    category = st.nextToken();
    data = st.nextToken();

    Document document = new Document(PageSize.LETTER, 80, 80, 50, 50);
    FileOutputStream salida = new FileOutputStream(project + "_depreciation.pdf");
    PdfWriter writer = PdfWriter.getInstance(document, salida);
    writer.setInitialLeading(0);

    Paragraph paragraph = new Paragraph();
    paragraph.setFont(new Font(FontFactory.getFont("Courier", 20, Font.BOLDITALIC, BaseColor.RED)));
    paragraph.add("\n\n\nDEPRECIACION");
    paragraph.setAlignment(Paragraph.ALIGN_CENTER);

    //System.out.println(getClass().getResource("images/logo_report.png"));
    //Image image = Image.getInstance("/home/isaac/IdeaProjects/ProjectEvaluation/src/images/logo_report.png");

    //image.scaleToFit(150, 150);

    Image image1 = Image.getInstance(project + "/" + project + "_DEP_TY.png");

    image1.scaleToFit(300, 300);

    //image.setAlignment(Chunk.ALIGN_RIGHT);
    image1.setAlignment(Chunk.ALIGN_CENTER);

    Paragraph paragraph_2 = new Paragraph();
    paragraph_2.setFont(new Font(FontFactory.getFont("Courier", 12, Font.BOLD, BaseColor.BLUE)));
    paragraph_2.add(
            "\n\n\n\n\n\n\n\n\n\n\nADMINISTRACION Y EVALUACION DE PROYECTOS\n\n SERGIO VALDES TORRES A01365520\n ERIK MARTIN A01365096\nISAAC SECUNDINO A01361162\n IVAN CABRER A01184937");
    paragraph_2.setAlignment(Paragraph.ALIGN_RIGHT);

    Paragraph paragraph_3 = new Paragraph();
    paragraph_3.setFont(new Font(FontFactory.getFont("Courier", 11, Font.BOLD, BaseColor.BLACK)));
    paragraph_3.add("\n " + data);
    paragraph_3.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_5 = new Paragraph();
    paragraph_5.setFont(new Font(FontFactory.getFont("Courier", 6, Font.BOLD, BaseColor.BLUE)));
    paragraph_5.add("\n\nP   DEPRECIATON RATE  ANNUAL DEPRECIATON  CUMMULATIVE DEPRECIATON  VALUE IN LEDGERS ");
    paragraph_5.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_4 = new Paragraph();
    paragraph_4.setFont(new Font(FontFactory.getFont("Courier", 9, Font.BOLD, BaseColor.BLACK)));
    paragraph_4.add("Nombre del Evaluador: \n Principal: " + principal + " \n Salvag Value: " + salvageV
            + " \n Numero de Periodos: " + period + "\n Tax: " + tax + " \n Salvage Period: " + periodSalvage
            + "\n Categoria: " + category);
    paragraph_4.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_6 = new Paragraph();
    paragraph_6.setFont(new Font(FontFactory.getFont("Courier", 15, Font.BOLD, BaseColor.GRAY)));
    paragraph_6.add("\n GRAFICAS\n");
    paragraph_6.setAlignment(Paragraph.ALIGN_CENTER);

    document.open();
    //document.add(image);

    document.add(paragraph);

    document.add(paragraph_4);
    document.add(paragraph_5);
    document.add(paragraph_3);
    document.add(paragraph_6);
    Image image2 = Image.getInstance(project + "/" + project + "_DEP_DR.png");
    Image image3 = Image.getInstance(project + "/" + project + "_DEP_AD.png");
    Image image4 = Image.getInstance(project + "/" + project + "_DEP_ACD.png");
    Image image5 = Image.getInstance(project + "/" + project + "_DEP_LV.png");
    document.add(image2);
    document.add(image3);
    document.add(image4);
    document.add(image5);
    document.add(image1);
    document.add(paragraph_2);
    document.close();
    return null;

}

From source file:classes.utils.createPDF_checkList.java

public String writePDF(Scene scene, String datos)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {

    javafx.scene.control.TextField projectName = (javafx.scene.control.TextField) scene
            .lookup(CNodeID.TEXTFIELD_PROJECT_NAME);
    String project = projectName.getText();
    StringTokenizer st = new StringTokenizer(datos, "*");

    dato1 = st.nextToken();/*from w  ww .j a v a  2s  .c o m*/
    dato2 = st.nextToken();
    dato3 = st.nextToken();
    dato4 = st.nextToken();
    dato5 = st.nextToken();
    dato6 = st.nextToken();
    dato7 = st.nextToken();
    dato8 = st.nextToken();
    dato9 = st.nextToken();
    dato10 = st.nextToken();
    dato11 = st.nextToken();
    dato12 = st.nextToken();
    dato13 = st.nextToken();
    dato14 = st.nextToken();
    dato15 = st.nextToken();
    dato16 = st.nextToken();
    dato17 = st.nextToken();

    Document document = new Document(PageSize.LETTER, 80, 80, 50, 50);
    FileOutputStream salida = new FileOutputStream(project + "_CheckList.pdf");
    PdfWriter writer = PdfWriter.getInstance(document, salida);
    writer.setInitialLeading(0);

    Paragraph paragraph = new Paragraph();
    paragraph.setFont(new Font(FontFactory.getFont("Courier", 20, Font.BOLDITALIC, BaseColor.RED)));
    paragraph.add("\n\n\nCHECK LIST");
    paragraph.setAlignment(Paragraph.ALIGN_CENTER);

    //Image image = Image.getInstance("/home/isaac/IdeaProjects/ProjectEvaluation/src/images/logo_report.png");

    //image.scaleToFit(150, 150);

    //image.setAlignment(Chunk.ALIGN_RIGHT);

    Paragraph paragraph_2 = new Paragraph();
    paragraph_2.setFont(new Font(FontFactory.getFont("Courier", 12, Font.BOLD, BaseColor.BLUE)));
    paragraph_2.add(
            "\n\n\n\n\n\n\nADMINISTRACION Y EVALUACION DE PROYECTOS\n\n SERGIO VALDES TORRES A01365520\n ERIK MARTIN A01365096\nISAAC SECUNDINO A01361162\n IVAN CABRER A01184937");
    paragraph_2.setAlignment(Paragraph.ALIGN_RIGHT);

    Paragraph paragraph_4 = new Paragraph();
    paragraph_4.setFont(new Font(FontFactory.getFont("Courier", 6, Font.BOLD, BaseColor.BLACK)));
    paragraph_4.add("Strategy---Alignment What specific organization strategy does this project align with?"
            + "     " + dato1 + "\n" + "Driver---What business problem does the project solve?" + "     "
            + dato2 + "\n" + "Success Metrics---How will measure success?" + "     " + dato3 + "\n"
            + "Sponsorship---Who is the project sponsor?" + "     " + dato4 + "\n"
            + "Risk---What is the impact of not doing this project?" + "     " + dato5 + "\n"
            + "Risk---What is the project risk to our organization?" + "     " + dato6 + "\n"
            + "Risk---Where does the proposed project fit in our risk profile?" + "     " + dato7 + "\n"
            + "Benefits, value---What is the value of the project organization?" + "     " + dato8 + "\n"
            + "Benefits, value---When will the project shows results?" + "     " + dato9 + "\n"
            + "Objectives---What are the project objectives?" + "     " + dato10 + "\n"
            + "Organization Culture---Is our organization culture right for this type of project?" + "     "
            + dato11 + "\n" + "Resources---Will internal resources be available for this project?" + "     "
            + dato12 + "\n" + "Approach---Will we build or buy?" + "     " + dato13 + "\n"
            + "Schedule---How long will this project take?" + "     " + dato14 + "\n"
            + "Schedule---Is the timeline realistic?" + "     " + dato15 + "\n"
            + "Training/Resources---Will staff training be required?" + "     " + dato16 + "\n"
            + "Finance/Portfolio---What is the estimated cost of the project?" + "     " + dato17 + "\n");
    /*+ "Portfolio---Is this a new initiative or path of an existing initiative?"+"     "+dato18+"\n"
    + "Portfolio---How does this project interact with current projects?"+"     "+dato19+"\n"
    + "Technology---Is the technology available or new?"+"     "+dato20+"");
    */

    paragraph_4.setAlignment(Paragraph.ALIGN_LEFT);

    document.open();
    //document.add(image);

    document.add(paragraph);

    document.add(paragraph_4);

    document.add(paragraph_2);
    document.close();
    return "pdf Creado";

}

From source file:classes.utils.createPDF_NetPresent.java

public String writePDF(Scene scene, String datos)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {

    javafx.scene.control.TextField projectName = (javafx.scene.control.TextField) scene
            .lookup(CNodeID.TEXTFIELD_PROJECT_NAME);
    String project = projectName.getText();
    StringTokenizer st = new StringTokenizer(datos, "_");

    period = st.nextToken();//from  w w  w.  ja  v a2s. c o m
    principal = st.nextToken();
    interestRate = st.nextToken();
    tax = st.nextToken();
    salvageV = st.nextToken();
    periodSalvage = st.nextToken();
    data = st.nextToken();

    Document document = new Document(PageSize.LETTER, 80, 80, 50, 50);
    FileOutputStream salida = new FileOutputStream(project + "_NetPresentValue.pdf");
    PdfWriter writer = PdfWriter.getInstance(document, salida);
    writer.setInitialLeading(0);

    Paragraph paragraph = new Paragraph();
    paragraph.setFont(new Font(FontFactory.getFont("Courier", 20, Font.BOLDITALIC, BaseColor.RED)));
    paragraph.add("\n\n\nNET PRESENT VALUE");
    paragraph.setAlignment(Paragraph.ALIGN_CENTER);

    //Image image = Image.getInstance("/home/isaac/IdeaProjects/ProjectEvaluation/src/images/logo_report.png");

    //image.scaleToFit(150, 150);

    Image image1 = Image.getInstance(project + "/" + project + "_NPV_CCF.png");

    image1.scaleToFit(300, 300);

    //image.setAlignment(Chunk.ALIGN_RIGHT);
    image1.setAlignment(Chunk.ALIGN_CENTER);

    Paragraph paragraph_2 = new Paragraph();
    paragraph_2.setFont(new Font(FontFactory.getFont("Courier", 12, Font.BOLD, BaseColor.BLUE)));
    paragraph_2.add(
            "\n\n\n\n\n\n\n\n\n\n\nADMINISTRACION Y EVALUACION DE PROYECTOS\n\n SERGIO VALDES TORRES A01365520\n ERIK MARTIN A01365096\nISAAC SECUNDINO A01361162\n IVAN CABRER A01184937");
    paragraph_2.setAlignment(Paragraph.ALIGN_RIGHT);

    Paragraph paragraph_3 = new Paragraph();
    paragraph_3.setFont(new Font(FontFactory.getFont("Courier", 11, Font.BOLD, BaseColor.BLACK)));
    paragraph_3.add("\n " + data);
    paragraph_3.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_5 = new Paragraph();
    paragraph_5.setFont(new Font(FontFactory.getFont("Courier", 10, Font.BOLD, BaseColor.BLUE)));
    paragraph_5.add("\n\nP   OUTFLOW   INFLOW   NET CASH FLOW   CUMULATIVE CASH ");
    paragraph_5.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_4 = new Paragraph();
    paragraph_4.setFont(new Font(FontFactory.getFont("Courier", 9, Font.BOLD, BaseColor.BLACK)));
    paragraph_4.add("Nombre del Evaluador: \nPeriods: " + period + "\n Principal: " + principal
            + " \n Interest Rate%: " + interestRate + " \n Tax Rate %: " + tax + "\n Salvage Value: " + salvageV
            + " \n Period SV: " + periodSalvage);
    paragraph_4.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_6 = new Paragraph();
    paragraph_6.setFont(new Font(FontFactory.getFont("Courier", 15, Font.BOLD, BaseColor.GRAY)));
    paragraph_6.add("\n GRAFICAS\n");
    paragraph_6.setAlignment(Paragraph.ALIGN_CENTER);

    document.open();
    //document.add(image);

    document.add(paragraph);

    document.add(paragraph_4);
    document.add(paragraph_5);
    document.add(paragraph_3);
    document.add(paragraph_6);
    document.add(image1);
    Image image2 = Image.getInstance(project + "/" + project + "_NPV_NCF.png");
    document.add(image2);
    document.add(paragraph_2);
    document.close();
    return null;

}

From source file:classes.utils.createPDF_PayBack.java

public String writePDF(Scene scene, String datos)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {

    javafx.scene.control.TextField projectName = (javafx.scene.control.TextField) scene
            .lookup(CNodeID.TEXTFIELD_PROJECT_NAME);
    String project = projectName.getText();

    StringTokenizer st = new StringTokenizer(datos, "_");

    period = st.nextToken();/* www  .  j  a v a 2  s .  co m*/
    principal = st.nextToken();
    interestRate = st.nextToken();
    data = st.nextToken();

    Document document = new Document(PageSize.LETTER, 80, 80, 50, 50);
    FileOutputStream salida = new FileOutputStream(project + "_PayBackPeriod.pdf");
    PdfWriter writer = PdfWriter.getInstance(document, salida);
    writer.setInitialLeading(0);

    Paragraph paragraph = new Paragraph();
    paragraph.setFont(new Font(FontFactory.getFont("Courier", 20, Font.BOLDITALIC, BaseColor.RED)));
    paragraph.add("\n\n\nPAYBACK PERIOD");
    paragraph.setAlignment(Paragraph.ALIGN_CENTER);
    // TODO: Change absolute to relative
    //Image image = Image.getInstance("/home/isaac/IdeaProjects/ProjectEvaluation/src/images/logo_report.png");

    //image.scaleToFit(150, 150);

    Image image1 = Image.getInstance(project + "/" + project + "_PBP_CCF.png");

    image1.scaleToFit(300, 300);

    //image.setAlignment(Chunk.ALIGN_RIGHT);
    image1.setAlignment(Chunk.ALIGN_CENTER);

    Paragraph paragraph_2 = new Paragraph();
    paragraph_2.setFont(new Font(FontFactory.getFont("Courier", 12, Font.BOLD, BaseColor.BLUE)));
    paragraph_2.add(
            "\n\n\n\n\n\n\n\n\n\n\nADMINISTRACION Y EVALUACION DE PROYECTOS\n\n SERGIO VALDES TORRES A01365520\n ERIK MARTIN A01365096\nISAAC SECUNDINO A01361162\n IVAN CABRER A01184937");
    paragraph_2.setAlignment(Paragraph.ALIGN_RIGHT);

    Paragraph paragraph_3 = new Paragraph();
    paragraph_3.setFont(new Font(FontFactory.getFont("Courier", 11, Font.BOLD, BaseColor.BLACK)));
    paragraph_3.add("\n " + data);
    paragraph_3.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_5 = new Paragraph();
    paragraph_5.setFont(new Font(FontFactory.getFont("Courier", 10, Font.BOLD, BaseColor.BLUE)));
    paragraph_5.add("\n\nP   OUTFLOW  INFLOW  CUMMULATIVE CASH... ");
    paragraph_5.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_4 = new Paragraph();
    paragraph_4.setFont(new Font(FontFactory.getFont("Courier", 9, Font.BOLD, BaseColor.BLACK)));
    paragraph_4.add("Nombre del Evaluador: \n Principal: " + principal + " \n Numero de Periodos: " + period
            + "\nInterest Rate %" + interestRate);
    paragraph_4.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_6 = new Paragraph();
    paragraph_6.setFont(new Font(FontFactory.getFont("Courier", 15, Font.BOLD, BaseColor.GRAY)));
    paragraph_6.add("\n GRAFICAS\n");
    paragraph_6.setAlignment(Paragraph.ALIGN_CENTER);

    document.open();
    //document.add(image);

    document.add(paragraph);

    document.add(paragraph_4);
    document.add(paragraph_5);
    document.add(paragraph_3);
    document.add(paragraph_6);
    Image image2 = Image.getInstance(project + "/" + project + "_PBP_NCF.png");
    document.add(image1);
    document.add(image2);
    document.add(paragraph_2);
    document.close();
    return null;

}

From source file:cn.afterturn.easypoi.pdf.styler.PdfExportStylerDefaultImpl.java

License:Apache License

@Override
public Font getFont(ExcelExportEntity entity, String text) {
    try {//from  ww  w. java  2s.  c o m
        //?
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font font = new Font(bfChinese);
        return font;
    } catch (DocumentException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
    Font font = new Font(FontFamily.UNDEFINED);
    return font;
}

From source file:com.dandymadeproductions.ajqvue.io.PDFDataTableDumpThread.java

License:Open Source License

public void run() {
    // Class Method Instances
    String title;/*  w  ww. ja  v  a2 s  . c  om*/

    Font titleFont;
    Font rowHeaderFont;
    Font tableDataFont;
    BaseFont rowHeaderBaseFont;

    PdfPTable pdfTable;
    PdfPCell titleCell;
    PdfPCell rowHeaderCell;
    PdfPCell bodyCell;

    Document pdfDocument;
    PdfWriter pdfWriter;
    ByteArrayOutputStream byteArrayOutputStream;

    int columnCount, rowNumber;
    int[] columnWidths;
    int totalWidth;
    Rectangle pageSize;

    ProgressBar dumpProgressBar;
    HashMap<String, String> summaryListTableNameTypes;
    DataExportProperties pdfDataExportOptions;

    String currentTableFieldName;
    String currentType, currentString;

    // Setup
    columnCount = summaryListTable.getColumnCount();
    rowNumber = summaryListTable.getRowCount();
    columnWidths = new int[columnCount];

    pdfTable = new PdfPTable(columnCount);
    pdfTable.setWidthPercentage(100);
    pdfTable.getDefaultCell().setPaddingBottom(4);
    pdfTable.getDefaultCell().setBorderWidth(1);

    summaryListTableNameTypes = new HashMap<String, String>();
    pdfDataExportOptions = DBTablesPanel.getDataExportProperties();

    titleFont = new Font(pdfDataExportOptions.getFont());
    titleFont.setStyle(Font.BOLD);
    titleFont.setSize((float) pdfDataExportOptions.getTitleFontSize());
    titleFont.setColor(new BaseColor(pdfDataExportOptions.getTitleColor().getRGB()));

    rowHeaderFont = new Font(pdfDataExportOptions.getFont());
    rowHeaderFont.setStyle(Font.BOLD);
    rowHeaderFont.setSize((float) pdfDataExportOptions.getHeaderFontSize());
    rowHeaderFont.setColor(new BaseColor(pdfDataExportOptions.getHeaderColor().getRGB()));
    rowHeaderBaseFont = rowHeaderFont.getCalculatedBaseFont(false);

    tableDataFont = pdfDataExportOptions.getFont();

    // Constructing progress bar.
    dumpProgressBar = new ProgressBar(exportedTable + " Dump");
    dumpProgressBar.setTaskLength(rowNumber);
    dumpProgressBar.pack();
    dumpProgressBar.center();
    dumpProgressBar.setVisible(true);

    // Create a Title if Optioned.
    title = pdfDataExportOptions.getTitle();

    if (!title.equals("")) {
        if (title.equals("EXPORTED TABLE"))
            title = exportedTable;

        titleCell = new PdfPCell(new Phrase(title, titleFont));
        titleCell.setBorder(0);
        titleCell.setPadding(10);
        titleCell.setColspan(summaryListTable.getColumnCount());
        titleCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);

        pdfTable.addCell(titleCell);
        pdfTable.setHeaderRows(2);
    } else
        pdfTable.setHeaderRows(1);

    // Create Row Header.
    for (int i = 0; i < columnCount; i++) {
        currentTableFieldName = summaryListTable.getColumnName(i);
        rowHeaderCell = new PdfPCell(new Phrase(currentTableFieldName, rowHeaderFont));
        rowHeaderCell.setBorderWidth(pdfDataExportOptions.getHeaderBorderSize());
        rowHeaderCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        rowHeaderCell.setBorderColor(new BaseColor(pdfDataExportOptions.getHeaderBorderColor().getRGB()));
        pdfTable.addCell(rowHeaderCell);
        columnWidths[i] = Math.min(50000,
                Math.max(columnWidths[i], rowHeaderBaseFont.getWidth(currentTableFieldName + " ")));
        if (tableColumnTypeNameHashMap != null)
            summaryListTableNameTypes.put(Integer.toString(i),
                    tableColumnTypeNameHashMap.get(currentTableFieldName));
        else
            summaryListTableNameTypes.put(Integer.toString(i), "String");
    }

    // Create the Body of Data.
    int i = 0;
    while ((i < rowNumber) && !dumpProgressBar.isCanceled()) {
        dumpProgressBar.setCurrentValue(i);

        // Collecting rows of data & formatting date & timestamps
        // as needed according to the Export Properties.

        if (summaryListTable.getValueAt(i, 0) != null) {
            for (int j = 0; j < summaryListTable.getColumnCount(); j++) {
                currentString = summaryListTable.getValueAt(i, j) + "";
                currentString = currentString.replaceAll("\n", "");
                currentString = currentString.replaceAll("\r", "");
                currentType = summaryListTableNameTypes.get(Integer.toString(j));

                // Format Date & Timestamp Fields as Needed.

                if ((currentType != null) && (currentType.equals("DATE") || currentType.equals("DATETIME")
                        || currentType.indexOf("TIMESTAMP") != -1)) {
                    if (!currentString.toLowerCase(Locale.ENGLISH).equals("null")) {
                        int firstSpace;
                        String time;

                        // Dates fall through DateTime and Timestamps try
                        // to get the time separated before formatting
                        // the date.

                        if (currentString.indexOf(" ") != -1) {
                            firstSpace = currentString.indexOf(" ");
                            time = currentString.substring(firstSpace);
                            currentString = currentString.substring(0, firstSpace);
                        } else
                            time = "";

                        currentString = Utils.convertViewDateString_To_DBDateString(currentString,
                                DBTablesPanel.getGeneralDBProperties().getViewDateFormat());
                        currentString = Utils.convertDBDateString_To_ViewDateString(currentString,
                                pdfDataExportOptions.getPDFDateFormat()) + time;
                    }
                }
                bodyCell = new PdfPCell(new Phrase(currentString, tableDataFont));
                bodyCell.setPaddingBottom(4);

                if (currentType != null) {
                    // Set Numeric Fields Alignment.
                    if (currentType.indexOf("BIT") != -1 || currentType.indexOf("BOOL") != -1
                            || currentType.indexOf("NUM") != -1 || currentType.indexOf("INT") != -1
                            || currentType.indexOf("FLOAT") != -1 || currentType.indexOf("DOUBLE") != -1
                            || currentType.equals("REAL") || currentType.equals("DECIMAL")
                            || currentType.indexOf("COUNTER") != -1 || currentType.equals("BYTE")
                            || currentType.equals("CURRENCY")) {
                        bodyCell.setHorizontalAlignment(pdfDataExportOptions.getNumberAlignment());
                        bodyCell.setPaddingRight(4);
                    }
                    // Set Date/Time Field Alignment.
                    if (currentType.indexOf("DATE") != -1 || currentType.indexOf("TIME") != -1
                            || currentType.indexOf("YEAR") != -1)
                        bodyCell.setHorizontalAlignment(pdfDataExportOptions.getDateAlignment());
                }

                pdfTable.addCell(bodyCell);
                columnWidths[j] = Math.min(50000,
                        Math.max(columnWidths[j], BASE_FONT.getWidth(currentString + " ")));
            }
        }
        i++;
    }
    dumpProgressBar.dispose();

    // Check to see if any data was in the summary
    // table to even be saved.

    if (pdfTable.size() <= pdfTable.getHeaderRows())
        return;

    // Create a document of the PDF formatted data
    // to be saved to the given output file.

    try {
        // Sizing & Layout
        totalWidth = 0;
        for (int width : columnWidths)
            totalWidth += width;

        if (pdfDataExportOptions.getPageLayout() == PDFExportPreferencesPanel.LAYOUT_PORTRAIT)
            pageSize = PageSize.A4;
        else {
            pageSize = PageSize.A4.rotate();
            pageSize.setRight(pageSize.getRight() * Math.max(1f, totalWidth / 53000f));
            pageSize.setTop(pageSize.getTop() * Math.max(1f, totalWidth / 53000f));
        }

        pdfTable.setWidths(columnWidths);

        // Document
        pdfDocument = new Document(pageSize);
        byteArrayOutputStream = new ByteArrayOutputStream();
        pdfWriter = PdfWriter.getInstance(pdfDocument, byteArrayOutputStream);
        pdfDocument.open();
        pdfTemplate = pdfWriter.getDirectContent().createTemplate(100, 100);
        pdfTemplate.setBoundingBox(new com.itextpdf.text.Rectangle(-20, -20, 100, 100));
        pdfWriter.setPageEvent(this);
        pdfDocument.add(pdfTable);
        pdfDocument.close();

        // Outputting
        WriteDataFile.mainWriteDataString(fileName, byteArrayOutputStream.toByteArray(), false);

    } catch (DocumentException de) {
        if (Ajqvue.getDebug()) {
            System.out.println("Failed to Create Document Needed to Output Data. \n" + de.toString());
        }
    }
}

From source file:com.dandymadeproductions.ajqvue.structures.DataExportProperties.java

License:Open Source License

private void loadPDFFonts() {
    // Method Instances.
    String fileSeparator;/*  w  w  w  . ja  v  a2  s.  c om*/
    String fontPath, fontName;
    String fontsDirectoryName;
    Iterator<String> fontNameIterator;
    File fontsDirectory;
    File[] fontsSubDirectories;
    String[] fontNames;
    TreeSet<String> fonts;

    // Setting up.
    fileSeparator = Utils.getFileSeparator();
    fontsDirectoryName = "fonts" + fileSeparator;
    fonts = new TreeSet<String>();

    // Insure have one default font.

    fontTreeMap.put(PDFExportPreferencesPanel.DEFAULT_FONT, new Font(Font.FontFamily.UNDEFINED));

    // Create the default registered fonts.

    fontNameIterator = FontFactory.getRegisteredFonts().iterator();

    while (fontNameIterator.hasNext()) {
        fontName = fontNameIterator.next();
        fontTreeMap.put(fontName, FontFactory.getFont(fontName));
    }

    // Create embedded fonts from fonts directory.

    fontsDirectory = new File(fontsDirectoryName);

    if (fontsDirectory.exists()) {
        // Handle one level of sub-directories.
        fontsSubDirectories = fontsDirectory.listFiles(new DirectoriesFilter());

        if (fontsSubDirectories != null) {
            for (int i = 0; i < fontsSubDirectories.length; i++) {
                fontNames = fontsSubDirectories[i].list(new FontNameFilter());

                if (fontNames != null)
                    for (int j = 0; j < fontNames.length; j++)
                        fonts.add(fontsSubDirectories[i] + fileSeparator + fontNames[j]);
            }
        }

        // Handle all direct font names in the directory.
        fontNames = fontsDirectory.list(new FontNameFilter());

        if (fontNames != null) {
            for (int i = 0; i < fontNames.length; i++)
                fonts.add(fontsDirectoryName + fontNames[i]);
        }

        // Load the found fonts.
        fontNameIterator = fonts.iterator();

        while (fontNameIterator.hasNext()) {
            fontPath = fontNameIterator.next();
            if (fontPath.indexOf(fileSeparator) != -1)
                fontName = fontPath.substring((fontPath.lastIndexOf(fileSeparator) + 1), fontPath.indexOf("."));
            else
                fontName = fontPath.substring(0, fontPath.indexOf("."));

            // System.out.println(fontName + " " + fontPath);
            try {
                BaseFont currentBaseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H,
                        BaseFont.EMBEDDED);
                fontTreeMap.put(fontName, new Font(currentBaseFont, 12));
            } catch (DocumentException de) {
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:com.dandymadeproductions.myjsqlview.io.PDFDataTableDumpThread.java

License:Open Source License

public void run() {
    // Class Method Instances
    String title;//from   www.j a v a 2s . c om
    PdfPTable pdfTable;
    PdfPCell titleCell, rowHeaderCell, bodyCell;
    Document pdfDocument;
    PdfWriter pdfWriter;
    ByteArrayOutputStream byteArrayOutputStream;

    int columnCount, rowNumber;
    int[] columnWidths;
    int totalWidth;
    Rectangle pageSize;

    MyJSQLView_ProgressBar dumpProgressBar;
    HashMap<String, String> summaryListTableNameTypes;
    String currentTableFieldName;
    String currentType, currentString;

    // Setup
    columnCount = summaryListTable.getColumnCount();
    rowNumber = summaryListTable.getRowCount();
    columnWidths = new int[columnCount];

    pdfTable = new PdfPTable(columnCount);
    pdfTable.setWidthPercentage(100);
    pdfTable.getDefaultCell().setPaddingBottom(4);
    pdfTable.getDefaultCell().setBorderWidth(1);

    summaryListTableNameTypes = new HashMap<String, String>();
    pdfDataExportOptions = DBTablesPanel.getDataExportProperties();

    titleFont = new Font(pdfDataExportOptions.getFont());
    titleFont.setStyle(Font.BOLD);
    titleFont.setSize((float) pdfDataExportOptions.getTitleFontSize());
    titleFont.setColor(new BaseColor(pdfDataExportOptions.getTitleColor().getRGB()));

    rowHeaderFont = new Font(pdfDataExportOptions.getFont());
    rowHeaderFont.setStyle(Font.BOLD);
    rowHeaderFont.setSize((float) pdfDataExportOptions.getHeaderFontSize());
    rowHeaderFont.setColor(new BaseColor(pdfDataExportOptions.getHeaderColor().getRGB()));
    rowHeaderBaseFont = rowHeaderFont.getCalculatedBaseFont(false);

    tableDataFont = pdfDataExportOptions.getFont();

    // Constructing progress bar.
    rowNumber = summaryListTable.getRowCount();
    dumpProgressBar = new MyJSQLView_ProgressBar(exportedTable + " Dump");
    dumpProgressBar.setTaskLength(rowNumber);
    dumpProgressBar.pack();
    dumpProgressBar.center();
    dumpProgressBar.setVisible(true);

    // Create a Title if Optioned.
    title = pdfDataExportOptions.getTitle();

    if (!title.equals("")) {
        if (title.equals("EXPORTED TABLE"))
            title = exportedTable;

        titleCell = new PdfPCell(new Phrase(title, titleFont));
        titleCell.setBorder(0);
        titleCell.setPadding(10);
        titleCell.setColspan(summaryListTable.getColumnCount());
        titleCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);

        pdfTable.addCell(titleCell);
        pdfTable.setHeaderRows(2);
    } else
        pdfTable.setHeaderRows(1);

    // Create Row Header.
    for (int i = 0; i < columnCount; i++) {
        currentTableFieldName = summaryListTable.getColumnName(i);
        rowHeaderCell = new PdfPCell(new Phrase(currentTableFieldName, rowHeaderFont));
        rowHeaderCell.setBorderWidth(pdfDataExportOptions.getHeaderBorderSize());
        rowHeaderCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        rowHeaderCell.setBorderColor(new BaseColor(pdfDataExportOptions.getHeaderBorderColor().getRGB()));
        pdfTable.addCell(rowHeaderCell);
        columnWidths[i] = Math.min(50000,
                Math.max(columnWidths[i], rowHeaderBaseFont.getWidth(currentTableFieldName + " ")));
        if (tableColumnTypeHashMap != null)
            summaryListTableNameTypes.put(Integer.toString(i),
                    tableColumnTypeHashMap.get(currentTableFieldName));
        else
            summaryListTableNameTypes.put(Integer.toString(i), "String");
    }

    // Create the Body of Data.
    int i = 0;
    while ((i < rowNumber) && !dumpProgressBar.isCanceled()) {
        dumpProgressBar.setCurrentValue(i);

        // Collecting rows of data & formatting date & timestamps
        // as needed according to the Export Properties.

        if (summaryListTable.getValueAt(i, 0) != null) {
            for (int j = 0; j < summaryListTable.getColumnCount(); j++) {
                currentString = summaryListTable.getValueAt(i, j) + "";
                currentString = currentString.replaceAll("\n", "");
                currentString = currentString.replaceAll("\r", "");
                currentType = summaryListTableNameTypes.get(Integer.toString(j));

                // Format Date & Timestamp Fields as Needed.

                if ((currentType != null) && (currentType.equals("DATE") || currentType.equals("DATETIME")
                        || currentType.indexOf("TIMESTAMP") != -1)) {
                    if (!currentString.toLowerCase().equals("null")) {
                        int firstSpace;
                        String time;

                        // Dates fall through DateTime and Timestamps try
                        // to get the time separated before formatting
                        // the date.

                        if (currentString.indexOf(" ") != -1) {
                            firstSpace = currentString.indexOf(" ");
                            time = currentString.substring(firstSpace);
                            currentString = currentString.substring(0, firstSpace);
                        } else
                            time = "";

                        currentString = MyJSQLView_Utils.convertViewDateString_To_DBDateString(currentString,
                                DBTablesPanel.getGeneralDBProperties().getViewDateFormat());
                        currentString = MyJSQLView_Utils.convertDBDateString_To_ViewDateString(currentString,
                                pdfDataExportOptions.getPDFDateFormat()) + time;
                    }
                }
                bodyCell = new PdfPCell(new Phrase(currentString, tableDataFont));
                bodyCell.setPaddingBottom(4);

                if (currentType != null) {
                    // Set Numeric Fields Alignment.
                    if (currentType.indexOf("BIT") != -1 || currentType.indexOf("BOOL") != -1
                            || currentType.indexOf("NUM") != -1 || currentType.indexOf("INT") != -1
                            || currentType.indexOf("FLOAT") != -1 || currentType.indexOf("DOUBLE") != -1
                            || currentType.equals("REAL") || currentType.equals("DECIMAL")
                            || currentType.indexOf("COUNTER") != -1 || currentType.equals("BYTE")
                            || currentType.equals("CURRENCY")) {
                        bodyCell.setHorizontalAlignment(pdfDataExportOptions.getNumberAlignment());
                        bodyCell.setPaddingRight(4);
                    }
                    // Set Date/Time Field Alignment.
                    if (currentType.indexOf("DATE") != -1 || currentType.indexOf("TIME") != -1
                            || currentType.indexOf("YEAR") != -1)
                        bodyCell.setHorizontalAlignment(pdfDataExportOptions.getDateAlignment());
                }

                pdfTable.addCell(bodyCell);
                columnWidths[j] = Math.min(50000,
                        Math.max(columnWidths[j], BASE_FONT.getWidth(currentString + " ")));
            }
        }
        i++;
    }
    dumpProgressBar.dispose();

    // Check to see if any data was in the summary
    // table to even be saved.

    if (pdfTable.size() <= pdfTable.getHeaderRows())
        return;

    // Create a document of the PDF formatted data
    // to be saved to the given output file.

    try {
        // Sizing & Layout
        totalWidth = 0;
        for (int width : columnWidths)
            totalWidth += width;

        if (pdfDataExportOptions.getPageLayout() == PDFExportPreferencesPanel.LAYOUT_PORTRAIT)
            pageSize = PageSize.A4;
        else {
            pageSize = PageSize.A4.rotate();
            pageSize.setRight(pageSize.getRight() * Math.max(1f, totalWidth / 53000f));
            pageSize.setTop(pageSize.getTop() * Math.max(1f, totalWidth / 53000f));
        }

        pdfTable.setWidths(columnWidths);

        // Document
        pdfDocument = new Document(pageSize);
        byteArrayOutputStream = new ByteArrayOutputStream();
        pdfWriter = PdfWriter.getInstance(pdfDocument, byteArrayOutputStream);
        pdfDocument.open();
        pdfTemplate = pdfWriter.getDirectContent().createTemplate(100, 100);
        pdfTemplate.setBoundingBox(new com.itextpdf.text.Rectangle(-20, -20, 100, 100));
        pdfWriter.setPageEvent(this);
        pdfDocument.add(pdfTable);
        pdfDocument.close();

        // Outputting
        WriteDataFile.mainWriteDataString(fileName, byteArrayOutputStream.toByteArray(), false);

    } catch (DocumentException de) {
        if (MyJSQLView.getDebug()) {
            System.out.println("Failed to Create Document Needed to Output Data. \n" + de.toString());
        }
    }
}