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

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

Introduction

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

Prototype

public void setTextMatrix(final float x, final float y) 

Source Link

Document

Changes the text matrix.

Usage

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.j a  va 2  s.co m*/
    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();// w w  w .j a v 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  .  j a v  a2 s . c o m*/
    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();//from www  .  j  a  va2s .  c om

    // 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 .  ja  va  2s .co 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();
    }/*from w w w  . j  a v  a 2s . c om*/
    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();

}

From source file:org.openlmis.web.view.pdf.PdfPageEventHandler.java

License:Open Source License

private void writeCurrentDate(Document document, PdfContentByte contentByte) {
    contentByte.setTextMatrix(document.left() + textAdjustment, document.bottom());
    String dateText = DATE_FORMAT.format(new Date());
    contentByte.showText(dateText);/* www . ja v  a2  s  .co m*/
}

From source file:org.openlmis.web.view.pdf.PdfPageEventHandler.java

License:Open Source License

private void writePageNumber(PdfWriter writer, Document document, PdfContentByte contentByte) {
    String pageNumberText = messageService.message("label.page.of", writer.getPageNumber()) + " ";
    float pageNumberTextSize = baseFont.getWidthPoint(pageNumberText, FOOTER_TEXT_SIZE);
    contentByte.setTextMatrix(document.right() - pageNumberTextSize - textAdjustment, document.bottom());
    contentByte.showText(pageNumberText);
    contentByte.addTemplate(pageNumberTemplate, document.right() - textAdjustment, document.bottom());
}

From source file:org.primaresearch.pdf.PageToPdfConverter.java

License:Apache License

/**
 * Adds the text of the given page to the current PDF page
 * @param writer/*w  w w . ja  va  2s .c o  m*/
 * @param page
 */
private void addText(PdfWriter writer, Page page) {

    if (textLevel == null)
        return;

    int pageHeight = page.getLayout().getHeight();

    try {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        for (ContentIterator it = page.getLayout().iterator(textLevel); it.hasNext();) {
            ContentObject obj = it.next();
            if (obj == null || !(obj instanceof TextObject))
                continue;
            TextObject textObj = (TextObject) obj;

            if (textObj.getText() != null && !textObj.getText().isEmpty()) {

                List<String> strings = new ArrayList<String>();
                List<Rect> boxes = new ArrayList<Rect>();

                float fontSize = 1.0f;

                //Collect
                if (textObj instanceof LowLevelTextObject) {
                    strings.add(textObj.getText());
                    Rect boundingBox = obj.getCoords().getBoundingBox();
                    boxes.add(boundingBox);
                    fontSize = calculateFontSize(textObj.getText(), boundingBox.getWidth(),
                            boundingBox.getHeight());
                } else {
                    fontSize = splitTextRegion((TextRegion) obj, strings, boxes);
                }

                //Render
                for (int i = 0; i < strings.size(); i++) {
                    String text = strings.get(i);
                    Rect boundingBox = boxes.get(i);

                    //Calculate vertical transition (text is rendered at baseline -> descending bits are below the chosen position)
                    int descent = (int) font.getDescentPoint(text, fontSize);
                    int ascent = (int) font.getAscentPoint(text, fontSize);
                    int textHeight = Math.abs(descent) + ascent;
                    int transY = descent;

                    if (textHeight < boundingBox.getHeight()) {
                        transY = descent - (boundingBox.getHeight() - textHeight) / 2;
                    }

                    cb.beginText();
                    //cb.moveText(boundingBox.left, pageHeight - boundingBox.bottom);
                    cb.setTextMatrix(boundingBox.left, pageHeight - boundingBox.bottom - transY);
                    cb.setFontAndSize(font, fontSize);
                    cb.showText(text);
                    cb.endText();

                    //Debug
                    //cb.moveTo(boundingBox.left, pageHeight - boundingBox.bottom - transY);
                    //cb.lineTo(boundingBox.right, pageHeight - boundingBox.bottom - transY);
                    //cb.moveTo(boundingBox.left, pageHeight - boundingBox.bottom);
                    //cb.lineTo(boundingBox.right, pageHeight - boundingBox.bottom);
                }
            }
        }
        cb.restoreState();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:pdf.alterLetter.java

public static void main(String args[]) {
    try {// w  w  w. j  av  a2  s  .co 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();
    }
}