Example usage for com.itextpdf.text.pdf BaseFont TIMES_ROMAN

List of usage examples for com.itextpdf.text.pdf BaseFont TIMES_ROMAN

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf BaseFont TIMES_ROMAN.

Prototype

String TIMES_ROMAN

To view the source code for com.itextpdf.text.pdf BaseFont TIMES_ROMAN.

Click Source Link

Document

This is a possible value of a base 14 type 1 font

Usage

From source file:com.innoviu.signature.Signature.java

public static void main(String[] args) {
    boolean isEncrypted = false;
    boolean isFailed = false;
    try {/*w w  w . j  a v a2  s  .  c om*/
        if (args.length < 2) {
            throw new FileNotFoundException();
        }
        PdfReader reader = new PdfReader(args[0]);
        isEncrypted = reader.isEncrypted();
        String suffix = ".pdf";
        if (isEncrypted) {
            System.out.println("Encrypted");
            String[] cmd = { "pdftk", args[0], "output", args[0] + ".pdftk.pdf" };
            try {
                Process proc = Runtime.getRuntime().exec(cmd);
                proc.waitFor();
            } catch (Exception e) {
                System.out.println("Exception is:" + e);
            }
            reader = new PdfReader(args[0] + ".pdftk.pdf");
            suffix = ".dec.pdf";
        }
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(args[0] + suffix));
        PdfContentByte over = stamper.getOverContent(1);
        String type = args[2];
        int xpos = 0;
        //int xpos = (type == "in") ? 120 : 10;
        if ("in".equals(type)) {
            xpos = 0;
        } else {
            xpos = 120;
        }
        over.setColorFill(BaseColor.WHITE);
        over.rectangle(xpos + 10, 8, 120, 8);
        over.fill();
        over.beginText();
        BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
        over.setFontAndSize(bf_times, 6);
        over.setColorFill(BaseColor.BLACK);
        over.showTextAligned(PdfContentByte.ALIGN_RIGHT, args[1], 120 + xpos, 10, 0);
        over.endText();
        stamper.close();
        if (isEncrypted) {
            File file = new File(args[0] + ".pdftk.pdf");
            file.delete();
        }
    } catch (FileNotFoundException e) {
        isFailed = true;
        e.printStackTrace();
    } catch (DocumentException e) {
        isFailed = true;
        e.printStackTrace();
    } catch (IOException e) {
        isFailed = true;
        e.printStackTrace();
    } finally {
        if (isEncrypted) {
            maintain(args[0]);
        } else if (isFailed) {
            fail(args[0]);
        } else {

        }
    }
}

From source file:Controller.app.ConsultaController.java

private File createPDF(TblServicioFactura factura) throws IOException {
    String data = factura.getTesPagoResponse();
    JSONObject obj = new JSONObject(data);
    JSONArray content = obj.getJSONArray("lineaFactura");
    String temp = "";
    File _file = null;//w  w  w  .  ja  v  a 2s  .c o m
    Document doc = null;
    OutputStream file = null;
    int page = 0;
    try {
        _file = File.createTempFile("temp_file", ".pdf");
        TblServicioServicio servicio = servicios.search(factura.getTesCodigoSintesisBi().toString());
        file = new FileOutputStream(_file);
        doc = new Document(PageSize.LETTER);
        doc.setMargins(servicio.getMarginLeft().floatValue(), servicio.getMarginRight().floatValue(),
                servicio.getMarginTop().floatValue(), servicio.getMarginBottom().floatValue());
        PdfWriter.getInstance(doc, file);
        doc.open();
        //            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        ClassLoader classloader = getClass().getClassLoader();
        URL url = classloader.getResource("cour.ttf");
        BaseFont base = null;
        if (url == null) {
            base = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } else {
            String path = url.getPath();
            if ("/".equals(path.substring(0, 1))) {
                path = path.substring(1);
            }
            Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, path);
            base = BaseFont.createFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }
        Font f = new Font(base, servicio.getFontSize(), Font.NORMAL, BaseColor.BLACK);
        String qr = "";
        float line = 0;
        for (Object item : content) {
            Paragraph paragraph = new Paragraph(item.toString(), f);
            if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")) {
                if (item.toString().contains("P X#X&$#&K##")) {
                    paragraph = new Paragraph(" ", f);
                    doc.add(paragraph);
                    doc.add(paragraph);
                    paragraph = new Paragraph(item.toString(), f);
                }
            }
            if (item.toString().contains("<b>")) {
                Font bold = new Font(base, 7.0f, Font.BOLD, BaseColor.BLACK);
                paragraph = new Paragraph(item.toString().replace("<b>", ""), bold);
            }
            if (item.toString().contains("<QR>") || item.toString().contains("<QR_ENT_G>")) {
                qr = item.toString().replaceAll("<QR>", "");
                qr = item.toString().replaceAll("<QR_ENT_G>", "");
                Image image = QR.create(qr);
                image.scaleAbsolute(servicio.getQrScale().floatValue(), servicio.getQrScale().floatValue());
                if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")
                        || servicio.getTesDetalleVc().trim().equals("PAGO TELECEL")
                        || servicio.getTesDetalleVc().trim().equals("PAGO NUEVATEL")
                        || servicio.getTesDetalleVc().trim().equals("PAGO TIGOSTAR (MULTIVISION)")) {
                    float y = (doc.getPageSize().getHeight() - (paragraph.getLeading() * (line + 1)));
                    float x = 0;
                    if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")) {
                        image.setAlignment(Image.ALIGN_RIGHT);
                        x = doc.getPageSize().getWidth() - (110 - servicio.getMarginLeft().floatValue());
                    }
                    if (servicio.getTesDetalleVc().trim().equals("PAGO TELECEL")) {
                        image.setAlignment(Image.ALIGN_LEFT);
                        x = 30;
                        y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading() * 2));
                    }
                    if (servicio.getTesDetalleVc().trim().equals("PAGO NUEVATEL")) {
                        image.setAlignment(Image.ALIGN_LEFT);
                        x = doc.getPageSize().getWidth() - (120 - servicio.getMarginLeft().floatValue());
                        y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading()));
                    }
                    if (servicio.getTesDetalleVc().trim().equals("PAGO TIGOSTAR (MULTIVISION)")) {
                        image.setAlignment(Image.ALIGN_LEFT);
                        x = doc.getPageSize().getWidth() - (120 - servicio.getMarginLeft().floatValue());
                        y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading()));
                    }
                    image.setAbsolutePosition(x, y);
                }
                doc.add(image);
            }
            if (servicio.getDelimitador().equals(item.toString().trim())) {
                line = 0;
                page++;
                doc.newPage();
            } else {
                line += 1f;
                if (!(item.toString().contains("<QR>") || item.toString().contains("<QR_ENT_G>"))) {
                    doc.add(paragraph);
                }
            }
            temp += item.toString();
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, null, ex);
    } catch (DocumentException | IOException ex) {
        Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, null, ex);
    }
    doc.close();
    file.close();
    return _file;
}

From source file:de.jost_net.JVerein.gui.control.FormularfeldControl.java

License:Open Source License

public SelectInput getFont() throws RemoteException {
    if (font != null) {
        return font;
    }//from  www  . j a va  2s . c o m
    ArrayList<String> fonts = new ArrayList<String>();
    fonts.add("FreeSans");
    fonts.add("FreeSans-Bold");
    fonts.add("FreeSans-BoldOblique");
    fonts.add("FreeSans-Oblique");
    fonts.add(BaseFont.HELVETICA);
    fonts.add(BaseFont.HELVETICA_BOLD);
    fonts.add(BaseFont.HELVETICA_BOLDOBLIQUE);
    fonts.add(BaseFont.HELVETICA_OBLIQUE);
    fonts.add(BaseFont.TIMES_ROMAN);
    fonts.add(BaseFont.TIMES_BOLD);
    fonts.add(BaseFont.TIMES_ITALIC);
    fonts.add(BaseFont.TIMES_BOLDITALIC);
    fonts.add(BaseFont.COURIER);
    fonts.add(BaseFont.COURIER_BOLD);
    fonts.add(BaseFont.COURIER_OBLIQUE);
    fonts.add(BaseFont.COURIER_BOLDOBLIQUE);
    font = new SelectInput(fonts, getFormularfeld().getFont());
    return font;
}

From source file:dk.dma.epd.common.util.FALPDFGenerator.java

License:Apache License

public void generateFal1Form(FALForm1 fal1form, String filename) {

    try {//  w  w w  . j  av a 2  s .c o m

        PdfReader pdfReader = new PdfReader("FALForm1.pdf");

        FileOutputStream fileWriteStream = new FileOutputStream(filename);

        PdfStamper pdfStamper = new PdfStamper(pdfReader, fileWriteStream);

        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {

            PdfContentByte content = pdfStamper.getUnderContent(i);

            // Text over the existing page
            BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.EMBEDDED);
            content.beginText();
            content.setFontAndSize(bf, 8);

            int xFirstColum = 68;
            int xSecondColum = 314;

            int startYFirstColumn = 659;

            int startYSecondColumn = 659;

            // Arrival Depature
            if (fal1form.isArrival()) {
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, "X", 316, 690, 0);
            } else {
                // Departure
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, "X", 380, 690, 0);
            }

            // Name and Type of ship
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNameAndTypeOfShip(), xFirstColum,
                    startYFirstColumn, 0);

            // IMO Number
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getImoNumber(), xSecondColum,
                    startYSecondColumn, 0);

            // Call Sign
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getCallSign(), xFirstColum,
                    startYFirstColumn - 30, 0);

            // Voyage Number
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getVoyageNumber(), xSecondColum,
                    startYSecondColumn - 30, 0);

            // Port of Arrival/depature
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getPortOfArrivalDeapture(), xFirstColum,
                    startYFirstColumn - 60, 0);

            // Date and time of arrival/depature
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getDateAndTimeOfArrivalDepature(),
                    xSecondColum, startYFirstColumn - 60, 0);

            // Flag State of ship
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getFlagStateOfShip(), xFirstColum,
                    startYFirstColumn - 90, 0);

            // Name of Master
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNameOfMaster(), xFirstColum + 135,
                    startYFirstColumn - 90, 0);

            // Last port of call/next port of all
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getLastPortOfCall(), xSecondColum,
                    startYFirstColumn - 90, 0);

            // Certificate of registry
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getCertificateOfRegistry(), xFirstColum,
                    startYFirstColumn - 120, 0);

            String nameAndContact = fal1form.getNameAndContactDetalsOfShipsAgent();

            addMultiLine(nameAndContact, startYFirstColumn, xSecondColum, content, 54, 120);

            // Gross Tonnage
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getGrossTonnage(), xFirstColum,
                    startYFirstColumn - 150, 0);

            // Net Tonnage
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNetTonnage(), xFirstColum + 135,
                    startYFirstColumn - 150, 0);

            // Position of the ship in the port
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getPositionOfTheShip(), xFirstColum,
                    startYFirstColumn - 180, 0);

            // Brief particulars of voyage
            String briefVoyageParticulars = fal1form.getBriefParticulars();

            addMultiLine(briefVoyageParticulars, startYFirstColumn, xFirstColum, content, 140, 210);

            // Brief particulars of cargo
            String briefCargoParticulars = fal1form.getBriefDescriptionOfCargo();

            addMultiLine(briefCargoParticulars, startYFirstColumn, xFirstColum, content, 140, 257);

            // Number of Crew
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNumberOfCrew(), xFirstColum,
                    startYFirstColumn - 305, 0);

            // Number of Passengers
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNumberOfPassengers(),
                    xFirstColum + 130, startYFirstColumn - 305, 0);

            // Remarks
            String remarks = fal1form.getRemarks();
            addMultiLine(remarks, startYFirstColumn, xSecondColum, content, 54, 305);

            // Ship waste requirements
            String wasteRequirements = fal1form.getShipWasteRequirements();
            addMultiLine(wasteRequirements, startYFirstColumn, xSecondColum, content, 54, 405);

            content.endText();
        }

        pdfStamper.close();
        fileWriteStream.close();
        fileWriteStream.flush();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

}

From source file:Model.MyFontSelector.java

License:Open Source License

/**
 * Inits the BaseFonts of External Fonts and gets of the internals
 * Faz a inicializao das BaseFonts das fontes externas e recupera das
 * fontes internas./*from   ww w .  j  av  a 2 s . com*/
 */
private void initBaseFonts() {
    try {
        ArrayList<BaseFont> baseFontList = new ArrayList<>();
        ArrayList<Font> fontList = new ArrayList<>();

        /**
         * Gets Internals BaseFonts
         * Recupera as BaseFonts das fontes internas
         */
        fontList.add(FontFactory.getFont(BaseFont.TIMES_ROMAN));
        fontList.add(FontFactory.getFont(BaseFont.COURIER));
        fontList.add(FontFactory.getFont(BaseFont.SYMBOL));

        for (Font f : fontList) {
            baseFontList.add(f.getBaseFont());
        }

        /**
         * Gets external chinese traditional BaseFonts
         * Recupera as BaseFonts da fonte externa do Chins tradicional
         */

        baseFontList.add(BaseFont.createFont("MHei-Medium", "UniCNS-UCS2-H", BaseFont.EMBEDDED));
        baseFontList.add(BaseFont.createFont("MSung-Light", "UniCNS-UCS2-H", BaseFont.EMBEDDED));

        /**
         * Gets external chinese simplified BaseFonts
         * Recupera o BaseFont da fonte externa do Chins simplificado
         */
        baseFontList.add(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED));

        initFonts(baseFontList);
    } catch (DocumentException | IOException ex) {
        System.out.println("Error - BaseFont generation");
    }
}

From source file:pdf.alterLetter.java

public static void main(String args[]) {
    try {/*from   www.ja  va  2 s  . c  o m*/
        PdfReader pdfReader;
        pdfReader = new PdfReader("C:\\Users\\asus\\Desktop\\web\\Appointment letter.pdf");
        //pdfReader = new PdfReader("C:\\Users\\asus\\Desktop\\TFMsystem\\Appointment letter.pdf");   

        //Create PdfStamper instance.
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(
                "C:\\Users\\asus\\Desktop\\TFMsystem\\web\\Modified appointment letter.pdf"));

        //new FileOutputStream("C:\\Users\\asus\\Desktop\\TFMsystem\\Modified appointment letter.pdf"));

        //Create BaseFont instance.
        BaseFont baseFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1257, BaseFont.NOT_EMBEDDED);

        //Get the number of pages in pdf.
        int pages = pdfReader.getNumberOfPages();

        //Iterate the pdf through pages.
        for (int i = 1; i <= pages; i++) {
            //Contain the pdf data.
            PdfContentByte pageContentByte = pdfStamper.getOverContent(i);

            pageContentByte.beginText();
            //Set text font and size.
            pageContentByte.setFontAndSize(baseFont, 12);

            //Write text
            pageContentByte.setTextMatrix(120, 706);
            pageContentByte.showText("[no rujukan(enter by admin/opai)]");

            pageContentByte.setTextMatrix(500, 706);
            pageContentByte.showText("[current date]");
            //address
            pageContentByte.setTextMatrix(46, 641);
            pageContentByte.showText("[name]");
            pageContentByte.setTextMatrix(46, 629);
            pageContentByte.showText("[position]");
            pageContentByte.setTextMatrix(46, 617);
            pageContentByte.showText("[department]");

            pageContentByte.setTextMatrix(155, 493);
            pageContentByte.showText("[status(penyelaras/ahli),taskforce name]");

            pageContentByte.setTextMatrix(178, 433);
            pageContentByte.showText("[start date]");

            pageContentByte.setTextMatrix(290, 433);
            pageContentByte.showText("[end date] .");

            pageContentByte.setTextMatrix(46, 248);
            pageContentByte.showText("[name]");
            pageContentByte.setTextMatrix(46, 236);
            pageContentByte.showText("[post]");
            pageContentByte.setTextMatrix(46, 224);
            pageContentByte.showText("[faculty]");
            pageContentByte.setTextMatrix(46, 212);
            pageContentByte.showText("[email]");

            pageContentByte.endText();
        }

        //Close the pdfStamper.
        pdfStamper.close();

        System.out.println("PDF modified successfully.");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:pdf.letter.java

public boolean AlterLetter(String rujukan, String name, String position, String department, String gStatus,
        String sDate, String eDate, String taskName, String postHolderName, String postHolderEmail,
        String postName) {/*from   ww  w. j a v  a 2 s  .c o m*/
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Date today = Calendar.getInstance().getTime();
    String currDate = df.format(today);
    try {
        PdfReader pdfReader;
        pdfReader = new PdfReader("C:\\Users\\on\\Desktop\\AD\\TFMsystem\\web\\Appointment letter.pdf");
        //C:\\Users\\on\\Desktop\\AD\\TFMsystem\\web\\Appointment letter.pdf

        //Create PdfStamper instance.
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(
                "C:\\Users\\on\\Desktop\\AD\\TFMsystem\\web\\Modified appointment letter.pdf"));
        //C:\\Users\\on\\Desktop\\AD\\TFMsystem\\web\\Modified Appointment letter.pdf

        //Create BaseFont instance.
        BaseFont baseFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1257, BaseFont.NOT_EMBEDDED);

        //Get the number of pages in pdf.
        int pages = pdfReader.getNumberOfPages();

        //Iterate the pdf through pages.
        for (int i = 1; i <= pages; i++) {
            //Contain the pdf data.
            PdfContentByte pageContentByte = pdfStamper.getOverContent(i);

            pageContentByte.beginText();
            //Set text font and size.
            pageContentByte.setFontAndSize(baseFont, 11);

            //Write text
            pageContentByte.setTextMatrix(120, 706);
            pageContentByte.showText(rujukan);

            pageContentByte.setTextMatrix(500, 706);
            pageContentByte.showText(currDate);
            //address
            pageContentByte.setTextMatrix(46, 641);
            pageContentByte.showText(name);
            pageContentByte.setTextMatrix(46, 629);
            pageContentByte.showText(position);
            pageContentByte.setTextMatrix(46, 617);
            pageContentByte.showText(department);

            String gstatus;

            pageContentByte.setTextMatrix(157, 493);
            String changeCase = gStatus + ", " + taskName;
            pageContentByte.showText(changeCase.toUpperCase());

            pageContentByte.setTextMatrix(250, 444);
            pageContentByte.showText(gStatus + "  " + taskName + " .");

            pageContentByte.setTextMatrix(180, 432);
            pageContentByte.showText(sDate);

            pageContentByte.setTextMatrix(290, 432);
            pageContentByte.showText(eDate + " .");

            pageContentByte.setTextMatrix(46, 248);
            pageContentByte.showText(postHolderName);
            pageContentByte.setTextMatrix(46, 236);
            pageContentByte.showText(postName);
            pageContentByte.setTextMatrix(46, 224);
            pageContentByte.showText("Fakulti Komputeran");
            pageContentByte.setTextMatrix(46, 212);
            pageContentByte.showText(postHolderEmail);

            pageContentByte.endText();
        }
        //Close the pdfStamper.
        pdfStamper.close();
        System.out.println("PDF modified successfully.");

        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

}

From source file:uy.gub.imm.sae.web.mbean.reserva.PasoFinalMBean.java

License:Open Source License

public String imprimirTicket() {
    try {//ww w .jav  a2  s. co m

        BaseColor colorBlack = new BaseColor(0, 0, 0);

        BaseFont times = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        BaseFont helveticaBold = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252,
                BaseFont.NOT_EMBEDDED);
        BaseFont symbol = BaseFont.createFont(BaseFont.SYMBOL, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

        SimpleDateFormat sdfHr = new SimpleDateFormat("HH:mm");
        SimpleDateFormat sdfFecha = new SimpleDateFormat("dd/MM/yyyy");

        Rectangle pageSize = new Rectangle(210, 210);

        Document document = new Document(pageSize);
        document.addTitle(getI18N().getText("etiqueta.reserva.title"));

        ByteArrayOutputStream os = new ByteArrayOutputStream();

        PdfWriter pdfWriter = PdfWriter.getInstance(document, os);
        document.open();

        PdfContentByte pdfContent = pdfWriter.getDirectContent();

        InputStream is = PasoFinalMBean.class.getResourceAsStream(SAEProfile.getInstance().getProperties()
                .getProperty(SAEProfile.PROFILE_UI_TEMPLATES_IMAGES_LOGO_TICKET_KEY));

        byte[] arrImage = new byte[4096];
        is.read(arrImage);

        Image img = Image.getInstance(arrImage);

        img.scaleAbsolute(100, 30);
        img.setAbsolutePosition(55, 170);
        document.add(img);

        //Dibujo primer lnea
        LineSeparator line = new LineSeparator();
        line.setAlignment(LineSeparator.ALIGN_CENTER);
        line.setLineColor(colorBlack);
        line.setLineWidth(0.5f);

        line.drawLine(pdfContent, 10, 200, 170);

        //Etiqueta RESERVA
        pdfContent.beginText();
        pdfContent.setFontAndSize(helveticaBold, 15);
        pdfContent.setTextMatrix(45, 150);
        pdfContent.showText(getI18N().getText("etiqueta.reserva.showText"));
        pdfContent.endText();

        //Fecha de la reserva
        String fecha_reserva = sdfFecha.format(sesionMBean.getDisponibilidad().getHoraInicio());

        pdfContent.beginText();
        pdfContent.setFontAndSize(symbol, 16);
        pdfContent.setTextMatrix(130, 150);
        pdfContent.showText(fecha_reserva);
        pdfContent.endText();

        //Dibujo segunda lnea
        line.drawLine(pdfWriter.getDirectContent(), 10, 200, 140);

        int etiqHoraTamanio = 25;
        int etiqHoraX = 15;
        int etiqHoraY = 85;

        int valorHoraTamanio = 40;
        int valorHoraX = 105;
        int valorHoraY = 80;

        String serie = sesionMBean.getRecurso().getSerie();
        boolean conSerie = (serie != null) && (serie.length() >= 1);

        if (sesionMBean.getRecurso().getMostrarNumeroEnTicket()) {

            if (!conSerie) {
                //Ajusto valor y etiqueta hora
                etiqHoraTamanio = 20;
                etiqHoraX = 15;
                etiqHoraY = 110;

                valorHoraTamanio = 30;
                valorHoraX = 120;
                valorHoraY = 107;

                //Etiqueta NUMERO
                pdfContent.beginText();
                pdfContent.setFontAndSize(helveticaBold, 20);
                pdfContent.setTextMatrix(15, 65);
                pdfContent.showText(getI18N().getText("etiqueta.numero.numero"));
                pdfContent.endText();

                //Numero de la reserva
                String nro = sesionMBean.getReservaConfirmada().getNumero().toString();
                int nro_pos = 135;

                if (nro.length() == 1) {
                    nro_pos = 135;
                } else if (nro.length() == 2) {
                    nro_pos = 125;
                } else {
                    nro_pos = 105;
                }

                pdfContent.beginText();
                pdfContent.setFontAndSize(symbol, 60);
                pdfContent.setTextMatrix(nro_pos, 55);
                pdfContent.showText(nro);
                pdfContent.endText();
            } else {
                //<<<<<< Agregado >>>>>>
                //Ajusto valor y etiqueta hora
                etiqHoraTamanio = 20;
                etiqHoraX = 15;
                etiqHoraY = 123;

                valorHoraTamanio = 20;
                valorHoraX = 120;
                valorHoraY = 122;

                //Etiqueta SERIE
                pdfContent.beginText();
                pdfContent.setFontAndSize(helveticaBold, 20);
                pdfContent.setTextMatrix(15, 87);
                pdfContent.showText(getI18N().getText("etiqueta.numero.serie"));
                pdfContent.endText();

                pdfContent.beginText();
                pdfContent.setFontAndSize(helveticaBold, 20);
                pdfContent.setTextMatrix(120, 87);
                pdfContent.showText(serie);
                pdfContent.endText();

                //Etiqueta NUMERO
                pdfContent.beginText();
                pdfContent.setFontAndSize(helveticaBold, 20);
                pdfContent.setTextMatrix(15, 50);
                pdfContent.showText(getI18N().getText("etiqueta.numero.numero"));
                pdfContent.endText();

                //Numero de la reserva
                String nro = sesionMBean.getReservaConfirmada().getNumero().toString();
                int nro_pos = 135;

                if (nro.length() == 1) {
                    nro_pos = 135;
                } else if (nro.length() == 2) {
                    nro_pos = 125;
                } else {
                    nro_pos = 105;
                }

                pdfContent.beginText();
                pdfContent.setFontAndSize(symbol, 40);
                pdfContent.setTextMatrix(nro_pos, 47);
                pdfContent.showText(nro);
                pdfContent.endText();
            }
        }

        //Etiqueta HORA
        pdfContent.beginText();
        pdfContent.setFontAndSize(helveticaBold, etiqHoraTamanio);
        pdfContent.setTextMatrix(etiqHoraX, etiqHoraY);
        pdfContent.showText(getI18N().getText("etiqueta.hora.hora"));
        pdfContent.endText();

        //Hora de la reserva
        pdfContent.beginText();
        pdfContent.setFontAndSize(symbol, valorHoraTamanio);
        pdfContent.setTextMatrix(valorHoraX, valorHoraY);
        pdfContent.showText(sdfHr.format(sesionMBean.getDisponibilidad().getHoraInicio()));
        pdfContent.endText();

        //Dibujo tercer lnea
        line.drawLine(pdfWriter.getDirectContent(), 10, 200, 45);

        String ticketEtiqUno = sesionMBean.getRecurso().getTextoRecurso().getTicketEtiquetaUno();
        String ticketEtiqDos = sesionMBean.getRecurso().getTextoRecurso().getTicketEtiquetaDos();
        int largoEtiqUno = 0;
        int largoEtiqDos = 0;
        int xValores = 0;

        if (ticketEtiqUno != null) {
            largoEtiqUno = ticketEtiqUno.length();
        }

        if (ticketEtiqDos != null) {
            largoEtiqDos = ticketEtiqDos.length();
        }

        if (largoEtiqUno > largoEtiqDos) {
            xValores = 8 * (largoEtiqUno + 1);
        } else {
            xValores = 8 * (largoEtiqDos + 1);
        }

        //Etiqueta uno
        if (ticketEtiqUno != null) {
            pdfContent.beginText();
            pdfContent.setFontAndSize(helveticaBold, 10);
            pdfContent.setTextMatrix(10, 30);
            pdfContent.showText(ticketEtiqUno + ":");
            pdfContent.endText();
        }

        //Valor etiqueta uno
        String valorEtiqUno = sesionMBean.getRecurso().getTextoRecurso().getValorEtiquetaUno();
        if (valorEtiqUno != null) {
            pdfContent.beginText();
            pdfContent.setFontAndSize(times, 10);
            pdfContent.setTextMatrix(xValores, 30);
            pdfContent.showText(valorEtiqUno);
            pdfContent.endText();
        }

        //Etiqueta dos

        if (ticketEtiqDos != null) {
            pdfContent.beginText();
            pdfContent.setFontAndSize(helveticaBold, 10);
            pdfContent.setTextMatrix(10, 15);
            pdfContent.showText(ticketEtiqDos + ":");
            pdfContent.endText();
        }

        //Valor etiqueta dos
        String valorEtiqDos = sesionMBean.getRecurso().getTextoRecurso().getValorEtiquetaDos();
        if (valorEtiqDos != null) {
            pdfContent.beginText();
            pdfContent.setFontAndSize(times, 10);
            pdfContent.setTextMatrix(xValores, 15);
            pdfContent.showText(valorEtiqDos);
            pdfContent.endText();
        }

        pdfWriter.addJavaScript("this.print({bUI: true, bSilent: true, bShrinkToFit: true});", false);
        pdfWriter.addJavaScript("this.closeDoc(true);");

        document.close();

        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        response.setContentType("application/pdf");

        os.writeTo(response.getOutputStream());

        response.getOutputStream().flush();
        response.getOutputStream().close();
        facesContext.responseComplete();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:uy.gub.imm.sae.web.mbean.reserva.PasoFinalMBean.java

License:Open Source License

public String guardarTicket() {
    try {//from   w  w  w . j ava 2  s. c o m

        BaseColor colorBlack = new BaseColor(0, 0, 0);

        BaseFont times = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        BaseFont helveticaBold = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252,
                BaseFont.NOT_EMBEDDED);
        BaseFont symbol = BaseFont.createFont(BaseFont.SYMBOL, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

        SimpleDateFormat sdfHr = new SimpleDateFormat("HH:mm");
        SimpleDateFormat sdfFecha = new SimpleDateFormat("dd/MM/yyyy");

        Rectangle pageSize = new Rectangle(210, 210);

        Document document = new Document(pageSize);
        document.addTitle(getI18N().getText("etiqueta.reserva.title"));

        ByteArrayOutputStream os = new ByteArrayOutputStream();

        PdfWriter pdfWriter = PdfWriter.getInstance(document, os);
        document.open();

        PdfContentByte pdfContent = pdfWriter.getDirectContent();

        InputStream is = PasoFinalMBean.class.getResourceAsStream(SAEProfile.getInstance().getProperties()
                .getProperty(SAEProfile.PROFILE_UI_TEMPLATES_IMAGES_LOGO_TICKET_KEY));

        byte[] arrImage = new byte[4096];
        is.read(arrImage);

        Image img = Image.getInstance(arrImage);

        img.scaleAbsolute(100, 30);
        img.setAbsolutePosition(55, 170);
        document.add(img);

        //Dibujo primer lnea
        LineSeparator line = new LineSeparator();
        line.setAlignment(LineSeparator.ALIGN_CENTER);
        line.setLineColor(colorBlack);
        line.setLineWidth(0.5f);

        line.drawLine(pdfContent, 10, 200, 170);

        //Etiqueta RESERVA
        pdfContent.beginText();
        pdfContent.setFontAndSize(helveticaBold, 15);
        pdfContent.setTextMatrix(45, 150);
        pdfContent.showText(getI18N().getText("etiqueta.reserva.showText"));
        pdfContent.endText();

        //Fecha de la reserva
        String fecha_reserva = sdfFecha.format(sesionMBean.getDisponibilidad().getHoraInicio());

        pdfContent.beginText();
        pdfContent.setFontAndSize(symbol, 16);
        pdfContent.setTextMatrix(130, 150);
        pdfContent.showText(fecha_reserva);
        pdfContent.endText();

        //Dibujo segunda lnea
        line.drawLine(pdfWriter.getDirectContent(), 10, 200, 140);

        int etiqHoraTamanio = 25;
        int etiqHoraX = 15;
        int etiqHoraY = 85;

        int valorHoraTamanio = 40;
        int valorHoraX = 105;
        int valorHoraY = 80;

        String serie = sesionMBean.getRecurso().getSerie();
        boolean conSerie = (serie != null) && (serie.length() >= 1);

        if (sesionMBean.getRecurso().getMostrarNumeroEnTicket()) {

            if (!conSerie) {
                //Ajusto valor y etiqueta hora
                etiqHoraTamanio = 20;
                etiqHoraX = 15;
                etiqHoraY = 110;

                valorHoraTamanio = 30;
                valorHoraX = 120;
                valorHoraY = 107;

                //Etiqueta NUMERO
                pdfContent.beginText();
                pdfContent.setFontAndSize(helveticaBold, 20);
                pdfContent.setTextMatrix(15, 65);
                pdfContent.showText(getI18N().getText("etiqueta.numero.numero"));
                pdfContent.endText();

                //Numero de la reserva
                String nro = sesionMBean.getReservaConfirmada().getNumero().toString();
                int nro_pos = 135;

                if (nro.length() == 1) {
                    nro_pos = 135;
                } else if (nro.length() == 2) {
                    nro_pos = 125;
                } else {
                    nro_pos = 105;
                }

                pdfContent.beginText();
                pdfContent.setFontAndSize(symbol, 60);
                pdfContent.setTextMatrix(nro_pos, 55);
                pdfContent.showText(nro);
                pdfContent.endText();
            } else {

                //Ajusto valor y etiqueta hora
                etiqHoraTamanio = 20;
                etiqHoraX = 15;
                etiqHoraY = 123;

                valorHoraTamanio = 20;
                valorHoraX = 120;
                valorHoraY = 122;

                //Etiqueta SERIE
                pdfContent.beginText();
                pdfContent.setFontAndSize(helveticaBold, 20);
                pdfContent.setTextMatrix(15, 87);
                pdfContent.showText(getI18N().getText("etiqueta.numero.serie"));
                pdfContent.endText();

                pdfContent.beginText();
                pdfContent.setFontAndSize(symbol, 20);
                pdfContent.setTextMatrix(120, 87);
                pdfContent.showText(serie);
                pdfContent.endText();

                //Etiqueta NUMERO
                pdfContent.beginText();
                pdfContent.setFontAndSize(helveticaBold, 20);
                pdfContent.setTextMatrix(15, 50);
                pdfContent.showText(getI18N().getText("etiqueta.numero.numero"));
                pdfContent.endText();

                //Numero de la reserva
                String nro = sesionMBean.getReservaConfirmada().getNumero().toString();
                int nro_pos = 135;

                if (nro.length() == 1) {
                    nro_pos = 135;
                } else if (nro.length() == 2) {
                    nro_pos = 125;
                } else {
                    nro_pos = 105;
                }

                pdfContent.beginText();
                pdfContent.setFontAndSize(symbol, 40);
                pdfContent.setTextMatrix(nro_pos, 47);
                pdfContent.showText(nro);
                pdfContent.endText();
            }
        }

        //Etiqueta HORA
        pdfContent.beginText();
        pdfContent.setFontAndSize(helveticaBold, etiqHoraTamanio);
        pdfContent.setTextMatrix(etiqHoraX, etiqHoraY);
        pdfContent.showText(getI18N().getText("etiqueta.hora.hora"));
        pdfContent.endText();

        //Hora de la reserva
        pdfContent.beginText();
        pdfContent.setFontAndSize(symbol, valorHoraTamanio);
        pdfContent.setTextMatrix(valorHoraX, valorHoraY);
        pdfContent.showText(sdfHr.format(sesionMBean.getDisponibilidad().getHoraInicio()));
        pdfContent.endText();

        //Dibujo tercer lnea
        line.drawLine(pdfWriter.getDirectContent(), 10, 200, 45);

        String ticketEtiqUno = sesionMBean.getRecurso().getTextoRecurso().getTicketEtiquetaUno();
        String ticketEtiqDos = sesionMBean.getRecurso().getTextoRecurso().getTicketEtiquetaDos();
        int largoEtiqUno = 0;
        int largoEtiqDos = 0;
        int xValores = 0;

        if (ticketEtiqUno != null) {
            largoEtiqUno = ticketEtiqUno.length();
        }

        if (ticketEtiqDos != null) {
            largoEtiqDos = ticketEtiqDos.length();
        }

        if (largoEtiqUno > largoEtiqDos) {
            xValores = 8 * (largoEtiqUno + 1);
        } else {
            xValores = 8 * (largoEtiqDos + 1);
        }

        //Etiqueta uno
        if (ticketEtiqUno != null) {
            pdfContent.beginText();
            pdfContent.setFontAndSize(helveticaBold, 10);
            pdfContent.setTextMatrix(10, 30);
            pdfContent.showText(ticketEtiqUno + ":");
            pdfContent.endText();
        }

        //Valor etiqueta uno
        String valorEtiqUno = sesionMBean.getRecurso().getTextoRecurso().getValorEtiquetaUno();
        if (valorEtiqUno != null) {
            pdfContent.beginText();
            pdfContent.setFontAndSize(times, 10);
            pdfContent.setTextMatrix(xValores, 30);
            pdfContent.showText(valorEtiqUno);
            pdfContent.endText();
        }

        //Etiqueta dos
        if (ticketEtiqDos != null) {
            pdfContent.beginText();
            pdfContent.setFontAndSize(helveticaBold, 10);
            pdfContent.setTextMatrix(10, 15);
            pdfContent.showText(ticketEtiqDos + ":");
            pdfContent.endText();
        }

        //Valor etiqueta dos
        String valorEtiqDos = sesionMBean.getRecurso().getTextoRecurso().getValorEtiquetaDos();
        if (valorEtiqDos != null) {
            pdfContent.beginText();
            pdfContent.setFontAndSize(times, 10);
            pdfContent.setTextMatrix(xValores, 15);
            pdfContent.showText(valorEtiqDos);
            pdfContent.endText();
        }

        document.close();

        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "attachment; filename=" + "Ticket de confirmacin.pdf");

        os.writeTo(response.getOutputStream());

        response.getOutputStream().flush();
        response.getOutputStream().close();
        facesContext.responseComplete();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}