Example usage for org.apache.pdfbox.pdmodel PDPageContentStream PDPageContentStream

List of usage examples for org.apache.pdfbox.pdmodel PDPageContentStream PDPageContentStream

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDPageContentStream PDPageContentStream.

Prototype

public PDPageContentStream(PDDocument doc, PDAppearanceStream appearance) throws IOException 

Source Link

Document

Create a new appearance stream.

Usage

From source file:mail.java

private void ImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ImprimirActionPerformed
    try {//  w ww  . j  a va 2s.  c o  m
        // TODO add your handling code here:

        PDDocument documento = new PDDocument();
        PDPage paginablanco = new PDPage();
        documento.addPage(paginablanco);
        PDPageContentStream content;
        try {
            content = new PDPageContentStream(documento, paginablanco);

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 9);
            content.newLineAtOffset(50, 780);
            content.showText("Consejo Profesional de Abogacia");
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 9);
            content.newLineAtOffset(450, 780);
            Locale espanol = new Locale("es", "ES");
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE MMMM d HH:mm:ss z yyyy", espanol);
            String fecha = dateFormat.format(new Date());
            content.showText(fecha);
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 6);
            content.newLineAtOffset(50, 770);
            content.showText("Direccin: San Martin 457 - Formosa");
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 10);
            content.newLineAtOffset(200, 750);
            content.showText("Estado de Cuenta de Matricula");
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 10);
            content.newLineAtOffset(50, 735);
            content.showText("Matricula N " + idmatricula + "       Nombre:     " + nombre + "," + apellido);//
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 10);
            content.newLineAtOffset(100, 705);
            content.showText(
                    "Items       Periodo                        Vencimiento                            Importe");
            content.endText();
            content.addRect(50, 10, 400, 700);

            int j = 0;
            int renglon = 685;

            System.out.println(itemsList.size());

            for (int i = 1; i < itemsList.size(); i++) {

                content.beginText();
                content.setFont(PDType1Font.HELVETICA, 10);
                j++;
                content.newLineAtOffset(100, renglon);
                content.showText("  " + i + "              " + itemsList.get(i).getVencimiento()
                        + "                                " + itemsList.get(i).getPeriodo()
                        + "                                      "
                        + String.valueOf(itemsList.get(i).getImporte()));
                renglon = renglon - 13;
                content.endText();
            }
            content.beginText();
            content.newLineAtOffset(100, renglon - 20);
            DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
            simbolos.setDecimalSeparator('.');
            DecimalFormat decim = new DecimalFormat("0.00", simbolos);

            content.showText("Total Adeudado            :$ " + String.valueOf(decim.format(total)));
            content.endText();
            content.close();

            documento.save("matricula_" + idmatricula + ".pdf");
            documento.close();
            System.out.println("guardo archivo matricula_" + idmatricula + ".pdf");
            EnviarMail.setEnabled(true);

        } catch (IOException ex) {
            EnviarMail.setEnabled(false);
            Logger.getLogger(mail.class.getName()).log(Level.SEVERE, null, ex);
        }
        bonos();

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

}

From source file:mail.java

private void bonos() throws SQLException {
    //**//from   w w w.j  a v  a2 s. co  m
    double total = 0;
    ListaBono.clear();
    if (idmatricula != "0") {
        Connection conn;
        try {
            conn = Conector.Connect();

            System.out.println("Bonos");

            PreparedStatement resultado;
            PreparedStatement bono;
            String sql1 = "select * from bonos b left join juzgados j on b.ID_JUZGADO=j.id_juzgado where ID_MATRICULA=? ORDER BY ANO  ";
            bono = conn.prepareStatement(sql1);

            bono.setString(1, idmatricula);
            ResultSet ds = bono.executeQuery();
            DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
            SimpleDateFormat formatofecha = new SimpleDateFormat("dd-MM-yyyy");
            simbolos.setDecimalSeparator('.');
            DecimalFormat decim = new DecimalFormat("0.00", simbolos);
            if (ds.first()) {

                ds.beforeFirst();//regresa el puntero al primer registro
                while (ds.next()) {
                    int numero_expediente = ds.getInt("NUMERO_EXPTE");
                    String ano = ds.getString("ANO");
                    String caratula = ds.getString("cara");
                    String fecha_actuacion = ds.getString("FECHA_ACTUACION");
                    String juzgado = ds.getString("descripcion");
                    double importe = ds.getDouble("MONTOBONO");

                    Double monto_bono = Double.valueOf(decim.format(importe));
                    caratula = caratula.replaceAll("\r\n", " ");
                    caratula = caratula.replaceAll("\n", " ");
                    caratula = caratula.replaceAll("\\\\\\\\", "");

                    //                                    Date per =formatofecha.parse(fecha_pa);
                    //                                   String fecha_pago = formatofecha.format(per);
                    System.out.println(idmatricula);
                    System.out.format("%s,%s,%s,%s,%s,%s\n", numero_expediente, ano, caratula.toLowerCase(),
                            juzgado.toLowerCase(), fecha_actuacion, importe);

                    ListaBono.add(
                            new Bonos(numero_expediente, ano, caratula, juzgado, fecha_actuacion, monto_bono));
                    total = total + monto_bono;

                    botones(true);

                }

                ds.close();
                System.out.println(total);
                System.out.println(ListaBono.size());
            }
        } catch (SQLException ex) {
            Logger.getLogger(mail.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    //**
    int alto = 595;
    int ancho = 842;
    PDDocument documento = new PDDocument();
    PDPage paginablanco = new PDPage(new PDRectangle(ancho, alto));

    documento.addPage(paginablanco);
    PDPageContentStream content;
    System.out.println(paginablanco.getMediaBox().getHeight() + "--" + paginablanco.getMediaBox().getWidth());

    try {
        content = new PDPageContentStream(documento, paginablanco);

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 9);
        content.newLineAtOffset(50, alto - 20);
        content.showText("Consejo Profesional de Abogacia");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 9);
        content.newLineAtOffset(450, alto - 20);
        Locale espanol = new Locale("es", "ES");
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE MMMM d HH:mm:ss z yyyy", espanol);
        String fecha = dateFormat.format(new Date());
        content.showText(fecha);
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 6);
        content.newLineAtOffset(50, alto - 28);
        content.showText("Direccin: San Martin 457 - Formosa");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 10);
        content.newLineAtOffset(200, alto - 38);
        content.showText("BONOS DE ACCCIN LETRADA");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(200, alto - 45);
        content.showText("Estado de Gestin de bonos del Profesional");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 9);
        content.newLineAtOffset(50, alto - 60);
        // para que no tenga errores las tabla de mysql cotejamiento en utf8_bin al cargar en la PDF da error si esta con el tema de las 
        content.showText("Matricula N: " + idmatricula + "       Nombre:     " + nombre + "," + apellido);//
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(50, alto - 75);
        content.showText("Item");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(70, alto - 75);
        content.showText("Expte");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(100, alto - 75);
        content.showText("Ao");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(130, alto - 75);
        content.showText("Caratula");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(500, alto - 75);
        content.showText("Juzgado");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(650, alto - 75);
        content.showText("Monto");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(680, alto - 75);
        content.showText("Vencimiento");
        content.endText();
        content.setNonStrokingColor(Color.DARK_GRAY);
        content.addRect(25, 45, 700, 400);
        //            content.fill();
        int j = 0;
        int renglon = alto - 100;

        for (int i = 0; i < ListaBono.size(); i++) {

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            j++;
            content.newLineAtOffset(50, renglon);
            content.showText(String.valueOf(i + 1));
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            content.newLineAtOffset(70, renglon);
            content.showText(String.valueOf(ListaBono.get(i).getNumero_expediente()));
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            content.newLineAtOffset(100, renglon);
            content.showText(ListaBono.get(i).getAno());
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            content.newLineAtOffset(130, renglon);
            content.showText(String.valueOf(ListaBono.get(i).getCaratula()));
            content.endText();
            content.setFont(PDType1Font.COURIER, 8);

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            content.newLineAtOffset(500, renglon);
            content.showText(ListaBono.get(i).getJuzgado());
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            content.newLineAtOffset(650, renglon);
            content.showText(String.valueOf(ListaBono.get(i).getMonto_bono()));
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            content.newLineAtOffset(680, renglon);
            content.showText(ListaBono.get(i).getFecha_pago());
            content.endText();

            renglon = renglon - 13;
        }

        content.beginText();
        content.newLineAtOffset(100, renglon - 20);
        DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
        simbolos.setDecimalSeparator('.');
        DecimalFormat decim = new DecimalFormat("0.00", simbolos);

        content.showText("Total Bonos Adeudados           :$ " + String.valueOf(decim.format(total)));
        content.endText();
        content.close();

        documento.save("matricula_" + idmatricula + "_bonos.pdf");
        documento.close();
        System.out.println("guardo archivo matricula_" + idmatricula + "_bonos.pdf");
        //            System.out.println(String.valueOf(decim.format(total)));

        EnviarMail.setEnabled(true);

    } catch (IOException ex) {
        EnviarMail.setEnabled(false);
        Logger.getLogger(mail.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:airviewer.AnnotationGenerator.java

/**
 *
 * @param a//from   www  . ja v  a  2  s.  c  o  m
 * @param d
 * @param p
 * @param shouldResize
 * @return
 */
public static PDAppearanceStream generateSquareAppearance(PDAnnotation a, PDDocument d, PDPage p,
        boolean shouldResize) {
    assert null != a;
    assert null != d;
    assert null != p;

    PDAppearanceStream annotationAppearanceStream = null;

    try {
        if (shouldResize) {
            resizeAnnotationToContent(a);
        }

        final String contents = a.getContents();
        final boolean hasContents = null != contents && 0 < contents.length();
        float borderWidth = 0;
        if (a instanceof PDAnnotationMarkup) {
            final PDBorderStyleDictionary borderStyle = ((PDAnnotationMarkup) a).getBorderStyle();
            if (null != a.getColor() && null != borderStyle) {
                borderWidth = Math.abs(borderStyle.getWidth());
            }
        }
        final float fontSize = FONT_SIZE_PDF_POINTS;
        final float textHeight = fontSize;
        final float margin = MARGIN_SIZE_PDF_POINTS;

        PDRectangle position = a.getRectangle();
        final float lowerLeftX = position.getLowerLeftX();
        final float lowerLeftY = position.getLowerLeftY();
        float width = position.getWidth();
        float height = position.getHeight();

        annotationAppearanceStream = new PDAppearanceStream(d);

        annotationAppearanceStream.setBBox(position);
        annotationAppearanceStream.setMatrix(new AffineTransform());
        annotationAppearanceStream.setResources(p.getResources());

        try (PDPageContentStream appearanceContent = new PDPageContentStream(d, annotationAppearanceStream)) {
            appearanceContent.transform(new Matrix()); // Identity transform

            // Rect is inset by half border width to prevent border leaking
            // outside bounding box
            final float insetLowerLeftX = lowerLeftX + borderWidth * 0.5f;
            final float insetLowerLeftY = lowerLeftY + borderWidth * 0.5f;
            final float insetWidth = width - borderWidth;
            final float insetheight = height - borderWidth;
            appearanceContent.addRect(insetLowerLeftX, insetLowerLeftY, insetWidth, insetheight);
            appearanceContent.setLineWidth(borderWidth);
            appearanceContent.setNonStrokingColor(GRAY);

            if (null != a.getColor() && 0 < borderWidth) {
                appearanceContent.setStrokingColor(a.getColor());
                appearanceContent.fillAndStroke();
            } else {
                appearanceContent.fill();

            }

            if (hasContents) {
                appearanceContent.moveTo(0, 0);
                appearanceContent.beginText();

                // Center vertically, left justified inside border with margin
                appearanceContent.newLineAtOffset(lowerLeftX + borderWidth + margin,
                        lowerLeftY + (height + LINE_SPACE_SIZE_PDF_POINTS) * 0.5f - textHeight * 0.5f);
                appearanceContent.setFont(FONT, fontSize);
                if (null != a.getColor()) {
                    appearanceContent.setNonStrokingColor(a.getColor()); // Sets color of text
                } else {
                    appearanceContent.setNonStrokingColor(BLACK); // Sets color of text

                }
                appearanceContent.showText(a.getContents());
                appearanceContent.endText();
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(AnnotationGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }

    return annotationAppearanceStream;
}

From source file:airviewer.AnnotationGenerator.java

/**
 *
 * @param a/*from  w  w  w . j a  v a  2s .c  o  m*/
 * @param d
 * @param p
 * @param shouldResize
 * @return
 */
public static PDAppearanceStream generateCircleAppearance(PDAnnotation a, PDDocument d, PDPage p,
        boolean shouldResize) {
    assert null != a;
    assert null != d;
    assert null != p;

    PDAppearanceStream annotationAppearanceStream = null;

    try {
        if (shouldResize) {
            resizeAnnotationToContent(a);
        }

        final String contents = a.getContents();
        final boolean hasContents = null != contents && 0 < contents.length();
        float borderWidth = 0;
        if (a instanceof PDAnnotationMarkup) {
            final PDBorderStyleDictionary borderStyle = ((PDAnnotationMarkup) a).getBorderStyle();
            if (null != a.getColor() && null != borderStyle) {
                borderWidth = Math.abs(borderStyle.getWidth());
            }
        }
        final float fontSize = FONT_SIZE_PDF_POINTS;
        final float textHeight = fontSize;
        final float margin = MARGIN_SIZE_PDF_POINTS;

        PDRectangle position = a.getRectangle();
        final float lowerLeftX = position.getLowerLeftX();
        final float lowerLeftY = position.getLowerLeftY();
        float width = position.getWidth();
        float height = position.getHeight();

        annotationAppearanceStream = new PDAppearanceStream(d);

        annotationAppearanceStream.setBBox(position);
        annotationAppearanceStream.setMatrix(new AffineTransform());
        annotationAppearanceStream.setResources(p.getResources());

        try (PDPageContentStream appearanceContent = new PDPageContentStream(d, annotationAppearanceStream)) {
            appearanceContent.transform(new Matrix()); // Identity transform

            // Rect is inset by half border width to prevent border leaking
            // outside bounding box
            final float insetLowerLeftX = lowerLeftX + borderWidth * 0.5f;
            final float insetLowerLeftY = lowerLeftY + borderWidth * 0.5f;
            final float insetWidth = width - borderWidth;
            final float insetheight = height - borderWidth;

            if (null != a.getColor()) {
                appearanceContent.setLineWidth(borderWidth);
                appearanceContent.moveTo(insetLowerLeftX, insetLowerLeftY + insetheight * 0.5f);
                appearanceContent.curveTo(insetLowerLeftX, insetLowerLeftY + insetheight * 0.75f,
                        insetLowerLeftX + insetWidth * 0.25f, insetLowerLeftY + insetheight,
                        insetLowerLeftX + insetWidth * 0.5f, insetLowerLeftY + insetheight);
                appearanceContent.curveTo(insetLowerLeftX + insetWidth * 0.75f, insetLowerLeftY + insetheight,
                        insetLowerLeftX + insetWidth, insetLowerLeftY + insetheight * 0.75f,
                        insetLowerLeftX + insetWidth, insetLowerLeftY + insetheight * 0.5f);
                appearanceContent.curveTo(insetLowerLeftX + insetWidth, insetLowerLeftY + insetheight * 0.25f,
                        insetLowerLeftX + insetWidth * 0.75f, insetLowerLeftY,
                        insetLowerLeftX + insetWidth * 0.5f, insetLowerLeftY);
                appearanceContent.curveTo(insetLowerLeftX + insetWidth * 0.25f, insetLowerLeftY,
                        insetLowerLeftX, insetLowerLeftY + insetheight * 0.25f, insetLowerLeftX,
                        insetLowerLeftY + insetheight * 0.5f);
            }
            appearanceContent.setNonStrokingColor(GRAY);

            if (null != a.getColor() && 0 < borderWidth) {
                appearanceContent.setStrokingColor(a.getColor());
                appearanceContent.fillAndStroke();
            } else {
                appearanceContent.fill();

            }

            if (hasContents) {
                appearanceContent.moveTo(0, 0);
                appearanceContent.beginText();

                // Center text vertically, left justified inside border with margin
                appearanceContent.newLineAtOffset(lowerLeftX + borderWidth + margin,
                        lowerLeftY + (height + LINE_SPACE_SIZE_PDF_POINTS) * 0.5f - textHeight * 0.5f);
                appearanceContent.setFont(FONT, fontSize);
                appearanceContent.setNonStrokingColor(BLACK); // Sets color of text
                appearanceContent.showText(a.getContents());
                appearanceContent.endText();
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(AnnotationGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }

    return annotationAppearanceStream;
}

From source file:airviewer.BoxAnnotationMaker.java

License:Apache License

/**
 *
 * @param document//w  ww  .ja v  a  2 s .co m
 * @param arguments(lowerLeftX, lowerLeftY, width, height)
 * @return
 */
public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) {
    assert null != arguments && arguments.size() == 5;
    assert null != document;

    List<PDAnnotation> result;

    try {
        int pageNumber = parseInt(arguments.get(0));
        float lowerLeftX = parseFloat(arguments.get(1));
        float lowerLeftY = parseFloat(arguments.get(2));
        float width = parseFloat(arguments.get(3));
        float height = parseFloat(arguments.get(4));
        String contents = "";
        PDFont font = PDType1Font.HELVETICA_OBLIQUE;
        float fontSize = 16; // Or whatever font size you want.
        //float textWidth = font.getStringWidth(contents) * fontSize / 1000.0f;
        //float textHeight = 32;

        try {
            PDPage page = document.getPage(pageNumber);
            PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE);
            PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary();
            borderThick.setWidth(72 / 12); // 12th inch
            PDRectangle position = new PDRectangle();
            position.setLowerLeftX(lowerLeftX);
            position.setLowerLeftY(lowerLeftY);
            position.setUpperRightX(lowerLeftX + width);
            position.setUpperRightY(lowerLeftY + height);

            PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle(
                    PDAnnotationSquareCircle.SUB_TYPE_SQUARE);
            aSquare.setAnnotationName(new UID().toString());
            aSquare.setContents(contents);
            aSquare.setColor(red); // Outline in red, not setting a fill
            PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE);
            aSquare.setInteriorColor(fillColor);
            aSquare.setBorderStyle(borderThick);
            aSquare.setRectangle(position);
            result = new ArrayList<>(page.getAnnotations()); // copy
            page.getAnnotations().add(aSquare);

            // The following lines are needed for PDFRenderer to render 
            // annotations. Preview and Acrobat don't seem to need these.
            if (null == aSquare.getAppearance()) {
                aSquare.setAppearance(new PDAppearanceDictionary());
                PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document);
                position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f);
                position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f);
                position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f);
                position.setUpperRightY(lowerLeftY + height + borderThick.getWidth() * 0.5f);
                annotationAppearanceStream.setBBox(position);
                annotationAppearanceStream.setMatrix(new AffineTransform());
                annotationAppearanceStream.setResources(page.getResources());

                try (PDPageContentStream appearanceContent = new PDPageContentStream(document,
                        annotationAppearanceStream)) {
                    Matrix transform = new Matrix();
                    appearanceContent.transform(transform);
                    appearanceContent.addRect(lowerLeftX, lowerLeftY, width, height);
                    appearanceContent.setLineWidth(borderThick.getWidth());
                    appearanceContent.setNonStrokingColor(fillColor);
                    appearanceContent.setStrokingColor(red);
                    appearanceContent.fillAndStroke();
                    appearanceContent.beginText();

                    // Center text vertically, left justified
                    appearanceContent.newLineAtOffset(lowerLeftX, lowerLeftY + height * 0.5f - fontSize * 0.5f);
                    appearanceContent.setFont(font, fontSize);
                    appearanceContent.setNonStrokingColor(red);
                    appearanceContent.showText(contents);
                    appearanceContent.endText();
                }
                aSquare.getAppearance().setNormalAppearance(annotationAppearanceStream);
            }
            //System.out.println(page.getAnnotations().toString());

        } catch (IOException ex) {
            Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex);
            result = null;
        }
    } catch (NumberFormatException | NullPointerException ex) {
        System.err.println("\tNon number encountered where floating point number expected.");
        result = null;
    }

    return result;
}

From source file:airviewer.EllipseAnnotationMaker.java

License:Apache License

/**
 * //from  w  w w  .  j av a 2s.  c o m
 * @param document
 * @param arguments(pageNumber, lowerLeftX, lowerLeftY, width, height, contents)
 * @return 
 */
public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) {
    assert null != arguments && arguments.size() == 6;
    assert null != document;

    List<PDAnnotation> result;

    try {
        int pageNumber = parseInt(arguments.get(0));
        float lowerLeftX = parseFloat(arguments.get(1));
        float lowerLeftY = parseFloat(arguments.get(2));
        float width = parseFloat(arguments.get(3));
        float height = parseFloat(arguments.get(4));
        String contents = arguments.get(5);

        PDFont font = PDType1Font.HELVETICA_OBLIQUE;
        final float fontSize = 16.0f; // Or whatever font size you want.
        //final float lineSpacing = 4.0f;
        width = max(width, font.getStringWidth(contents) * fontSize / 1000.0f);
        //final float textHeight = fontSize + lineSpacing;

        try {
            PDPage page = document.getPage(pageNumber);
            PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE);
            PDColor black = new PDColor(new float[] { 0, 0, 0 }, PDDeviceRGB.INSTANCE);
            PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary();
            borderThick.setWidth(72 / 12); // 12th inch
            PDRectangle position = new PDRectangle();
            position.setLowerLeftX(lowerLeftX);
            position.setLowerLeftY(lowerLeftY);
            position.setUpperRightX(lowerLeftX + width);
            position.setUpperRightY(lowerLeftY + height);

            PDAnnotationSquareCircle aCircle = new PDAnnotationSquareCircle(
                    PDAnnotationSquareCircle.SUB_TYPE_CIRCLE);
            aCircle.setAnnotationName(new UID().toString());
            aCircle.setContents(contents);
            PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE);
            aCircle.setInteriorColor(fillColor);
            aCircle.setColor(red);
            aCircle.setBorderStyle(borderThick);
            aCircle.setRectangle(position);

            result = new ArrayList<>(page.getAnnotations()); // Copy
            page.getAnnotations().add(aCircle);

            // The following lines are needed for PDFRenderer to render 
            // annotations. Preview and Acrobat don't seem to need these.
            if (null == aCircle.getAppearance()) {
                aCircle.setAppearance(new PDAppearanceDictionary());
                PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document);
                position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f);
                position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f);
                position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f);
                position.setUpperRightY(lowerLeftY + height + borderThick.getWidth() * 0.5f);
                annotationAppearanceStream.setBBox(position);
                annotationAppearanceStream.setMatrix(new AffineTransform());
                annotationAppearanceStream.setResources(page.getResources());

                try (PDPageContentStream appearanceContent = new PDPageContentStream(document,
                        annotationAppearanceStream)) {
                    Matrix transform = new Matrix();
                    appearanceContent.transform(transform);
                    appearanceContent.moveTo(lowerLeftX, lowerLeftY + height * 0.5f);
                    appearanceContent.curveTo(lowerLeftX, lowerLeftY + height * 0.75f,
                            lowerLeftX + width * 0.25f, lowerLeftY + height, lowerLeftX + width * 0.5f,
                            lowerLeftY + height);
                    appearanceContent.curveTo(lowerLeftX + width * 0.75f, lowerLeftY + height,
                            lowerLeftX + width, lowerLeftY + height * 0.75f, lowerLeftX + width,
                            lowerLeftY + height * 0.5f);
                    appearanceContent.curveTo(lowerLeftX + width, lowerLeftY + height * 0.25f,
                            lowerLeftX + width * 0.75f, lowerLeftY, lowerLeftX + width * 0.5f, lowerLeftY);
                    appearanceContent.curveTo(lowerLeftX + width * 0.25f, lowerLeftY, lowerLeftX,
                            lowerLeftY + height * 0.25f, lowerLeftX, lowerLeftY + height * 0.5f);
                    appearanceContent.setLineWidth(borderThick.getWidth());
                    appearanceContent.setNonStrokingColor(fillColor);
                    appearanceContent.setStrokingColor(red);
                    appearanceContent.fillAndStroke();
                    appearanceContent.moveTo(0, 0);

                    appearanceContent.beginText();
                    appearanceContent.setNonStrokingColor(black);
                    // Center text vertically, left justified
                    appearanceContent.newLineAtOffset(lowerLeftX + borderThick.getWidth(),
                            lowerLeftY + height * 0.5f - fontSize * 0.5f);
                    appearanceContent.setFont(font, fontSize);
                    appearanceContent.showText(contents);
                    appearanceContent.endText();
                }
                aCircle.getAppearance().setNormalAppearance(annotationAppearanceStream);
            }

        } catch (IOException ex) {
            Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex);
            result = null;
        }
    } catch (NumberFormatException | NullPointerException ex) {
        System.err.println("Non number encountered where floating point number expected.");
        result = null;
    } catch (IOException ex) {
        Logger.getLogger(EllipseAnnotationMaker.class.getName()).log(Level.SEVERE, null, ex);
        result = null;
    }

    return result;
}

From source file:airviewer.TextAnnotationMaker.java

License:Apache License

/**
 * /*from   w ww. j av a2 s .com*/
 * @param document
 * @param arguments(pageNumber, lowerLeftX, lowerLeftY);
        
    String contents 
 * @return 
 */
public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) {
    assert null != arguments && arguments.size() == 4;
    assert null != document;

    List<PDAnnotation> result;

    try {
        int pageNumber = parseInt(arguments.get(0));
        float lowerLeftX = parseFloat(arguments.get(1));
        float lowerLeftY = parseFloat(arguments.get(2));

        String contents = arguments.get(3);
        PDFont font = PDType1Font.HELVETICA_OBLIQUE;
        final float fontSize = 16.0f; // Or whatever font size you want.
        final float lineSpacing = 4.0f;
        float width = font.getStringWidth(contents) * fontSize / 1000.0f; // font.getStringWidth(contents) returns thousanths of PS point
        final float textHeight = fontSize + lineSpacing;

        try {
            PDPage page = document.getPage(pageNumber);
            PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE);
            PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary();
            borderThick.setWidth(72 / 12); // 12th inch
            PDRectangle position = new PDRectangle();
            position.setLowerLeftX(lowerLeftX);
            position.setLowerLeftY(lowerLeftY);
            position.setUpperRightX(lowerLeftX + width);
            position.setUpperRightY(lowerLeftY + textHeight);

            PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle(
                    PDAnnotationSquareCircle.SUB_TYPE_SQUARE);
            aSquare.setAnnotationName(new UID().toString());
            aSquare.setContents(contents);
            PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE);
            aSquare.setInteriorColor(fillColor);
            aSquare.setRectangle(position);
            result = new ArrayList<>(page.getAnnotations()); // copy
            page.getAnnotations().add(aSquare);

            // The following lines are needed for PDFRenderer to render 
            // annotations. Preview and Acrobat don't seem to need these.
            if (null == aSquare.getAppearance()) {
                aSquare.setAppearance(new PDAppearanceDictionary());
                PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document);
                position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f);
                position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f);
                position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f);
                position.setUpperRightY(lowerLeftY + textHeight + borderThick.getWidth() * 0.5f);
                annotationAppearanceStream.setBBox(position);
                annotationAppearanceStream.setMatrix(new AffineTransform());
                annotationAppearanceStream.setResources(page.getResources());

                try (PDPageContentStream appearanceContent = new PDPageContentStream(document,
                        annotationAppearanceStream)) {
                    Matrix transform = new Matrix();
                    appearanceContent.transform(transform);
                    appearanceContent.addRect(lowerLeftX, lowerLeftY, width, textHeight);
                    appearanceContent.setNonStrokingColor(fillColor);
                    appearanceContent.fill();
                    appearanceContent.beginText();

                    // Center text vertically, left justified
                    appearanceContent.newLineAtOffset(lowerLeftX,
                            lowerLeftY + textHeight * 0.5f - fontSize * 0.5f);
                    appearanceContent.setFont(font, fontSize);
                    appearanceContent.setNonStrokingColor(red);
                    appearanceContent.showText(contents);
                    appearanceContent.endText();
                }
                aSquare.getAppearance().setNormalAppearance(annotationAppearanceStream);
            }
            //System.out.println(page.getAnnotations().toString());

        } catch (IOException ex) {
            Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex);
            result = null;
        }
    } catch (NumberFormatException | NullPointerException ex) {
        System.err.println("Non number encountered where floating point number expected.");
        result = null;
    } catch (IOException ex) {
        Logger.getLogger(TextAnnotationMaker.class.getName()).log(Level.SEVERE, null, ex);
        result = null;
    }

    return result;
}

From source file:ambroafb.general.PDFHelper.java

public void replace(BufferedImage img, int index) throws IOException {
    PDPage old = doc.getPage(index);//  w  w  w  . j a va  2 s  .  c  o m
    float width, height;
    if (img.getWidth() > img.getHeight()) {
        width = PDRectangle.LETTER.getHeight();
        height = PDRectangle.LETTER.getWidth();
    } else {
        height = PDRectangle.LETTER.getHeight();
        width = PDRectangle.LETTER.getWidth();
    }
    PDPage newPage = new PDPage(new PDRectangle(width, height));
    doc.getPages().insertAfter(newPage, old);
    doc.removePage(old);
    PDImageXObject pdImage = JPEGFactory.createFromImage(doc, img);
    try (PDPageContentStream contents = new PDPageContentStream(doc, newPage)) {
        contents.drawImage(pdImage, 0, 0, width, height);
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsVisualSignatureBuilder.java

License:EUPL

public void createInnerFormStreamPdfAs(PDDocument template, PDDocument origDoc) throws PdfAsException {
    try {/*from   w  w w  .j  a va2 s.  co m*/

        // Hint we have to create all PDXObjectImages before creating the
        // PDPageContentStream
        // only PDFbox developers know why ...
        // if (getStructure().getPage().getResources() != null) {
        // innerFormResources = getStructure().getPage().getResources();
        // } else {
        innerFormResources = new PDResources();
        getStructure().getPage().setResources(innerFormResources);
        // }
        readTableResources(properties.getMainTable(), template);

        PDPageContentStream stream = new PDPageContentStream(template, getStructure().getPage());
        // stream.setFont(PDType1Font.COURIER, 5);
        TableDrawUtils.drawTable(getStructure().getPage(), stream, 1, 1, designer.getWidth(),
                designer.getHeight(), properties.getMainTable(), template, false, innerFormResources, images,
                settings, this, properties);
        stream.close();
        PDStream innterFormStream = new PDStream(template, getStructure().getPage().getContents());

        getStructure().setInnterFormStream(innterFormStream);
        logger.debug("Strean of another form (inner form - it would be inside holder form) has been created");

    } catch (Throwable e) {
        logger.warn("Failed to create visual signature block", e);
        throw new PdfAsException("Failed to create visual signature block", e);
    }
}

From source file:blankpdf.BlankPDF.java

public void TestePDF() {
    String fileName = "Sparta.pdf"; // name of our file

    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();

    doc.addPage(page);/*from  www  . ja  v  a 2 s . c  om*/
    PDImageXObject imagem;
    PDPageContentStream content;
    try {
        content = new PDPageContentStream(doc, page);

        //OBSERVAO IMPORTANTE --
        //Para funcionar sem tratamento de string criar o projeto em pasta sem caracteres
        //especiais nem ESPAO EM BRANCO
        imagem = PDImageXObject.createFromFile(getClass().getResource("sparta.png").getPath(), doc);
        ///Users/marcelosiedler/Google%20Drive/bage/2016_02/BlankPDF/build/classes/blankpdf/silviosantos.jpg
        //imagem = PDImageXObject.createFromFile("/Users/marcelosiedler/Google Drive/bage/2016_02/BlankPDF/build/classes/blankpdf/sparta.png", doc);

        content.beginText();
        content.setFont(PDType1Font.TIMES_BOLD, 26);
        content.newLineAtOffset(10, 750);
        content.showText("Gincana IFSUL2");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.TIMES_BOLD, 16);
        content.newLineAtOffset(80, 700);
        content.showText("Turma : ");
        content.endText();

        content.drawImage(imagem, 75, 500);

        content.close();
        doc.save(fileName);
        doc.close();

        System.out.println("Arquivo criado em : " + System.getProperty("user.dir"));

    } catch (Exception e) {

        System.out.println(e.getMessage());

    }

}