Example usage for com.itextpdf.text.pdf PdfContentByte showText

List of usage examples for com.itextpdf.text.pdf PdfContentByte showText

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfContentByte showText.

Prototype

public void showText(final PdfTextArray text) 

Source Link

Document

Show an array of text.

Usage

From source file:com.vectorprint.report.itext.style.stylers.Shadow.java

License:Open Source License

@Override
public void draw(Rectangle rect, String genericTag) throws VectorPrintException {
    if (genericTag == null) {
        if (log.isLoggable(Level.FINE)) {
            log.fine("not drawing shadow because genericTag is null (no data for shadow)");
        }// w ww.ja  v  a  2s.  co m
        return;
    }
    DelayedData delayed = getDelayed(genericTag);
    PdfContentByte canvas = getPreparedCanvas();
    try {
        com.itextpdf.text.Font f = delayed.getChunk().getFont();
        if (f.getBaseFont() == null) {
            throw new VectorPrintRuntimeException(
                    "font " + f.getFamilyname() + " does not have a basefont, check your fontloading");
        }
        /*
         * print as much of the text as fits in the width of the rectangle
         */
        String toPrint = delayed.getStringData();
        int i = toPrint.length() + 1;
        do {
            toPrint = toPrint.substring(0, --i);
        } while (ItextHelper.getTextWidth(toPrint, f.getBaseFont(), f.getSize()) > rect.getWidth() + 1);
        if (i < delayed.getStringData().length()) {
            String nextPart = delayed.getStringData().substring(i).replaceFirst(" *", "");
            if (log.isLoggable(Level.FINE)) {
                log.fine(String.format("event %s, printed shadow %s of %s, left %s for next event", genericTag,
                        toPrint, delayed.getData(), nextPart));
            }
            delayed.setData(nextPart);
        }

        canvas.setFontAndSize(f.getBaseFont(), f.getSize());
        canvas.setColorFill((getColor() == null) ? f.getColor() : itextHelper.fromColor(getColor()));
        canvas.setColorStroke((getColor() == null) ? f.getColor() : itextHelper.fromColor(getColor()));

        canvas.beginText();
        HashMap<String, Object> attributes = delayed.getChunk().getAttributes();
        if (attributes != null && attributes.containsKey(Chunk.SKEW)) {
            float[] skew = (float[]) attributes.get(Chunk.SKEW);
            canvas.setTextMatrix(1, skew[0], skew[1], 1, rect.getLeft() + calculateShift(getShiftx(), f),
                    rect.getBottom() - calculateShift(getShifty(), f));
        } else {
            canvas.setTextMatrix(1, 0, 0, 1, rect.getLeft() + calculateShift(getShiftx(), f),
                    rect.getBottom() - calculateShift(getShifty(), f));
        }
        canvas.setTextRise(delayed.getChunk().getTextRise());
        canvas.showText(toPrint);
        canvas.endText();
    } catch (Exception ex) {
        resetCanvas(canvas);
        throw new VectorPrintException(ex);
    }
    resetCanvas(canvas);
}

From source file:Controlador.ControladorCrearPase.java

private static void absText(PdfWriter writer, String text, int x, int y) throws DocumentException, IOException {

    PdfContentByte cb = writer.getDirectContent();
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb.saveState();//from www  .  ja  v  a 2 s.  c  o  m
    cb.beginText();
    cb.moveText(x, y);
    cb.setFontAndSize(bf, 12);
    cb.showText(text);
    cb.endText();
    cb.restoreState();

}

From source file:dbedit.actions.ExportPdfAction.java

License:Open Source License

/**
 * Print page numbers on right bottom corner
 * @param writer// w w w.  j a va 2 s.  c  o  m
 * @param document
 */
@Override
public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    String text = String.format("Page %d of ", writer.getPageNumber());
    float textSize = BASE_FONT.getWidthPoint(text, 12);
    float textBase = document.bottom() - 20;
    cb.beginText();
    cb.setFontAndSize(BASE_FONT, 12);
    float adjust = BASE_FONT.getWidthPoint("000", 12);
    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(pdfTemplate, document.right() - adjust, textBase);
}

From source file:de.jost_net.JVerein.io.FormularAufbereitung.java

License:Open Source License

private void goFormularfeld(PdfContentByte contentByte, Formularfeld feld, Object val)
        throws DocumentException, IOException {
    BaseFont bf = null;// ww  w.j a  v  a 2s.c o  m
    if (feld.getFont().startsWith("FreeSans")) {
        String filename = "/fonts/FreeSans";
        if (feld.getFont().length() > 8) {
            filename += feld.getFont().substring(9);
        }
        bf = BaseFont.createFont(filename + ".ttf", BaseFont.IDENTITY_H, true);
    } else {
        bf = BaseFont.createFont(feld.getFont(), BaseFont.CP1250, false);
    }

    float x = mm2point(feld.getX().floatValue());
    float y = mm2point(feld.getY().floatValue());
    if (val == null) {
        return;
    }
    buendig = links;
    String stringVal = getString(val);
    stringVal = stringVal.replace("\\n", "\n");
    stringVal = stringVal.replaceAll("\r\n", "\n");
    String[] ss = stringVal.split("\n");
    for (String s : ss) {
        contentByte.setFontAndSize(bf, feld.getFontsize().floatValue());
        contentByte.beginText();
        float offset = 0;
        if (buendig == rechts) {
            offset = contentByte.getEffectiveStringWidth(s, true);
        }
        contentByte.moveText(x - offset, y);
        contentByte.showText(s);
        contentByte.endText();
        y -= feld.getFontsize().floatValue() + 3;
    }
}

From source file:es.clinica.veterinaria.facturas.FacturaPdf.java

private void createHeadings(PdfContentByte cb, float x, float y, String text, int tam) {
    cb.beginText();/*from   w w  w  .  ja v  a  2s. c  om*/
    cb.setFontAndSize(bfBold, tam);
    cb.setFontAndSize(bfBold, tam);
    cb.setTextMatrix(x, y);
    cb.showText(text.trim());
    cb.endText();
}

From source file:es.clinica.veterinaria.facturas.FacturaPdf.java

private void createCliente(PdfContentByte cb, float x, float y, String text, int tam) {
    cb.beginText();/*  www  .  j av  a  2 s  .  c o m*/
    cb.setFontAndSize(bf, tam);
    cb.setFontAndSize(bf, tam);
    cb.setTextMatrix(x, y);
    cb.showText(text.trim());
    cb.endText();
}

From source file:Excel.pdfsJavaGenerador.java

public void run() {
    Document documento = new Document();
    documento.setPageSize(PageSize.A4.rotate());
    int i = 1;/*w w w  . ja va  2 s. com*/
    String arch = periodo + "_Iva Ventas.pdf";

    File fich = new File(arch);

    FileOutputStream fichero;
    try {
        pdfsJavaGenerador pdf;

        ArrayList listado = new ArrayList();
        String sql = "select * from ivaventas where periodo='" + periodo + "' order by numero";
        Transaccionable tra = new ConeccionLocal();
        ResultSet rs = tra.leerConjuntoDeRegistros(sql);
        while (rs.next()) {
            pdf = new pdfsJavaGenerador();
            pdf.setComprobante(rs.getString("comprobante"));
            pdf.setFecha(rs.getString("fecha"));
            pdf.setNumeroFactura(rs.getString("numero"));
            pdf.setRazonSocial(rs.getString("cliente"));
            pdf.setCondicionIva(rs.getString("condicion"));
            pdf.setCuit(rs.getString("cuit"));
            pdf.setNeto(rs.getString("neto"));
            pdf.setIva(rs.getString("iva"));
            pdf.setTotal(rs.getString("total"));
            listado.add(pdf);
        }
        rs.close();
        Integer totalItems = listado.size();
        Integer totalPaginas = totalItems / 46;
        Integer contadorPaginas = 1;
        totalPaginas = totalPaginas + 1;
        System.out.println(" items " + totalItems + " paginas " + totalPaginas);
        fichero = new FileOutputStream(arch);
        PdfWriter writer = PdfWriter.getInstance(documento, fichero);

        documento.open();
        //writer.addPageDictEntry(PdfName.ROTATE,PdfPage.SEASCAPE);
        writer.addPageDictEntry(PdfName.ROTATE, null);
        PdfContentByte cb = writer.getDirectContent();

        BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.setFontAndSize(bf, 12);
        cb.beginText();
        //cb.setTextMatrix(250,820);
        //cb.showText("Subdiario de IVA Ventas");
        cb.setFontAndSize(bf, 10);

        cb.setTextMatrix(20, 480);
        cb.showText("Periodo " + periodo);
        //cb.setTextMatrix(750,550);
        //cb.showText("Hoja "+contadorPaginas+" de "+totalPaginas);

        int renglon = 460;
        String vencimiento;
        String descripcion;
        String monto;
        String recargo;
        String total;
        String totalFinal;
        Double tot = 0.00;
        String razonSocial;
        int itt = 0;
        //aca empieza la iteracion

        //encabezados
        bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.setFontAndSize(bf, 8);
        cb.setTextMatrix(20, renglon);
        cb.showText("Cbte");
        cb.setTextMatrix(50, renglon);
        cb.showText("Fecha");
        cb.setTextMatrix(90, renglon);
        cb.showText("Nro Factura");
        cb.setTextMatrix(150, renglon);
        cb.showText("Cliente");
        cb.setTextMatrix(500, renglon);
        //tot=saldo.getCantidad() * saldo.getPrecioUnitario();
        cb.showText("Cond");
        cb.setTextMatrix(540, renglon);
        cb.showText("C.U.I.T.");
        cb.setTextMatrix(610, renglon);
        cb.showText("Neto");
        cb.setTextMatrix(660, renglon);
        cb.showText("I.V.A.");
        cb.setTextMatrix(700, renglon);
        cb.showText("Imp. Int.");
        cb.setTextMatrix(760, renglon);
        cb.showText("Total");
        renglon = renglon - 20;

        //fin encabezados
        bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.setFontAndSize(bf, 6);
        Iterator itl = listado.listIterator();
        //vencimiento="Esta cotizacin tendr vigencia 30 das ";
        Double montoCIva = 0.00;
        Double descuento = 0.00;
        Double descUnitario = 0.00;
        Double descTotal = 0.00;
        Double montoCIvaTotal = 0.00;
        Double descuentoTotal = 0.00;
        Double descUnitarioTotal = 0.00;
        Double descTotalTotal = 0.00;
        String descripcionArt = null;
        while (itl.hasNext()) {
            pdf = (pdfsJavaGenerador) itl.next();

            //vencimiento=saldo.getVencimientoString();
            /*
            descripcion="Numero Resumen de cta ";
            montoCIva=saldo.getPrecioUnitario() * 1.21;
            monto=Numeros.ConvertirNumero(montoCIva);
            recargo="10%";
            total="nada";
            */

            //recargo=String.valueOf(saldo.getRecargo());
            //tot=tot + saldo.getTotal();
            //total=String.valueOf(saldo.getTotal());

            cb.setTextMatrix(20, renglon);
            cb.showText(pdf.getComprobante());
            cb.setTextMatrix(45, renglon);
            cb.showText(pdf.getFecha());
            cb.setTextMatrix(90, renglon);
            cb.showText(pdf.getNumeroFactura());
            cb.setTextMatrix(150, renglon);

            razonSocial = pdf.getRazonSocial();

            cb.showText(razonSocial);
            cb.setTextMatrix(500, renglon);

            cb.showText(pdf.getCondicionIva());
            cb.setTextMatrix(540, renglon);
            cb.showText(pdf.getCuit());
            cb.setTextMatrix(600, renglon);

            if (pdf.getComprobante().equals("N.C.")) {
                String neto = pdf.getNeto();
                String iva = pdf.getIva();
                String totalP = pdf.getTotal();
                pdf.setNeto("-" + neto.trim());
                pdf.setIva("-" + iva.trim());
                pdf.setTotal("-" + totalP.trim());
            }
            montoCIva = montoCIva + Numeros.ConvertirStringADouble(pdf.getNeto());
            descuento = descuento + Numeros.ConvertirStringADouble(pdf.getIva());
            descTotal = descTotal + Numeros.ConvertirStringADouble(pdf.getTotal());

            cb.showText(pdf.getNeto());
            cb.setTextMatrix(650, renglon);

            cb.showText(pdf.getIva());
            cb.setTextMatrix(710, renglon);
            cb.showText("0.00");
            cb.setTextMatrix(750, renglon);

            cb.showText(pdf.getTotal());

            //descuento=descuento+saldo.getDescuento();
            renglon = renglon - 10;
            if (renglon < 30) {
                bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                cb.setFontAndSize(bf, 7);
                cb.setTextMatrix(550, renglon);
                cb.showText("Subtotal:");
                cb.setTextMatrix(600, renglon);
                cb.showText(Numeros.ConvetirNumeroDosDigitos(montoCIva));
                cb.setTextMatrix(650, renglon);
                cb.showText(Numeros.ConvetirNumeroDosDigitos(descuento));
                cb.setTextMatrix(710, renglon);
                cb.showText("0.00");
                cb.setTextMatrix(750, renglon);
                cb.showText(Numeros.ConvetirNumeroDosDigitos(descTotal));
                montoCIvaTotal = montoCIvaTotal + montoCIva;
                descuentoTotal = descuentoTotal + descuento;

                descTotalTotal = descTotalTotal + descTotal;
                descuento = 0.00;
                descTotal = 0.00;
                montoCIva = 0.00;
                renglon = 460;
                cb.endText();
                documento.newPage();
                documento.setPageSize(PageSize.A4.rotate());
                cb.beginText();

                contadorPaginas++;
                cb.setFontAndSize(bf, 12);
                //cb.setTextMatrix(250,820);
                //cb.showText("Subdiario de IVA Ventas");
                cb.setFontAndSize(bf, 10);
                cb.setTextMatrix(20, 480);
                cb.showText("Periodo " + periodo);
                //cb.setTextMatrix(750,550);
                //cb.showText("Hoja "+contadorPaginas+" de "+totalPaginas);

                //aca empieza la iteracion

                //encabezados
                bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                cb.setFontAndSize(bf, 8);
                cb.setTextMatrix(20, renglon);
                cb.showText("Cbte");
                cb.setTextMatrix(50, renglon);
                cb.showText("Fecha");
                cb.setTextMatrix(90, renglon);
                cb.showText("Nro Factura");
                cb.setTextMatrix(150, renglon);
                cb.showText("Cliente");
                cb.setTextMatrix(500, renglon);
                //tot=saldo.getCantidad() * saldo.getPrecioUnitario();
                cb.showText("Cond");
                cb.setTextMatrix(540, renglon);
                cb.showText("C.U.I.T.");
                cb.setTextMatrix(610, renglon);
                cb.showText("Neto");
                cb.setTextMatrix(660, renglon);
                cb.showText("I.V.A.");
                cb.setTextMatrix(700, renglon);
                cb.showText("Imp. Int.");
                cb.setTextMatrix(760, renglon);
                cb.showText("Total");
                renglon = renglon - 20;

                //fin encabezados
                bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                cb.setFontAndSize(bf, 6);
            }
        }

        bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.setFontAndSize(bf, 7);
        cb.setTextMatrix(540, renglon);
        cb.showText("Subtotal:");
        cb.setTextMatrix(600, renglon);
        cb.showText(Numeros.ConvetirNumeroDosDigitos(montoCIva));
        cb.setTextMatrix(650, renglon);
        cb.showText(Numeros.ConvetirNumeroDosDigitos(descuento));
        cb.setTextMatrix(710, renglon);
        cb.showText("0.00");
        cb.setTextMatrix(750, renglon);
        cb.showText(Numeros.ConvetirNumeroDosDigitos(descTotal));
        renglon = renglon - 10;

        montoCIvaTotal = montoCIvaTotal + montoCIva;
        descuentoTotal = descuentoTotal + descuento;

        descTotalTotal = descTotalTotal + descTotal;
        cb.setTextMatrix(540, renglon);
        cb.showText("Total:");
        cb.setTextMatrix(600, renglon);
        cb.showText(Numeros.ConvetirNumeroDosDigitos(montoCIvaTotal));
        cb.setTextMatrix(650, renglon);
        cb.showText(Numeros.ConvetirNumeroDosDigitos(descuentoTotal));
        cb.setTextMatrix(710, renglon);
        cb.showText("0.00");
        cb.setTextMatrix(750, renglon);
        cb.showText(Numeros.ConvetirNumeroDosDigitos(descTotalTotal));

        descuento = 0.00;
        descTotal = 0.00;
        montoCIva = 0.00;

        cb.endText();
        documento.close();

        File f = new File(arch);
        if (f.exists()) {

            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + arch);
        }
        int confirmacion = 0;
        /*
        if(doc.getArchivo().isEmpty()){
                
        }else{
        confirmacion=JOptionPane.showConfirmDialog(null, "DESEA NOTIFICAR POR MAIL?");
        if(confirmacion==0){
        //JOptionPane.showMessageDialog(null,"acepto");
                
        }
        }
            */
        System.out.println("eligio " + confirmacion);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(pdfsJavaGenerador.class.getName()).log(Level.SEVERE, null, ex);

    } catch (DocumentException ex) {
        Logger.getLogger(pdfsJavaGenerador.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(pdfsJavaGenerador.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(pdfsJavaGenerador.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:fll.util.SimpleFooterHandler.java

License:Open Source License

@Override
public void onEndPage(final PdfWriter writer, final Document document) {
    final PdfContentByte cb = writer.getDirectContent();
    cb.saveState();//w w  w.ja  va  2  s .c o m

    // compose the footer
    final String text = "Page " + writer.getPageNumber() + " of ";
    final float textSize = _headerFooterFont.getWidthPoint(text, 12);
    final float textBase = document.bottom() - 20;
    cb.beginText();
    cb.setFontAndSize(_headerFooterFont, 12);

    final float adjust = _headerFooterFont.getWidthPoint("0", 12);
    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(_tpl, document.right() - adjust, textBase);

    cb.restoreState();
}

From source file:me.Aron.Heinecke.fbot.lib.Converter.java

License:Apache License

/***
 * Add a note to the bottom of a pdf file in italic font
 * @param rfile file to be read from//from   ww w .  j a  v  a  2  s. c o  m
 * @param wfile file to be written to
 * @param text text to add
 * @return path to the resulting pdf, null if it failed
 */
private String addPDFNote(File rfile, File wfile, String text) {
    try {
        PdfReader pdfReader = new PdfReader(rfile.getAbsolutePath());

        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(wfile));

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

            PdfContentByte cb = pdfStamper.getUnderContent(i);

            BaseFont bf = BaseFont.createFont();
            bf.setPostscriptFontName("ITALIC");
            cb.beginText();
            cb.setFontAndSize(bf, 12);
            cb.setTextMatrix(10, 20);
            cb.showText(text);
            cb.endText();
        }

        pdfStamper.close();
        return wfile.getAbsolutePath();
    } catch (IOException | DocumentException e) {
        fbot.getLogger().exception("converter", e);
        return null;
    }
}

From source file:org.javad.pdf.util.PdfUtil.java

License:Apache License

protected static void improveRenderText(PdfContentByte content, String str, Font f, float x, float y) {

    BaseFont bf = f.getCalculatedBaseFont(false);
    if (i18Font == null && (System.currentTimeMillis() - LAST_CHECK_TIME > 10000)) {
        i18Font = FontRegistry.getInstance().getFont(PdfFontDefinition.ExtendedCharacters)
                .getCalculatedBaseFont(false);
        LAST_CHECK_TIME = System.currentTimeMillis();
    }//ww  w  .j  a v  a2  s .  co m
    StringBuilder buf = new StringBuilder(str.length());
    boolean extendedCodePoint = false;
    float effWidth = 0.0f;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        int codePoint = Character.codePointAt("" + c, 0);
        boolean curCodePoint = (!bf.charExists(codePoint)) ? true : false;
        if (curCodePoint != extendedCodePoint) {
            content.setFontAndSize((extendedCodePoint) ? i18Font : bf, f.getSize());
            effWidth += content.getEffectiveStringWidth(buf.toString(), false);
            buf = new StringBuilder();
            extendedCodePoint = curCodePoint;
        }
        buf.append(c);
    }
    content.setFontAndSize(bf, f.getSize());
    effWidth += content.getEffectiveStringWidth(buf.toString(), false);
    float x_pos = x - (effWidth / 2.0f); // eq. to showTextAligned

    content.beginText();
    content.setTextMatrix(x_pos, y);
    BaseFont lastFont = bf;
    @SuppressWarnings("UnusedAssignment")
    BaseFont currentFont = lastFont;
    buf = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        int codePoint = Character.codePointAt("" + c, 0);
        if (!bf.charExists(codePoint)) {
            currentFont = i18Font;
        } else {
            currentFont = bf;
        }
        if (currentFont != lastFont) {
            content.showText(buf.toString());
            buf = new StringBuilder();
            content.setFontAndSize(currentFont, f.getSize());
            lastFont = currentFont;
        }
        buf.append(c);
    }
    if (buf.length() > 0) {
        content.showText(buf.toString());
    }
    content.endText();

}