Example usage for org.apache.pdfbox.pdmodel.font PDType1Font HELVETICA

List of usage examples for org.apache.pdfbox.pdmodel.font PDType1Font HELVETICA

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.font PDType1Font HELVETICA.

Prototype

PDType1Font HELVETICA

To view the source code for org.apache.pdfbox.pdmodel.font PDType1Font HELVETICA.

Click Source Link

Usage

From source file:mail.java

private void ImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ImprimirActionPerformed
    try {//  w ww  .  j a v  a2 s  .c  om
        // 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  .jav  a2 s  .  c  om
    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:TestPdfLayoutMgr.java

License:Apache License

@Test
public void testPdf() throws IOException, COSVisitorException {
    // Nothing happens without a PdfLayoutMgr.
    PdfLayoutMgr pageMgr = PdfLayoutMgr.newRgbPageMgr();

    // One inch is 72 document units.  40 is about a half-inch - enough margin to satisfy most
    // printers. A typical monitor has 72 dots per inch, so you can think of these as pixels
    // even though they aren't.  Things can be aligned right, center, top, or anywhere within
    // a "pixel".
    final float pMargin = 40;

    // A LogicalPage is a group of pages with the same settings.  When your contents scroll off
    // the bottom of a page, a new page is automatically created for you with the settings taken
    // from the LogicPage grouping. If you don't want a new page, be sure to stay within the
    // bounds of the current one!
    LogicalPage lp = pageMgr.logicalPageStart();

    // Set up some useful constants for later.
    final float tableWidth = lp.pageWidth() - (2 * pMargin);
    final float pageRMargin = pMargin + tableWidth;
    final float colWidth = tableWidth / 4f;
    final float[] colWidths = new float[] { colWidth + 10, colWidth + 10, colWidth + 10, colWidth - 30 };
    final Padding textCellPadding = Padding.of(2f);

    // Set up some useful styles for later
    final TextStyle heading = TextStyle.of(PDType1Font.HELVETICA_BOLD, 9.5f, WHITE);
    final CellStyle headingCell = CellStyle.of(BOTTOM_CENTER, textCellPadding, BLUE,
            BorderStyle.builder().left(LineStyle.of(BLUE)).right(LineStyle.of(WHITE)).build());
    final CellStyle headingCellR = CellStyle.of(BOTTOM_CENTER, textCellPadding, BLACK,
            BorderStyle.builder().left(LineStyle.of(WHITE)).right(LineStyle.of(BLACK)).build());

    final TextStyle regular = TextStyle.of(PDType1Font.HELVETICA, 9.5f, BLACK);
    final CellStyle regularCell = CellStyle.of(TOP_LEFT, textCellPadding, null, BorderStyle.builder()
            .left(LineStyle.of(BLACK)).right(LineStyle.of(BLACK)).bottom(LineStyle.of(BLACK)).build());

    // Let's draw three tables on our first landscape-style page grouping.

    // Draw the first table with lots of extra room to show off the vertical and horizontal
    // alignment.
    XyOffset xya = lp.tableBuilder(XyOffset.of(40f, lp.yPageTop())).addCellWidths(vec(120f, 120f, 120f))
            .textStyle(TextStyle.of(PDType1Font.COURIER_BOLD_OBLIQUE, 12f, YELLOW.brighter())).partBuilder()
            .cellStyle(CellStyle.of(BOTTOM_CENTER, Padding.of(2), decode("#3366cc"), BorderStyle.of(BLACK)))
            .rowBuilder().addTextCells("First", "Second", "Third").buildRow().buildPart().partBuilder()
            .cellStyle(CellStyle.of(MIDDLE_CENTER, Padding.of(2), decode("#ccffcc"), BorderStyle.of(DARK_GRAY)))
            .minRowHeight(120f).textStyle(TextStyle.of(PDType1Font.COURIER, 12f, BLACK)).rowBuilder()
            .cellBuilder().align(TOP_LEFT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(TOP_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(TOP_RIGHT).add("Line 1", "Line two", "Line three").buildCell().buildRow().rowBuilder()
            .cellBuilder().align(MIDDLE_LEFT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(MIDDLE_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(MIDDLE_RIGHT).add("Line 1", "Line two", "Line three").buildCell().buildRow().rowBuilder()
            .cellBuilder().align(BOTTOM_LEFT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(BOTTOM_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(BOTTOM_RIGHT).add("Line 1", "Line two", "Line three").buildCell().buildRow().buildPart()
            .buildTable();/*from w  w  w  .jav a2s .  c o m*/

    // The second table uses the x and y offsets from the previous table to position it to the
    // right of the first.
    XyOffset xyb = lp.tableBuilder(XyOffset.of(xya.x() + 10, lp.yPageTop()))
            .addCellWidths(vec(100f, 100f, 100f))
            .textStyle(TextStyle.of(PDType1Font.COURIER_BOLD_OBLIQUE, 12f, YELLOW.brighter())).partBuilder()
            .cellStyle(CellStyle.of(BOTTOM_CENTER, Padding.of(2), decode("#3366cc"), BorderStyle.of(BLACK)))
            .rowBuilder().addTextCells("First", "Second", "Third").buildRow().buildPart().partBuilder()
            .cellStyle(CellStyle.of(MIDDLE_CENTER, Padding.of(2), decode("#ccffcc"), BorderStyle.of(DARK_GRAY)))
            .minRowHeight(100f).textStyle(TextStyle.of(PDType1Font.COURIER, 12f, BLACK)).rowBuilder()
            .cellBuilder().align(BOTTOM_RIGHT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(BOTTOM_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(BOTTOM_LEFT).add("Line 1", "Line two", "Line three").buildCell().buildRow().rowBuilder()
            .cellBuilder().align(MIDDLE_RIGHT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(MIDDLE_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(MIDDLE_LEFT).add("Line 1", "Line two", "Line three").buildCell().buildRow().rowBuilder()
            .cellBuilder().align(TOP_RIGHT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(TOP_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder().align(TOP_LEFT)
            .add("Line 1", "Line two", "Line three").buildCell().buildRow().buildPart().buildTable();

    // The third table uses the x and y offsets from the previous tables to position it to the
    // right of the first and below the second.  Negative Y is down.  This third table showcases
    // the way cells extend vertically (but not horizontally) to fit the text you put in them.
    lp.tableBuilder(XyOffset.of(xya.x() + 10, xyb.y() - 10)).addCellWidths(vec(100f, 100f, 100f))
            .textStyle(TextStyle.of(PDType1Font.COURIER_BOLD_OBLIQUE, 12f, YELLOW.brighter())).partBuilder()
            .cellStyle(CellStyle.of(BOTTOM_CENTER, Padding.of(2), decode("#3366cc"), BorderStyle.of(BLACK)))
            .rowBuilder().addTextCells("First", "Second", "Third").buildRow().buildPart().partBuilder()
            .cellStyle(CellStyle.of(MIDDLE_CENTER, Padding.of(2), decode("#ccffcc"), BorderStyle.of(DARK_GRAY)))
            .textStyle(TextStyle.of(PDType1Font.COURIER, 12f, BLACK)).rowBuilder().cellBuilder()
            .align(BOTTOM_RIGHT).add("Line 1").buildCell().cellBuilder().align(BOTTOM_CENTER)
            .add("Line 1", "Line two").buildCell().cellBuilder().align(BOTTOM_LEFT)
            .add("Line 1", "Line two", "[Line three is long enough to wrap]").buildCell().buildRow()
            .rowBuilder().cellBuilder().align(MIDDLE_RIGHT).add("Line 1", "Line two").buildCell().cellBuilder()
            .align(MIDDLE_CENTER).add("").buildCell().cellBuilder().align(MIDDLE_LEFT).add("Line 1").buildCell()
            .buildRow().rowBuilder().cellBuilder().align(TOP_RIGHT).add("L1").buildCell().cellBuilder()
            .align(TOP_CENTER).add("Line 1", "Line two").buildCell().cellBuilder().align(TOP_LEFT).add("Line 1")
            .buildCell().buildRow().buildPart().buildTable();

    lp.commit();

    // Let's do a portrait page now.  I just copied this from the previous page.
    lp = pageMgr.logicalPageStart(LogicalPage.Orientation.PORTRAIT);
    lp.tableBuilder(XyOffset.of(40f, lp.yPageTop())).addCellWidths(vec(120f, 120f, 120f))
            .textStyle(TextStyle.of(PDType1Font.COURIER_BOLD_OBLIQUE, 12f, YELLOW.brighter())).partBuilder()
            .cellStyle(CellStyle.of(BOTTOM_CENTER, Padding.of(2), decode("#3366cc"), BorderStyle.of(BLACK)))
            .rowBuilder().addTextCells("First", "Second", "Third").buildRow().buildPart().partBuilder()
            .cellStyle(CellStyle.of(MIDDLE_CENTER, Padding.of(2), decode("#ccffcc"), BorderStyle.of(DARK_GRAY)))
            .minRowHeight(120f).textStyle(TextStyle.of(PDType1Font.COURIER, 12f, BLACK)).rowBuilder()
            .cellBuilder().align(TOP_LEFT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(TOP_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(TOP_RIGHT).add("Line 1", "Line two", "Line three").buildCell().buildRow().rowBuilder()
            .cellBuilder().align(MIDDLE_LEFT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(MIDDLE_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(MIDDLE_RIGHT).add("Line 1", "Line two", "Line three").buildCell().buildRow().rowBuilder()
            .cellBuilder().align(BOTTOM_LEFT).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(BOTTOM_CENTER).add("Line 1", "Line two", "Line three").buildCell().cellBuilder()
            .align(BOTTOM_RIGHT).add("Line 1", "Line two", "Line three").buildCell().buildRow().buildPart()
            .buildTable();

    // Where's the lower-right-hand corner?  Put a cell there.
    lp.tableBuilder(XyOffset.of(lp.pageWidth() - (100 + pMargin), lp.yPageBottom() + 15 + pMargin))
            .addCellWidths(vec(100f))
            .textStyle(TextStyle.of(PDType1Font.COURIER_BOLD_OBLIQUE, 12f, YELLOW.brighter())).partBuilder()
            .cellStyle(CellStyle.of(MIDDLE_CENTER, Padding.of(2), decode("#3366cc"), BorderStyle.of(BLACK)))
            .rowBuilder().addTextCells("Lower-Right").buildRow().buildPart().buildTable();

    lp.commit();

    // More landscape pages
    lp = pageMgr.logicalPageStart();
    TextStyle pageHeadTextStyle = TextStyle.of(PDType1Font.HELVETICA, 7f, BLACK);
    CellStyle pageHeadCellStyle = CellStyle.of(TOP_CENTER, null, null, null);

    lp.putCellAsHeaderFooter(pMargin, lp.yPageTop() + 10,
            Cell.of(pageHeadCellStyle, tableWidth, pageHeadTextStyle, "Test Logical Page Three"));

    //        y = pageMgr.putRect(XyPair.of(pMargin, y), XyPair.of(100f,100f), Color.BLUE).y();

    // We're going to reset and reuse this y variable.
    float y = lp.yPageTop();

    y = lp.putRow(pMargin, y,
            Cell.of(headingCell, colWidths[0], heading,
                    "Transliterated Russian (with un-transliterated Chinese below)"),
            Cell.of(headingCellR, colWidths[1], heading, "US English"),
            Cell.of(headingCellR, colWidths[2], heading, "Finnish"),
            Cell.of(headingCellR, colWidths[3], heading, "German"));

    File f = new File("target/test-classes/melon.jpg");
    System.out.println(f.getAbsolutePath());
    BufferedImage melonPic = ImageIO.read(f);

    y = lp.putRow(pMargin, y, Cell.builder(regularCell, colWidths[0]).add(regular, vec(
            "???  ???  ,",
            "???  ?  ?.",
            "? ?, ? ? ",
            " ??  ? !", null, "Chorus:", null,
            "??, ?  ?, ?  ?"
                    + " ,  ? ? ?! ??, ?!"
                    + "  ?? !",
            null,
            "    ? ? ??  ? "
                    + " ?.    ?!   ?  ?  "
                    + "? ?!",
            null, "Chorus:", null, " ? ?   ? ",
            "?   .",
            "? ?   ? .",
            " ,  ?    ?!", null, "Chorus", null, null,
            null,
            "Chinese will not print.  The substitution character is a"
                    + " bullet, so below should be lots of bullets.",
            null,
            "???? " + "?? "
                    + "??? " + "??? "
                    + "??? " + "? "
                    + "??? " + "??? "
                    + "?????",
            null,
            "Here is a picture with the default and other sizes.  Though"
                    + " it shows up several times, the image data is only attached"
                    + " to the file once and reused."))
            .add(ScaledJpeg.of(melonPic), ScaledJpeg.of(melonPic, 50, 50), ScaledJpeg.of(melonPic, 50, 50),
                    ScaledJpeg.of(melonPic, 170, 100))
            .build(),
            Cell.builder(regularCell, colWidths[1]).add(regular,
                    // Flowing text
                    vec("O say can you see by the dawn's early light, "
                            + "What so proudly we hailed at the twilight's last gleaming, "
                            + "Whose broad stripes and bright stars " + "through the perilous fight, "
                            + "O'er the ramparts we watched, were so gallantly streaming? "
                            + "And the rockets' red glare, the bombs bursting in air, "
                            + "Gave proof through the night that our flag was still there; "
                            + "O say does that star-spangled banner yet wave, "
                            + "O'er the land of the free and the home of the brave? ",
                            // Tiny space
                            null,
                            // Set line breaks:
                            "On the shore dimly seen through the mists of the deep, ",
                            "Where the foe's haughty host in dread silence reposes, ",
                            "What is that which the breeze, o'er the towering steep, ",
                            "As it fitfully blows, half conceals, half discloses? ",
                            "Now it catches the gleam of the morning's first beam, ",
                            "In full glory reflected now shines in the stream: ",
                            "'Tis the star-spangled banner, O! long may it wave ",
                            "O'er the land of the free and the home of the brave. ",
                            // Big space.
                            null, null, null, null, null, null, null, null,
                            // Flowing text
                            "And where is that band who so vauntingly swore "
                                    + "That the havoc of war and the battle's confusion, "
                                    + "A home and a country, should leave us no more? "
                                    + "Their blood has washed out their foul footsteps' pollution. "
                                    + "No refuge could save the hireling and slave "
                                    + "From the terror of flight, or the gloom of the grave: "
                                    + "And the star-spangled banner in triumph doth wave, "
                                    + "O'er the land of the free and the home of the brave. " + null,
                            "O thus be it ever, when freemen shall stand "
                                    + "Between their loved home and the war's desolation. "
                                    + "Blest with vict'ry and peace, may the Heav'n rescued land "
                                    + "Praise the Power that hath made and preserved us a nation! "
                                    + "Then conquer we must, when our cause it is just, "
                                    + "And this be our motto: \"In God is our trust.\" "
                                    + "And the star-spangled banner in triumph shall wave "
                                    + "O'er the land of the free and the home of the brave!"))
                    .build(),
            Cell.builder(regularCell, colWidths[2]).add(regular, vec("Maamme", null,
                    "Monument to the Vrt Land poem in Helsinki. " + "Oi maamme, Suomi, synnyinmaa, "
                            + "soi, sana kultainen! " + "Ei laaksoa, ei kukkulaa, "
                            + "ei vett, rantaa rakkaampaa " + "kuin kotimaa t pohjoinen, "
                            + "maa kallis isien. " + "Sun kukoistukses kuorestaan " + "kerrankin puhkeaa; "
                            + "viel' lempemme saa nousemaan " + "sun toivos, riemus loistossaan, "
                            + "ja kerran laulus, synnyinmaa " + "korkeemman kaiun saa. ",
                    null, "Vrt land ", null,
                    "(the original, by Johan Ludvig Runeberg) " + "Vrt land, vrt land, vrt fosterland, "
                            + "ljud hgt, o dyra ord! " + "Ej lyfts en hjd mot himlens rand, "
                            + "ej snks en dal, ej skljs en strand, " + "mer lskad n vr bygd i nord, "
                            + "n vra fders jord! " + "Din blomning, sluten n i knopp, "
                            + "Skall mogna ur sitt tvng; " + "Se, ur vr krlek skall g opp "
                            + "Ditt ljus, din glans, din frjd, ditt hopp. "
                            + "Och hgre klinga skall en gng " + "Vr fosterlndska sng."))
                    .build(),
            Cell.builder(regularCell, colWidths[3]).add(regular, vec(// Older first 2 verses obsolete.
                    "Einigkeit und Recht und Freiheit " + "Fr das deutsche Vaterland! "
                            + "Danach lasst uns alle streben " + "Brderlich mit Herz und Hand! "
                            + "Einigkeit und Recht und Freiheit " + "Sind des Glckes Unterpfand;"
                            + "Blh' im Glanze dieses Glckes, " + "  Blhe, deutsches Vaterland!"))
                    .build());

    lp.putRow(pMargin, y, Cell.of(regularCell, colWidths[0], regular, "Another row of cells"),
            Cell.of(regularCell, colWidths[1], regular, "On the second page"),
            Cell.of(regularCell, colWidths[2], regular, "Just like any other page"),
            Cell.of(regularCell, colWidths[3], regular, "That's it!"));
    lp.commit();

    final LineStyle lineStyle = LineStyle.of(BLACK, 1);

    lp = pageMgr.logicalPageStart();

    lp.putCellAsHeaderFooter(pMargin, lp.yPageTop() + 10,
            Cell.of(pageHeadCellStyle, tableWidth, pageHeadTextStyle, "Test Logical Page Four"));

    // Make a big 3-page X in a box.  Notice that we code it as though it's on one page, and the
    // API adds two more pages as needed.  This is a great test for how geometric shapes break
    // across pages.

    // top lne
    lp.putLine(pMargin, lp.yPageTop(), pageRMargin, lp.yPageTop(), lineStyle);
    // left line
    lp.putLine(pMargin, lp.yPageTop(), pMargin, -lp.yPageTop(), lineStyle);
    // 3-page-long X
    lp.putLine(pMargin, lp.yPageTop(), pageRMargin, -lp.yPageTop(), lineStyle);
    // middle line
    lp.putLine(pMargin, 0, pageRMargin, 0, lineStyle);
    lp.putLine(pageRMargin, lp.yPageTop(), pMargin, -lp.yPageTop(), lineStyle);
    // right line
    lp.putLine(pageRMargin, lp.yPageTop(), pageRMargin, -lp.yPageTop(), lineStyle);
    // bottom line
    lp.putLine(pMargin, -lp.yPageTop(), pageRMargin, -lp.yPageTop(), lineStyle);
    lp.commit();

    // All done - write it out!

    // In a web application, this could be:
    //
    // httpServletResponse.setContentType("application/pdf") // your server may do this for you.
    // os = httpServletResponse.getOutputStream()            // you probably have to do this
    //
    // Also, in a web app, you probably want name your action something.pdf and put
    // target="_blank" on your link to the PDF download action.

    // We're just going to write to a file.
    OutputStream os = new FileOutputStream("test.pdf");

    // Commit it to the output stream!
    pageMgr.save(os);
}

From source file:at.asitplus.regkassen.core.modules.print.SimplePDFPrinterModule.java

License:Apache License

@Override
public byte[] printReceipt(final ReceiptPackage receiptPackage, final ReceiptPrintType receiptPrintType) {
    //TODO Training/Storno!
    try {/*from  www.j  a  v  a 2s . c om*/
        //init PDF document
        final PDDocument document = new PDDocument();
        final PDPage page = new PDPage(PDPage.PAGE_SIZE_A6);
        document.addPage(page);

        //init content objects
        final PDRectangle rect = page.getMediaBox();
        final PDPageContentStream cos = new PDPageContentStream(document, page);

        //add taxtype-sums
        int line = 1;
        //get string that will be encoded as QR-Code
        final String qrCodeRepresentation = CashBoxUtils.getQRCodeRepresentationFromJWSCompactRepresentation(
                receiptPackage.getJwsCompactRepresentation());

        addTaxTypeToPDF(cos, rect, line++,
                CashBoxUtils.getValueFromMachineCode(qrCodeRepresentation, MachineCodeValue.SUM_TAX_SET_NORMAL),
                TaxType.SATZ_NORMAL);
        addTaxTypeToPDF(cos, rect, line++, CashBoxUtils.getValueFromMachineCode(qrCodeRepresentation,
                MachineCodeValue.SUM_TAX_SET_ERMAESSIGT1), TaxType.SATZ_ERMAESSIGT_1);
        addTaxTypeToPDF(cos, rect, line++, CashBoxUtils.getValueFromMachineCode(qrCodeRepresentation,
                MachineCodeValue.SUM_TAX_SET_ERMAESSIGT2), TaxType.SATZ_ERMAESSIGT_2);
        addTaxTypeToPDF(cos, rect, line++, CashBoxUtils.getValueFromMachineCode(qrCodeRepresentation,
                MachineCodeValue.SUM_TAX_SET_BESONDERS), TaxType.SATZ_BESONDERS);
        addTaxTypeToPDF(cos, rect, line++,
                CashBoxUtils.getValueFromMachineCode(qrCodeRepresentation, MachineCodeValue.SUM_TAX_SET_NULL),
                TaxType.SATZ_NULL);

        final String signatureValue = CashBoxUtils.getValueFromMachineCode(qrCodeRepresentation,
                MachineCodeValue.SIGNATURE_VALUE);
        final String decodedSignatureValue = new String(CashBoxUtils.base64Decode(signatureValue, false));
        final boolean secDeviceWasDamaged = "Sicherheitseinrichtung ausgefallen".equals(decodedSignatureValue);
        if (secDeviceWasDamaged) {
            final PDFont fontPlain = PDType1Font.HELVETICA;
            cos.beginText();
            cos.setFont(fontPlain, 8);
            cos.moveTextPositionByAmount(20, rect.getHeight() - 20 * (line));
            cos.drawString("SICHERHEITSEINRICHTUNG AUSGEFALLEN");
            cos.endText();
            line++;
        }

        //add OCR code or QR-code
        if (receiptPrintType == ReceiptPrintType.OCR) {
            addOCRCodeToPDF(document, cos, rect, line++, receiptPackage);
        } else {
            //create QRCode
            final BufferedImage image = createQRCode(receiptPackage);
            //add QRCode to PDF document
            final PDXObjectImage ximage = new PDPixelMap(document, image);
            final float scale = 2f; // alter this value to set the image size
            cos.drawXObject(ximage, 25, 0, ximage.getWidth() * scale, ximage.getHeight() * scale);
        }
        cos.close();

        final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        document.save(bOut);
        document.close();
        return bOut.toByteArray();

    } catch (final IOException e) {
        e.printStackTrace();
    } catch (final COSVisitorException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:at.asitplus.regkassen.core.modules.print.SimplePDFPrinterModule.java

License:Apache License

protected void addTaxTypeToPDF(final PDPageContentStream cos, final PDRectangle rect, final int line,
        final String sum, final TaxType taxType) {
    final PDFont fontPlain = PDType1Font.HELVETICA;
    try {//w w  w .  j  ava 2  s .c om
        cos.beginText();
        cos.setFont(fontPlain, 8);
        cos.moveTextPositionByAmount(20, rect.getHeight() - 20 * (line));
        cos.drawString(taxType.getTaxTypeString() + ": " + sum);
        cos.endText();
    } catch (final IOException e) {
        e.printStackTrace();
    }
}

From source file:at.medevit.elexis.impfplan.ui.handlers.PrintVaccinationEntriesHandler.java

License:Open Source License

private void createPDF(Patient patient, Image image) throws IOException, COSVisitorException {
    PDDocumentInformation pdi = new PDDocumentInformation();
    Mandant mandant = (Mandant) ElexisEventDispatcher.getSelected(Mandant.class);
    pdi.setAuthor(mandant.getName() + " " + mandant.getVorname());
    pdi.setCreationDate(new GregorianCalendar());
    pdi.setTitle("Impfausweis " + patient.getLabel());

    PDDocument document = new PDDocument();
    document.setDocumentInformation(pdi);

    PDPage page = new PDPage();
    page.setMediaBox(PDPage.PAGE_SIZE_A4);
    document.addPage(page);/*from w w  w .j a va  2 s. c  om*/

    PDRectangle pageSize = page.findMediaBox();
    PDFont font = PDType1Font.HELVETICA_BOLD;

    PDFont subFont = PDType1Font.HELVETICA;

    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.beginText();
    contentStream.setFont(font, 14);
    contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 40);
    contentStream.drawString(patient.getLabel());
    contentStream.endText();

    String dateLabel = sdf.format(Calendar.getInstance().getTime());
    String title = Person.load(mandant.getId()).get(Person.TITLE);
    String mandantLabel = title + " " + mandant.getName() + " " + mandant.getVorname();
    contentStream.beginText();
    contentStream.setFont(subFont, 10);
    contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 55);
    contentStream.drawString("Ausstellung " + dateLabel + ", " + mandantLabel);
    contentStream.endText();

    BufferedImage imageAwt = convertToAWT(image.getImageData());

    PDXObjectImage pdPixelMap = new PDPixelMap(document, imageAwt);
    contentStream.drawXObject(pdPixelMap, 40, 30, pageSize.getWidth() - 80, pageSize.getHeight() - 100);
    contentStream.close();

    String outputPath = CoreHub.userCfg.get(PreferencePage.VAC_PDF_OUTPUTDIR,
            CoreHub.getWritableUserDir().getAbsolutePath());
    if (outputPath.equals(CoreHub.getWritableUserDir().getAbsolutePath())) {
        SWTHelper.showInfo("Kein Ausgabeverzeichnis definiert", "Ausgabe erfolgt in: " + outputPath
                + "\nDas Ausgabeverzeichnis kann unter Einstellungen\\Klinische Hilfsmittel\\Impfplan definiert werden.");
    }
    File outputDir = new File(outputPath);
    File pdf = new File(outputDir, "impfplan_" + patient.getPatCode() + ".pdf");
    document.save(pdf);
    document.close();
    Desktop.getDesktop().open(pdf);
}

From source file:at.oculus.teamf.technical.printing.Printer.java

License:Open Source License

/**
 * <h3>$print</h3>/*from   w  w  w  .ja  v  a 2 s .  c  om*/
 * <p/>
 * <b>Description:</b>
 * <p/>
 * This method prints the given parameters into a PDF-Document and opens the file with the standard program.
 * <p/>
 * <b>Parameter</b>
 *
 * @param title Is a string which will be printed as title in the PDF Document.
 * @param text Is a string which will be printed as message in the PDF Document.
 */
public void print(String title, String text) throws IOException, COSVisitorException {

    //creates a new PDDocument object
    PDDocument document = new PDDocument();
    //create a page to the document
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    //rectangle is for sizes (height and width) of page
    PDRectangle rectangle = page1.getMediaBox();
    //add page to document
    document.addPage(page1);

    //fonts for the document are implemented here
    PDFont fontPlain = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;

    //running variable to calculate which line you are in the document right now
    int line = 0;

    try {
        //create the content stream which will write into the document
        PDPageContentStream stream = new PDPageContentStream(document, page1);

        //always use all these lines for entering new text into the document
        //move textToPosition will set the cursor to the current position
        stream.beginText();
        stream.setFont(fontBold, 14);
        stream.moveTextPositionByAmount(SPACING_LEFT, rectangle.getHeight() - SPACING_TOP);
        stream.drawString(title + ":");
        stream.endText();

        //calculates the correct place and then writes the whole text into the PDF-Document
        int start = 0;
        int end = text.length();
        while (start < end) {
            String tobePrinted;
            if ((end - start) > MAX_CHARACTERS_PER_LINE) {
                int tempEnd = start + MAX_CHARACTERS_PER_LINE;
                while (text.charAt(tempEnd) != ' ') {
                    ++tempEnd;
                }
                tobePrinted = text.substring(start, start = ++tempEnd);

            } else {
                tobePrinted = text.substring(start);
                start = start + MAX_CHARACTERS_PER_LINE;
            }
            stream.beginText();
            stream.setFont(fontPlain, 12);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString(tobePrinted);
            stream.endText();

        }
        //print oculus image into pdf file
        BufferedImage awtImage = ImageIO
                .read(new File("/home/oculus/IdeaProjects/Oculus/Technical/src/res/oculus.JPG"));
        PDXObjectImage ximage = new PDPixelMap(document, awtImage);
        float scale = 0.3f; // alter this value to set the image size
        stream.drawXObject(ximage, 380, 780, ximage.getWidth() * scale, ximage.getHeight() * scale);

        //close stream afterwards
        stream.close();

        //save document and close document
        document.save(
                "/home/oculus/IdeaProjects/Oculus/Technical/src/at/oculus/teamf/technical/printing/output_files/"
                        + title + ".pdf");
        document.close();
        //open document with standard application for the file
        Desktop.getDesktop().open(new File(
                "/home/oculus/IdeaProjects/Oculus/Technical/src/at/oculus/teamf/technical/printing/output_files/"
                        + title + ".pdf"));
    } catch (IOException | COSVisitorException e) {
        throw e;
    }
}

From source file:at.oculus.teamf.technical.printing.Printer.java

License:Open Source License

/**
 * <h3>$printPrescription</h3>
 * <p/>//  ww  w.  j  a  va  2 s. c o  m
 * <b>Description:</b>
 * <p/>
 * This method prints the given parameters into a PDF-Document and opens the file with the standard program.
 * <p/>
 * <b>Parameter</b>
 *
 * @param iPrescription Is an Interface of a prescription from which all the information will be printed into
 *                      a PDF-File and then started with standard application from OS.
 */
public void printPrescription(IPrescription iPrescription, IDoctor iDoctor) throws COSVisitorException,
        IOException, CantGetPresciptionEntriesException, NoPrescriptionToPrintException {
    if (iPrescription == null) {
        throw new NoPrescriptionToPrintException();
    }

    //instantiate a new document, create a page and add the page to the document
    PDDocument document = new PDDocument();
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    PDRectangle rectangle = page1.getMediaBox();
    document.addPage(page1);

    //create fonts for the document
    PDFont fontPlain = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;

    //running variable to calculate current line
    int line = 0;

    try {
        //new Stream to print into the file
        PDPageContentStream stream = new PDPageContentStream(document, page1);

        //print header (headlining)
        stream.beginText();
        stream.setFont(fontBold, 14);
        stream.moveTextPositionByAmount(SPACING_LEFT, rectangle.getHeight() - SPACING_TOP);
        stream.drawString("Prescription:");
        stream.endText();

        //get patient to print data from
        IPatient iPatient = iPrescription.getPatient();

        //write data from patient
        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString(iPatient.getFirstName() + " " + iPatient.getLastName());
        stream.endText();

        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        /* -- Team D: Add check on null -- */
        stream.drawString(iPatient.getBirthDay() == null ? "" : iPatient.getBirthDay().toString());
        /* -- -- -- */
        stream.endText();

        if (iPatient.getStreet() != null) {
            stream.beginText();
            stream.setFont(fontPlain, 12);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString(iPatient.getStreet());
            stream.endText();
        }

        if ((iPatient.getPostalCode() != null) && (iPatient.getCity() != null)) {
            stream.beginText();
            stream.setFont(fontPlain, 12);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString(iPatient.getPostalCode() + ", " + iPatient.getCity());
            stream.endText();
        }

        //next row
        ++line;

        //write data from doctor
        stream.beginText();
        stream.setFont(fontBold, 14);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString("Prescription issued from doctor:");
        stream.endText();

        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString(iDoctor.getTitle() + " " + iDoctor.getFirstName() + " " + iDoctor.getLastName());
        stream.endText();

        //next row
        ++line;

        //print all the entries in the prescription
        if (iPrescription.getPrescriptionEntries().size() > 0) {
            stream.beginText();
            stream.setFont(fontBold, 14);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString("Prescription Entries:");
            stream.endText();
            for (IPrescriptionEntry entry : iPrescription.getPrescriptionEntries()) {
                stream.beginText();
                stream.setFont(fontPlain, 12);
                stream.moveTextPositionByAmount(SPACING_LEFT,
                        rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
                stream.drawString("ID: " + entry.getId() + ", " + entry.getMedicine());
                stream.endText();
            }
        }

        //print oculus image into pdf file
        //Not working
        /*BufferedImage awtImage = ImageIO.read(new File("oculus.JPG"));
        PDXObjectImage ximage = new PDPixelMap(document, awtImage);
        float scale = 0.3f; // alter this value to set the image size
        stream.drawXObject(ximage, 380, 780, ximage.getWidth() * scale, ximage.getHeight() * scale);*/

        //signature field

        ++line;
        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString("Doctor's Signature:");
        stream.endText();

        //print a line for signature field
        stream.setLineWidth(0.5f);
        stream.addLine(SPACING_LEFT, rectangle.getHeight() - LINE_HEIGHT * (line += 2) - SPACING_HEADER,
                SPACING_LEFT + 100, rectangle.getHeight() - LINE_HEIGHT * (line) - SPACING_HEADER);
        stream.closeAndStroke();

        //close the stream
        stream.close();

        //save the document and close it
        document.save("prescription.pdf"); //Todo: position from property file
        document.close();
        //open file with standard OS application
        Desktop.getDesktop().open(new File("prescription.pdf"));

        //Print file directly from standard printer (NOT SUPPORTED ON OCULUS-LINUX -- should be tested first!!!)
        //Desktop.getDesktop().print(new File("/home/oculus/IdeaProjects/Oculus/Technical/src/at/oculus/teamf/technical/printing/output_files/prescription.pdf"));
    } catch (COSVisitorException | CantGetPresciptionEntriesException | IOException e) {
        throw e;
    }
}

From source file:Bulletin.test.java

public static void test2() {
    try {/*from w ww  . j a  va  2  s  .  c  o m*/
        PDDocument document = new PDDocument();
        PDPage page = new PDPage(PDRectangle.A4);
        PDPageContentStream cos = null;
        try {
            cos = new PDPageContentStream(document, page);
        } catch (IOException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }

        float X = 501.4f;
        float Y = 556.0f;
        //            String text = "HALLO";
        //            String text = "HALLO#HOE#GAAT#HET";
        //            String text = "HALLO#HOE#GAAT";
        String text = "Non atteints";
        int rh = 10;

        cos.moveTo(X, Y - 50);
        cos.lineTo(X, Y + 50);
        cos.stroke();
        cos.moveTo(X - 50, Y);
        cos.lineTo(X + 50, Y);
        cos.stroke();

        cos.beginText();
        cos.setFont(PDType1Font.HELVETICA, 6);
        float dtw = 0.5f * getTextWidth(PDType1Font.HELVETICA, text, 6);
        float dth = 0.0f * getFontHeight(PDType1Font.HELVETICA, 6);
        int nbLines = text.split("#").length;

        Y += 0.5f * (nbLines - 1) * rh;

        for (String line : text.split("#")) {
            Matrix M = Matrix.getTranslateInstance(X, Y);
            M.concatenate(Matrix.getRotateInstance(Math.toRadians(0), 0, 0));
            M.concatenate(Matrix.getTranslateInstance(-dtw, -dth));
            cos.setTextMatrix(M);
            cos.showText(line);
            Y -= rh;
        }
        cos.close();
        document.addPage(page);
        document.save("/tmp/test.pdf");
        document.close();

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

From source file:cdiscisa.StreamUtil.java

private static void imprimirDC3_individual(Participante p, Curso c, String chkDC3Firmaa, String chkDC3Logoa,
            String savePath, Map<String, String> dosc, Map<String, String> abreviaturas) throws IOException {

        //JOptionPane.showMessageDialog(null, "entrando a imrpimir individual");
        PDDocument document;/*from   w  ww .  ja v  a2  s .c  om*/
        //BufferedInputStream file;
        InputStream file = null;

        try {
            file = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/DC3_blank.pdf");
            //file = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/DC3_base_firma.pdf");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Error al cargar el una forma DC3 \nfile: " + String.valueOf(file) + "\n" + ex.toString());
        }
        document = PDDocument.load(file);

        BufferedImage logo = null;
        BufferedImage firma = null;

        try {
            //logo = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/logo.png").getFile());
            logo = ImageIO.read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/logo.png"));
            //logo = StreamUtil.stream2file(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/logo.png"));
            if (c.capacitador.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaCoco.png").getFile());
                firma = ImageIO
                        .read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaCoco.png"));
            } else if (c.capacitador.equalsIgnoreCase("Manuel Anguiano Razn")) {
                firma = ImageIO.read(
                        cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaManuel.png"));
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaManuel.png").getFile());
            } else {
                firma = ImageIO
                        .read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaJorge.png"));
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaJorge.png").getFile());
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar la imagen del logo o la firma \nfile: "
                    + String.valueOf(logo) + "\n" + String.valueOf(firma) + "\n" + ex.toString());
        }

        PDImageXObject firmaObject = null;
        PDImageXObject logoObject = null;

        try {
            if (chkDC3Firmaa.equalsIgnoreCase("true")) {
                firmaObject = LosslessFactory.createFromImage(document, firma);
                //firmaObject = PDImageXObject.createFromFile(firma, document);
            }

            if (chkDC3Logoa.equalsIgnoreCase("true")) {
                logoObject = LosslessFactory.createFromImage(document, logo);
                //logoObject = PDImageXObject.createFromFile(logo, document);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al crear objetos de logo o firma \nfile: "
                    + String.valueOf(logoObject) + "\n" + String.valueOf(firmaObject) + "\n" + ex.toString());
        }

        PDPage page = (PDPage) document.getDocumentCatalog().getPages().get(0);
        PDFont helvetica = PDType1Font.HELVETICA_BOLD;
        PDFont helvetica_normal = PDType1Font.HELVETICA;
        PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);

        contentStream.beginText();
        contentStream.setFont(helvetica_normal, 13);
        contentStream.setNonStrokingColor(Color.BLACK);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 602));
        contentStream.showText(p.apellidos + " " + p.nombre);

        String temp;

        if (p.curp.length() > 18) {
            temp = p.curp.substring(0, 18);
        } else {
            temp = p.curp;
        }
        char[] curpArray = temp.toCharArray();
        float[] xPosition = { 32, 49, 63, 77, 92, (float) 106.5, 120, (float) 134.5, 149, 163, 177, (float) 191.5,
                205, 223, 241, 255, 269, 286 };

        float charWidth;

        for (int i = 0; i <= curpArray.length - 1; i++) {
            charWidth = helvetica_normal.getStringWidth(String.valueOf(curpArray[i])) / 1000 * 13;
            //System.out.println("Char " + i + " width: " + charWidth);

            float x = xPosition[i] - (charWidth / 2);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, x, 572));
            contentStream.showText(String.valueOf(curpArray[i]));
        }

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 548));
        contentStream.showText(p.area_puesto);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 486));
        if (c.walmart) {
            contentStream.showText("OPERADORA WALMART S DE RL DE CV");
        } else {
            contentStream.showText(c.nombre_empresa);
        }

        char[] rfc_emprea_array;

        if (c.walmart) {
            rfc_emprea_array = "OWM011023AWA".toCharArray();
        } else {
            rfc_emprea_array = c.rfc_empresa.toCharArray();
        }

        try {
            int j = 0;
            for (int i = 0; i <= rfc_emprea_array.length - 1; i++) {
                charWidth = helvetica_normal
                        .getStringWidth(String.valueOf(rfc_emprea_array[rfc_emprea_array.length - i - 1])) / 1000
                        * 13;
                //System.out.println("Char " + i + " width: " + charWidth);

                if (j == 3 || i == 9) {
                    j = j + 1;
                }
                float x = xPosition[xPosition.length - j - 4] - (charWidth / 2);
                contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, x, 458));
                contentStream.showText(String.valueOf(rfc_emprea_array[rfc_emprea_array.length - i - 1]));
                j = j + 1;
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "El RFC de la empresa esta mal formado. \n\nex.toString : " + ex.toString());
            return;
        }
        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 405));
        contentStream.showText(c.nombre_curso);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 381));
        contentStream.showText(c.horas_texto);

        //if (c.walmart){
        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 356));
        contentStream.showText("6000 SEGURIDAD");
        //} else{
        //    contentStream.setTextMatrix(new Matrix(1,0,0,1,30,356 ));           
        //    contentStream.showText(p.area_tematica);
        //}

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 30, 332));
        contentStream.showText(c.uCapacitadora);

        Calendar cal = Calendar.getInstance();
        cal.setTime(c.fecha_inicio);
        String month = String.format("%02d", cal.get(Calendar.MONTH) + 1);
        String year = String.format("%04d", cal.get(Calendar.YEAR));
        String day = String.format("%02d", cal.get(Calendar.DAY_OF_MONTH));

        String date = year + month + day;

        cal.setTime(c.fecha_termino);
        month = String.format("%02d", cal.get(Calendar.MONTH) + 1);
        year = String.format("%04d", cal.get(Calendar.YEAR));
        day = String.format("%02d", cal.get(Calendar.DAY_OF_MONTH));

        date = date + year + month + day;

        char[] date_array = date.toCharArray();
        float[] xPos = { 256, 272, 288, 304, 322, 343, 365, 386, 428, 447, 467, 486, 507, 528, 549, 570 };

        for (int i = 0; i <= date_array.length - 1; i++) {
            charWidth = helvetica_normal.getStringWidth(String.valueOf(date_array[i])) / 1000 * 13;
            //System.out.println("Char " + i + " width: " + charWidth);

            float x = xPos[i] - (charWidth / 2);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, x, 381));
            contentStream.showText(String.valueOf(date_array[i]));

        }

        charWidth = helvetica_normal.getStringWidth(p.area_tematica) / 1000 * 13;
        //System.out.println(p.area_tematica + " bold : " + charWidth);
        if (charWidth >= 255) {
            contentStream.setFont(helvetica_normal, 10);
            charWidth = helvetica_normal.getStringWidth(p.area_tematica) / 1000 * 10;
            //System.out.println(p.area_tematica + " : " + charWidth);
            if (charWidth >= 260) {
                contentStream.setFont(helvetica_normal, 8);
                //charWidth = helvetica_normal.getStringWidth(p.area_tematica) /1000 * 8;
                //System.out.println(p.area_tematica + " : " + charWidth);
            }
        }

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 310, 572));
        contentStream.showText(p.area_tematica);

        contentStream.endText();

        //xPosition = 256, 272, 288, 304, 322, 343, 365, 386, 428, 447, 467, 486, 507, 528, 549, 570
        //year: 256, 272, 288, 304
        //month: 322, 343
        //day: 365, 386

        //year: 428, 447, 467, 486
        //month: 507, 528
        //day: 549, 570

        // 32, 49, 63, 77, 92, 106.5, 120, 134.5, 149, 163, 177, 191.5, 205, 223, 241, 255, 269, 286  
        /*Esto es para medir las casillas del curp
        contentStream.setStrokingColor(Color.BLACK);
        contentStream.moveTo(286,569);
        contentStream.lineTo(286,580);
        contentStream.stroke();
        */

        /*
        PDImageXObject logo = PDImageXObject.createFromFile("src/files/logo.png", document);
        PDImageXObject firma = PDImageXObject.createFromFile("src/files/firmasola.png", document);
            
        System.out.println("logoWidth: " + logo.getWidth());
        System.out.println("logoHeight: " + logo.getHeight());
        System.out.println("firmaWidth: " + firma.getWidth());
        System.out.println("firmaHeight: " + firma.getHeight());
        */
        contentStream.addRect(50, 750, 500, 100);
        contentStream.setNonStrokingColor(Color.WHITE);
        contentStream.fill();

        contentStream.addRect(50, 224, 150, 10);
        contentStream.setNonStrokingColor(Color.WHITE);
        contentStream.fill();

        if (logoObject != null && !logoObject.isEmpty()) {
            contentStream.drawImage(logoObject, 430, 700, 150, 75);
        }
        if (firmaObject != null && !firmaObject.isEmpty()) {
            contentStream.drawImage(firmaObject, 80, 223, 110, 42);

            contentStream.setStrokingColor(Color.BLACK);
            contentStream.setLineWidth((float) .8);
            contentStream.moveTo(50, (float) 235.6);
            contentStream.lineTo(200, (float) 235.6);
            contentStream.stroke();

        }

        contentStream.beginText();
        contentStream.setFont(helvetica_normal, 8);
        contentStream.setNonStrokingColor(Color.BLACK);

        charWidth = helvetica_normal.getStringWidth(c.capacitador) / 1000 * 8;
        float x = 126 - charWidth / 2;

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, x, 228));
        contentStream.showText(c.capacitador);
        //GIS100219KK8003
        String regUnidad;

        if (c.uCapacitadora.equalsIgnoreCase("TSI. Jorge Antonio Razn Gil")) {
            regUnidad = "RAGJ610813BIA005";
        } else {
            regUnidad = "GIS100219KK8003";
        }

        charWidth = helvetica_normal.getStringWidth(regUnidad) / 1000 * 8;
        x = 126 - charWidth / 2;
        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, x, 219));
        contentStream.showText(regUnidad);

        contentStream.endText();

        // Make sure that the content stream is closed:
        contentStream.close();
        Format formatter = new SimpleDateFormat("ddMMMYYYY", new Locale("es", "MX"));
        String formatedDate = formatter.format(c.fecha_inicio);

        String abrev = abreviaturas.get(c.nombre_curso);

        // Save the results and ensure that the document is properly closed:

        document.save(savePath + File.separator + "p_DC3_" + p.curp + "_" + p.determinante + "_"
                + p.nombre.replaceAll(" ", "_") + "_" + p.apellidos.replaceAll(" ", "_") + "_" + abrev + "_"
                + formatedDate + ".pdf");
        document.close();
        dosc.put(savePath + File.separator + "p_DC3_" + p.curp + "_" + p.determinante + "_"
                + p.nombre.replaceAll(" ", "_") + "_" + p.apellidos.replaceAll(" ", "_") + "_" + abrev + "_"
                + formatedDate + ".pdf", p.determinante);

    }