Example usage for com.itextpdf.text Font setStyle

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

Introduction

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

Prototype

public void setStyle(final String style) 

Source Link

Document

Sets the style using a String containing one or more of the following values: normal, bold, italic, oblique, underline, line-through

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;//  w  w  w  .  ja va  2s  .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:biblioteca.reportes.PdfCreator.java

License:Open Source License

/**
 * createPdf es una funcin estatica que funciona como plantilla para generar
 * reportes dinamicos, segn la necesidad del usuario.
 * @param path La direccin del archivo donde se guardar el pdf
 * @param titulo El Ttulo que llevar el pdf
 * @param encabezado Un texto que se mostrar bajo el ttulo
 * @param tabla La tabla de resultados que mostrar el pdf
 *///from   w ww . j a  v  a 2  s . co m
static public void createPdf(String path, String titulo, String encabezado, PdfPTable tabla) {
    Document document = new Document();
    // step 2
    try {
        PdfWriter.getInstance(document, new FileOutputStream(path));
        Font myFontTitle = new Font();
        myFontTitle.setFamily("Arial");
        myFontTitle.setStyle(Font.BOLD);
        myFontTitle.setSize(14);
        Font Univallef = new Font();
        Univallef.setColor(BaseColor.RED);
        Univallef.setFamily("Arial");
        Univallef.setSize(18);
        Image header = Image
                .getInstance(PdfCreator.class.getResource("/biblioteca/gui/resources/minilogo.png"));
        header.setAlignment(Image.ALIGN_CENTER);
        header.scaleToFit(50, 75);
        Paragraph Univalle = new Paragraph("Universidad del Valle", Univallef);
        Univalle.setAlignment(Paragraph.ALIGN_CENTER);
        Paragraph pTitulo = new Paragraph(titulo, myFontTitle);
        pTitulo.setAlignment(Paragraph.ALIGN_CENTER);
        Paragraph biblioteca = new Paragraph("Biblioteca Digital EISC", myFontTitle);
        biblioteca.setAlignment(Paragraph.ALIGN_CENTER);
        Paragraph developers = new Paragraph(
                "Desarrollado por:\n Mara Cristina Bustos \n Alejandro Valds Villada", myFontTitle);
        developers.setAlignment(Paragraph.ALIGN_CENTER);
        Paragraph Fecha = new Paragraph("Fecha y Hora del Reporte: " + fecha, myFontTitle);
        document.open();
        // step 4
        document.add(header);
        document.add(new Paragraph("\r\n"));
        document.add(Univalle);
        document.add(new Paragraph("\r\n"));
        document.add(pTitulo);
        document.add(new Paragraph("\r\n"));
        document.add(biblioteca);
        document.add(new Paragraph("\r\n"));
        document.add(developers);
        document.add(new Paragraph("\r\n"));
        document.add(Fecha);
        document.add(new Paragraph("\r\n"));
        document.add(new Paragraph(encabezado + (tabla.getRows().size() - 1)));
        document.add(new Paragraph("\r\n"));
        document.add(tabla);
        // step 5
        document.close();
    } catch (DocumentException de) {
        System.err.println(de);
    } catch (IOException ioex) {
        System.err.println(ioex);
    }
}

From source file:biblioteca.reportes.PdfCreator.java

License:Open Source License

static public void createArrayListPdf(String path, String titulo, String encabezado,
        ArrayList<PdfPTable> tablas) {
    Document document = new Document();
    ArrayList<String> NombreTablas = new DaoReportesEstadisticas().getNombreTablas();
    //step 2/*from  w  w w  . j av a 2s  .c o  m*/
    try {
        PdfWriter.getInstance(document, new FileOutputStream(path));
        Font myFontTitle = new Font();
        myFontTitle.setFamily("Arial");
        myFontTitle.setStyle(Font.BOLD);
        myFontTitle.setSize(12);
        Font Univallef = new Font();
        Univallef.setColor(BaseColor.RED);
        Univallef.setFamily("Arial");
        Univallef.setSize(18);
        Image header = Image
                .getInstance(PdfCreator.class.getResource("/biblioteca/gui/resources/minilogo.png"));
        header.setAlignment(Image.ALIGN_CENTER);
        header.scaleToFit(50, 75);
        Paragraph Univalle = new Paragraph("Universidad del Valle", Univallef);
        Univalle.setAlignment(Paragraph.ALIGN_CENTER);
        Paragraph pTitulo = new Paragraph(titulo, myFontTitle);
        pTitulo.setAlignment(Paragraph.ALIGN_CENTER);
        Paragraph biblioteca = new Paragraph("Biblioteca Digital EISC", myFontTitle);
        biblioteca.setAlignment(Paragraph.ALIGN_CENTER);
        Paragraph developers = new Paragraph(
                "Desarrollado por:\n Mara Cristina Bustos \n Alejandro Valds Villada", myFontTitle);
        developers.setAlignment(Paragraph.ALIGN_CENTER);
        Paragraph Fecha = new Paragraph("Fecha y Hora de Reporte: " + fecha, myFontTitle);
        document.open();
        // step 4
        document.add(header);
        document.add(new Paragraph("\r\n"));
        document.add(Univalle);
        document.add(new Paragraph("\r\n"));
        document.add(pTitulo);
        document.add(new Paragraph("\r\n"));
        document.add(biblioteca);
        document.add(new Paragraph("\r\n"));
        document.add(developers);
        document.add(new Paragraph("\r\n"));
        document.add(Fecha);
        document.add(new Paragraph("\r\n"));
        for (int i = 0; i < tablas.size(); i++) {
            document.add(new Paragraph(NombreTablas.get(i)));
            document.add(new Paragraph(encabezado + (tablas.get(i).getRows().size() - 1)));
            document.add(new Paragraph("\r\n"));
            document.add(tablas.get(i));
        }
        // step 5
        document.close();
    } catch (DocumentException de) {
        System.err.println(de);
    } catch (IOException ioex) {
        System.err.println(ioex);
    }
}

From source file:biblioteca.reportes.PdfCreator.java

License:Open Source License

static public void createDinamicPdf(String path, String titulo, String encabezado,
        ArrayList<Element> contenido) {
    Document document = new Document();
    //step 2/*from ww w  .ja v  a  2s  . c o  m*/
    try {
        PdfWriter.getInstance(document, new FileOutputStream(path));
        Font myFontTitle = new Font();
        myFontTitle.setFamily("Arial");
        myFontTitle.setStyle(Font.BOLD);
        myFontTitle.setSize(12);
        Font Univallef = new Font();
        Univallef.setColor(BaseColor.RED);
        Univallef.setFamily("Arial");
        Univallef.setSize(18);
        Image header = Image
                .getInstance(PdfCreator.class.getResource("/biblioteca/gui/resources/minilogo.png"));
        header.setAlignment(Image.ALIGN_CENTER);
        header.scaleToFit(50, 75);
        Paragraph Univalle = new Paragraph("Universidad del Valle", Univallef);
        Univalle.setAlignment(Paragraph.ALIGN_CENTER);
        Paragraph pTitulo = new Paragraph(titulo, myFontTitle);
        pTitulo.setAlignment(Paragraph.ALIGN_CENTER);
        Paragraph biblioteca = new Paragraph("Biblioteca Digital EISC", myFontTitle);
        biblioteca.setAlignment(Paragraph.ALIGN_CENTER);
        Paragraph developers = new Paragraph(
                "Desarrollado por:\n Mara Cristina Bustos \n Alejandro Valds Villada", myFontTitle);
        developers.setAlignment(Paragraph.ALIGN_CENTER);
        Paragraph Fecha = new Paragraph("Fecha y Hora de Reporte: " + fecha, myFontTitle);
        //Paragraph Introduccion = new Paragraph("Reporte de usuarios registrados");
        document.open();
        // step 4
        document.add(header);
        document.add(new Paragraph("\r\n"));
        document.add(Univalle);
        document.add(new Paragraph("\r\n"));
        document.add(pTitulo);
        document.add(new Paragraph("\r\n"));
        document.add(biblioteca);
        document.add(new Paragraph("\r\n"));
        document.add(developers);
        document.add(new Paragraph("\r\n"));
        document.add(Fecha);
        document.add(new Paragraph("\r\n"));
        // document.add(Introduccion);
        document.add(new Paragraph("\r\n"));
        for (int i = 0; i < contenido.size(); i++) {
            document.add(contenido.get(i).getClass().equals(new PdfPTable(2).getClass())
                    ? (PdfPTable) contenido.get(i)
                    : contenido.get(i));
        }
        // step 5
        document.close();
    } catch (DocumentException de) {
        System.err.println(de);
    } catch (IOException ioex) {
        System.err.println(ioex);
    }
}

From source file:BusinessLogic.Controller.HandleCertificate.java

public void downloadCertificate(ContractDAO contrDAO, CertificateDAO certificateDAO, UserDAO usDAO,
        HttpServletResponse response, int idUser, int option) throws DocumentException, IOException {
    User user = usDAO.searchByPkID(idUser);
    List<Certificate> certificateObject = certificateDAO.searchUserAproved();
    List<Certificate> certificateReturn = new ArrayList<Certificate>();
    if (certificateObject != null) {
        certificateReturn.clear();/*from  w  ww.  j  a  v a 2s.c o  m*/
        for (int i = 0; i < certificateObject.size(); i++) {
            if (certificateObject.get(i).getFkuserID().getPkID().equals(user.getPkID())) {
                certificateReturn.add(certificateObject.get(i));
            }
        }
    }
    Contract contractObject = contrDAO.getUserContract(new User(user.getPkID()));
    Certificate cert = certificateReturn.get(option);
    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);
    document.open();
    Font fuente = new Font();
    fuente.setStyle(Font.BOLD);
    fuente.setColor(BaseColor.BLACK);
    fuente.setFamily(Font.FontFamily.TIMES_ROMAN.toString());
    fuente.setSize(15);
    Paragraph header = new Paragraph("\n\n\n\n\nEL DEPARTAMENTO DE GESTION HUMANA\n"
            + "DE TALENTO-HUMANO LTDA\n\n\n\n\n" + "CERTIFICA QUE:\n\n\n\n\n", fuente);
    header.setAlignment(Element.ALIGN_CENTER);
    Calendar fecha = new GregorianCalendar();
    int annio = fecha.get(Calendar.YEAR);
    int mes = fecha.get(Calendar.MONTH) + 1;
    int dia = fecha.get(Calendar.DAY_OF_MONTH);
    Paragraph endtext = new Paragraph("\n\nSe expide la presente certificacion a solicitud"
            + " del interesado a la fecha de : " + dia + "/" + mes + "/" + annio
            + "\n\n\nCordialmente\n\n\nEdwin Alexander Bohorquez\nGERENTE GENERAL DE TALENTO-HUMANO LTDA");
    endtext.setAlignment(Element.ALIGN_LEFT);
    String typeCertificate = "";
    if (cert.getType().toLowerCase().equals("laboral")) {
        typeCertificate = "Laboral";
        document.add(header);
        List<String> positionlist = new ArrayList<String>();
        for (Position cargo : contractObject.getPositionSet()) {
            positionlist.add(cargo.getName());
        }
        Paragraph body = new Paragraph(user.getName().toUpperCase() + " " + user.getLastname().toUpperCase()
                + " con cedula de ciudadania No." + user.getIdentifyCard() + ", trabaja en esta empresa"
                + " desde " + contractObject.getStartDate() + ", desempeandose actualmente como "
                + positionlist + " con una asignacion mensual de $" + contractObject.getSalary()
                + ".Su contrato de trabajo es a termino " + contractObject.getType() + ".");
        body.setAlignment(Element.ALIGN_JUSTIFIED_ALL);
        document.add(body);
        document.add(endtext);
    } else if (cert.getType().toLowerCase().equals("nmina")) {
        typeCertificate = "Nomina";
        Paragraph Payroll_header = new Paragraph("DEPARTAMENTO DE CONTABILIDAD\n" + "TALENTO-HUMANO LTDA\n\n"
                + "LIQUIDACION DE NOMINA:\n" + "Nombre del empleado : " + user.getName() + " "
                + user.getLastname() + "\n" + "Cedula : " + user.getIdentifyCard() + "\n\n", fuente);
        Payroll_header.setAlignment(Element.ALIGN_CENTER);
        document.add(Payroll_header);
        double commissions = 10000;
        double extra_hours = 50000;
        double transportation_aid = 63600;
        double totalAccrued = contractObject.getSalary() + commissions + extra_hours + transportation_aid;

        PdfPTable basetable = new PdfPTable(2);
        PdfPCell headertable = new PdfPCell(new Paragraph("Tabla Base", fuente));
        headertable.setColspan(2);
        basetable.addCell(headertable);
        PdfPCell cell1 = new PdfPCell(new Paragraph("Salario Basico : "));
        PdfPCell cell2 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary())));
        PdfPCell cell3 = new PdfPCell(new Paragraph("Comisiones : "));
        PdfPCell cell4 = new PdfPCell(new Paragraph(String.valueOf(commissions)));
        PdfPCell cell5 = new PdfPCell(new Paragraph("Horas Extras : "));
        PdfPCell cell6 = new PdfPCell(new Paragraph(String.valueOf(extra_hours)));
        PdfPCell cell7 = new PdfPCell(new Paragraph("Auxilio de transporte : "));
        PdfPCell cell8 = new PdfPCell(new Paragraph(String.valueOf(transportation_aid)));
        PdfPCell ce9 = new PdfPCell(new Paragraph("Total Devengado : "));
        PdfPCell ce10 = new PdfPCell(new Paragraph(" $ " + String.valueOf(totalAccrued)));
        basetable.setWidthPercentage(100F);
        basetable.setHorizontalAlignment(Element.ALIGN_CENTER);
        basetable.addCell(cell1);
        basetable.addCell(cell2);
        basetable.addCell(cell3);
        basetable.addCell(cell4);
        basetable.addCell(cell5);
        basetable.addCell(cell6);
        basetable.addCell(cell7);
        basetable.addCell(cell8);
        basetable.addCell(ce9);
        basetable.addCell(ce10);
        document.add(basetable);

        PdfPTable tableliquidation = new PdfPTable(2);
        PdfPCell title = new PdfPCell(
                new Paragraph("Liquidacion. Deducciones de nomina(Conceptos a cargo del empleado) ", fuente));
        title.setColspan(2);
        tableliquidation.addCell(title);
        PdfPCell cell9 = new PdfPCell(new Paragraph("Salud (4%) : "));
        PdfPCell cell10 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary() * 0.04)));
        PdfPCell cell11 = new PdfPCell(new Paragraph("Pension (4%) : "));
        PdfPCell cell12 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary() * 0.04)));

        tableliquidation.setWidthPercentage(100F);
        tableliquidation.setHorizontalAlignment(Element.ALIGN_CENTER);
        tableliquidation.addCell(cell9);
        tableliquidation.addCell(cell10);
        tableliquidation.addCell(cell11);
        tableliquidation.addCell(cell12);
        document.add(tableliquidation);

        PdfPTable tablesocialSecurity = new PdfPTable(2);
        PdfPCell title2 = new PdfPCell(new Paragraph("Seguridad Social a cargo del empleador", fuente));
        title2.setColspan(2);
        tablesocialSecurity.addCell(title2);
        PdfPCell cell13 = new PdfPCell(new Paragraph("Salud (8.5%) : "));
        PdfPCell cell14 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary() * 0.085)));
        PdfPCell cell15 = new PdfPCell(new Paragraph("Pension (12%) : "));
        PdfPCell cell16 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary() * 0.12)));
        PdfPCell cell17 = new PdfPCell(new Paragraph("A.R.P : "));
        PdfPCell cell18 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary() * 0.00522)));

        tablesocialSecurity.setWidthPercentage(100F);
        tablesocialSecurity.setHorizontalAlignment(Element.ALIGN_CENTER);
        tablesocialSecurity.addCell(cell13);
        tablesocialSecurity.addCell(cell14);
        tablesocialSecurity.addCell(cell15);
        tablesocialSecurity.addCell(cell16);
        tablesocialSecurity.addCell(cell17);
        tablesocialSecurity.addCell(cell18);
        document.add(tablesocialSecurity);

        PdfPTable social_benefits = new PdfPTable(2);
        PdfPCell title3 = new PdfPCell(new Paragraph("Prestaciones Sociales", fuente));
        title3.setColspan(2);
        social_benefits.addCell(title3);
        PdfPCell cell19 = new PdfPCell(new Paragraph("Prima de servicios : "));
        PdfPCell cell20 = new PdfPCell(new Paragraph(String.valueOf(totalAccrued * 0.0833)));
        PdfPCell cell21 = new PdfPCell(new Paragraph("Cesantias : "));
        PdfPCell cell22 = new PdfPCell(new Paragraph(String.valueOf(totalAccrued * 0.0833)));
        PdfPCell cell23 = new PdfPCell(new Paragraph("Intereses sobre las cesantias : "));
        PdfPCell cell24 = new PdfPCell(new Paragraph(String.valueOf(totalAccrued * 0.0833 * 0.12)));
        PdfPCell cell25 = new PdfPCell(new Paragraph("Vacaciones : "));
        PdfPCell cell26 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary() * 0.0417)));
        social_benefits.setWidthPercentage(100F);
        social_benefits.setHorizontalAlignment(Element.ALIGN_CENTER);
        social_benefits.addCell(cell19);
        social_benefits.addCell(cell20);
        social_benefits.addCell(cell21);
        social_benefits.addCell(cell22);
        social_benefits.addCell(cell23);
        social_benefits.addCell(cell24);
        social_benefits.addCell(cell25);
        social_benefits.addCell(cell26);
        document.add(social_benefits);

        PdfPTable fiscal_contributions = new PdfPTable(2);
        PdfPCell title4 = new PdfPCell(new Paragraph("Aportes Parafiscales", fuente));
        title4.setColspan(2);
        fiscal_contributions.addCell(title4);
        PdfPCell cell27 = new PdfPCell(new Paragraph("Cajas de compensacion familiar (4%) : "));
        PdfPCell cell28 = new PdfPCell(
                new Paragraph(String.valueOf((contractObject.getSalary() + extra_hours + commissions) * 0.04)));
        PdfPCell cell29 = new PdfPCell(new Paragraph("I.CB.F (3%) : "));
        PdfPCell cell30 = new PdfPCell(
                new Paragraph(String.valueOf((contractObject.getSalary() + extra_hours + commissions) * 0.03)));
        PdfPCell cell31 = new PdfPCell(new Paragraph("Sena (2%) : "));
        PdfPCell cell32 = new PdfPCell(
                new Paragraph(String.valueOf((contractObject.getSalary() + extra_hours + commissions) * 0.02)));
        fiscal_contributions.setWidthPercentage(100F);
        fiscal_contributions.setHorizontalAlignment(Element.ALIGN_CENTER);
        fiscal_contributions.addCell(cell27);
        fiscal_contributions.addCell(cell28);
        fiscal_contributions.addCell(cell29);
        fiscal_contributions.addCell(cell30);
        fiscal_contributions.addCell(cell31);
        fiscal_contributions.addCell(cell32);
        document.add(fiscal_contributions);

        PdfPTable totalValue = new PdfPTable(2);
        PdfPCell title5 = new PdfPCell(new Paragraph("Neto a pagar al empleado", fuente));
        title5.setColspan(2);
        totalValue.addCell(title5);
        PdfPCell cell33 = new PdfPCell(new Paragraph(" Total devengado - salud - pension"));
        cell33.setColspan(2);
        PdfPCell cell34 = new PdfPCell(new Paragraph(
                " $ " + String.valueOf(totalAccrued - contractObject.getSalary() * 0.08), fuente));
        cell34.setColspan(2);
        totalValue.setWidthPercentage(100F);
        totalValue.setHorizontalAlignment(Element.ALIGN_CENTER);
        totalValue.addCell(cell33);
        totalValue.addCell(cell34);
        document.add(totalValue);

        document.add(endtext);
    } else if (cert.getType().toLowerCase().equals("salud")) {
        typeCertificate = "Salud";
        document.add(header);
        Paragraph body = new Paragraph(user.getName().toUpperCase() + " " + user.getLastname().toUpperCase()
                + " con cedula de ciudadania No." + user.getIdentifyCard() + ", esta afiliado desde "
                + contractObject.getStartHealthDate() + " a la empresa de salud "
                + contractObject.getHealthEnterprise() + ".");
        body.setAlignment(Element.ALIGN_JUSTIFIED_ALL);
        document.add(body);
        document.add(endtext);
    } else if (cert.getType().toLowerCase().equals("pensin")) {
        typeCertificate = "Pension";
        document.add(header);
        Paragraph body = new Paragraph(user.getName().toUpperCase() + " " + user.getLastname().toUpperCase()
                + " con cedula de ciudadania No." + user.getIdentifyCard()
                + ", esta afiliado a la empresa de pension " + contractObject.getPensionEnterprise()
                + ".La fecha de inicio de pension es " + contractObject.getStartPensionDate() + ".");
        body.setAlignment(Element.ALIGN_JUSTIFIED_ALL);
        document.add(body);
        document.add(endtext);
    }
    document.close();
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentType("application/octet-strem");
    File f = new File("Certificado" + typeCertificate + ".pdf");
    response.setHeader("Content-Disposition", "attachment;filename=" + f.getName());
    response.setContentLength(baos.size());
    System.out.println("Hasta aca crea el pdf bien");
    OutputStream os = response.getOutputStream();
    System.out.println("Ac'a ya deberia haber descargado");
    baos.writeTo(os);
    os.flush();
    os.close();
}

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);/*  w ww  . java2 s. c  o 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:com.athena.chameleon.engine.core.PDFCommonEventHelper.java

License:Apache License

/**
 * //w w  w. j  a  va 2  s  . c  o m
 *  Paragraph ?.(Navigation  ?  title ) 
 *
 * @param title 
 * @param pageNumber 
 * @param depth 
 * @param x1 document left 
 * @param x2 document right 
 * @return Paragraph
 */
public Paragraph getTocParagraph(String title, int pageNumber, int depth, float x1, float x2) {

    Font tocFont = new Font(bfKorean, 10);
    if (depth == 0)
        tocFont.setStyle(Font.BOLD);

    Paragraph p = new Paragraph();
    p.setSpacingAfter(5);

    Chunk tit = new Chunk(title + " ", tocFont);
    tit.setAction(PdfAction.gotoLocalPage(title, false));

    Chunk point = new Chunk(".", tocFont);

    Chunk number = new Chunk(" " + pageNumber, tocFont);
    number.setAction(PdfAction.gotoLocalPage(title, false));

    p.add(tit);

    float width = x2 - x1 - tit.getWidthPoint() - number.getWidthPoint() - (depth * 12);

    if ((x2 - x1) < tit.getWidthPoint())
        width = x2 - x1 - (tit.getWidthPoint() - (x2 - x1)) - number.getWidthPoint() - (depth * 12) - 65;

    float i = point.getWidthPoint();
    while (i < width) {
        p.add(point);
        i += point.getWidthPoint();
    }

    p.add(number);

    return p;
}

From source file:com.biblio.web.rest.PdfResources.java

@RequestMapping(value = "livre", method = RequestMethod.GET)
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, WriterException {
    response.setContentType("application/pdf");
    GenerateQRCode ge = new GenerateQRCode();

    try {/*from  www.  jav a 2s.  com*/

        Document document = new Document();
        String param = request.getParameter("isbn");
        Livre livre = livreRepository.findOneByIsbn(param).get();
        PdfWriter e = PdfWriter.getInstance(document, response.getOutputStream());

        document.open();

        Font font = new Font();

        font.setStyle(Font.BOLD);
        font.setSize(12);

        List list = new List(15);

        //  document.left(12);
        list.add(new ListItem("Titre  :" + livre.getTitre(), font));
        list.add(new ListItem("Categorie  :" + livre.getCategorie().getDescription(), font));
        list.add(new ListItem("Auteurs   :" + livre.getAuteurs(), font));
        list.add(new ListItem("Edition   :" + livre.getEdition(), font));
        list.add(new ListItem("Editeur   :" + livre.getEditeur(), font));
        list.add(new ListItem("Collection   :" + livre.getCollection(), font));
        list.add(new ListItem("Date parution   :" + livre.getDateParution(), font));
        list.add(new ListItem("Isbn   " + livre.getIsbn(), font));
        list.add(new ListItem("Resume   : " + livre.getResume(), font));

        document.add(list);
        document.addTitle(livre.getTitre());
        document.setMargins(100, 20, 0, 0);
        document.addCreationDate();
        System.out.println("TTT v " + document.addTitle(param));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(ge.createQRImage(param, 125), "jpg", baos);
        Image image = Image.getInstance(baos.toByteArray());
        document.add(image);
        document.close();

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

From source file:com.coast.PDFPrinter_iText.java

License:Apache License

/**
 * Prints the document at its actual size. This is the recommended way to print.
 *///from   w w w  .j  a  v  a  2  s  .  com
private static void print(String pFileName, String pPayload) throws IOException, Exception {
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(pFileName));
    // step 3
    document.open();
    // step 4
    String _dateTime = LocalDateTime.now().toString();
    document.addTitle("List of All Customers & their assets as of: " + _dateTime);
    document.addCreationDate();
    document.addSubject("List of All Customers & their assets as of: " + _dateTime);

    Font _font = new Font();
    _font.setColor(BaseColor.BLUE);
    _font.setStyle(Font.BOLD);
    _font.setSize(15);

    Chunk _chunk = new Chunk("List of All Customers & their assets as of: " + _dateTime);
    _chunk.setFont(_font);
    Paragraph _header = new Paragraph();
    _header.add(_chunk);
    document.add(_header);
    document.add(new Paragraph(pPayload));

    // step 5
    document.close();
}

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

License:Open Source License

public void run() {
    // Class Method Instances
    String title;/*from w  ww. j  a v  a 2  s. c o m*/

    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());
        }
    }
}