List of usage examples for org.apache.pdfbox.pdmodel.font PDType1Font COURIER
PDType1Font COURIER
To view the source code for org.apache.pdfbox.pdmodel.font PDType1Font COURIER.
Click Source Link
From source file:mail.java
private void bonos() throws SQLException { //**//from www . ja va 2 s .com 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();/* ww w. j a v a2 s . c om*/ // 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:com.baseprogramming.pdwriter.html.HtmlStyle.java
License:Apache License
private void createFontMap() { fontMap = new HashMap<>(); fontMap.put("TIMES NEW ROMAN", PDType1Font.TIMES_ROMAN); fontMap.put("TIMES NEW ROMAN_BOLD", PDType1Font.TIMES_BOLD); fontMap.put("TIMES NEW ROMAN_ITALIC", PDType1Font.TIMES_ITALIC); fontMap.put("TIMES NEW ROMAN_OBLIQUE", PDType1Font.TIMES_ITALIC); fontMap.put("TIMES NEW ROMAN_BOLD_ITALIC", PDType1Font.TIMES_BOLD_ITALIC); fontMap.put("COURIER", PDType1Font.COURIER); fontMap.put("COURIER_BOLD", PDType1Font.COURIER_BOLD); fontMap.put("COURIER_ITALIC", PDType1Font.COURIER_OBLIQUE); fontMap.put("COURIER_OBLIQUE", PDType1Font.COURIER_OBLIQUE); fontMap.put("COURIER_BOLD_ITALIC", PDType1Font.COURIER_BOLD_OBLIQUE); fontMap.put("HELVATICA", PDType1Font.TIMES_ROMAN); fontMap.put("HELVATICA_ITALIC", PDType1Font.HELVETICA_BOLD); fontMap.put("HELVATICA_OBLIQUE", PDType1Font.HELVETICA_BOLD); fontMap.put("HELVATICA_BOLD_ITALIC", PDType1Font.HELVETICA_OBLIQUE); fontMap.put("HELVATICA_BOLD_ITALIC", PDType1Font.HELVETICA_BOLD_OBLIQUE); }
From source file:com.baseprogramming.pdwriter.PdWriterTest.java
License:Apache License
@Test public void testBasicDemo() { try (PDDocument pdDoc = new PDDocument()) { Margin margin = new Margin(0.75f, 0.2f, 0.5f, 0.25f); PdWriter writer = new PdWriter(pdDoc, margin); PdParagraph title = writer.createParagraph(); title.setFont(PDType1Font.TIMES_BOLD); title.setFontSize(24);//from www .ja v a2 s .c o m title.setAboveSpacing(new PdInch(0.75f)); title.setBelowSpacing(new PdInch(0.75f)); PdParagraph heading = writer.createParagraph(); heading.setFont(PDType1Font.TIMES_BOLD_ITALIC); heading.setFontSize(16); heading.setAboveSpacing(new PdInch(0.1f)); PdParagraph body = writer.createParagraph(); body.setBelowSpacing(new PdInch(0.17f)); PdParagraph code = writer.createParagraph(); code.setFont(PDType1Font.COURIER); code.setBeforeTextIndent(new PdInch(0.5f)); code.setAboveSpacing(new PdInch(0.1f)); code.setBelowSpacing(new PdInch(0.1f)); writer.write(title, "PdWriter Class"); writeBasicParagraphDemo(writer, body, code, heading); writeListDemo(writer, body, code, heading); writeTableDemo(writer, heading, body, code); writeImageDemo(writer, heading, body, code); writeHtmlDemo(writer, heading, body, code); pdDoc.save(new File("c:/tmp/PdWriter-Demo.pdf")); } catch (Exception e) { e.printStackTrace(); } }
From source file:controldeadministradores.Admin.java
public void crearPDF(String file, String body) throws Exception { String outputFileName = file + ".pdf"; // if (args.length > 0) // outputFileName = args[0]; // Create a document and add a page to it PDDocument document = new PDDocument(); PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4); // PDPage.PAGE_SIZE_LETTER is also possible PDRectangle rect = page1.getMediaBox(); // rect can be used to get the page width and height document.addPage(page1);/*ww w . ja v a 2 s.c o m*/ // Create a new font object selecting one of the PDF base fonts PDFont fontPlain = PDType1Font.HELVETICA; PDFont fontBold = PDType1Font.HELVETICA_BOLD; PDFont fontItalic = PDType1Font.HELVETICA_OBLIQUE; PDFont fontMono = PDType1Font.COURIER; // Start a new content stream which will "hold" the to be created content PDPageContentStream cos = new PDPageContentStream(document, page1); int line = 0; // Define a text content stream using the selected font, move the cursor and draw some text cos.beginText(); cos.setFont(fontPlain, 14); cos.moveTextPositionByAmount(100, rect.getHeight() - 50 * (++line)); cos.drawString("Reporte de " + file); cos.endText(); String[] txtLine = body.split("-"); for (int k = 0; k < txtLine.length; k++) { cos.beginText(); cos.setFont(fontPlain, 12); cos.moveTextPositionByAmount(100, rect.getHeight() - 50 * (++line)); cos.drawString(txtLine[k]); cos.endText(); cos.close(); } // Make sure that the content stream is closed: // Save the results and ensure that the document is properly closed: document.save(outputFileName); document.close(); }
From source file:dtlgenerator.myDataReader.java
public void PdfGenerator(String pdfFileNameBase, List<String> cycles) throws IOException, COSVisitorException { GlobalVar.dirMake(new File(pdfFileNameBase)); //create a folder with the same name int rowCount = 0; int pageCount = 1; PDPage page; //default size PAGE_SIZE_A4 PDPageContentStream stream;/*from w ww .ja v a 2 s . c o m*/ //page.setRotation(90); //counterclock wise rotate 90 degree ////left hand rule // stream.setFont(PDType1Font.COURIER, FONT_SIZE); String lastUpdate = null; String lastCycle = null; System.out.println("DTL_DATA keyset:" + DTL_DATA.keySet()); System.out.println("Cycles empty? " + cycles.isEmpty()); System.out.println(cycles); for (String updateDate : DTL_DATA.keySet()) { Map<String, List<String>> thisDTData = DTL_DATA.get(updateDate); lastUpdate = updateDate; System.out.println("thisDT_DATA keyset:" + thisDTData.keySet()); for (String cycle : thisDTData.keySet()) { if (cycles.isEmpty() || cycles.contains(cycle)) { PDDocument pdf = new PDDocument(); lastCycle = cycle; List<String> thisCycle = thisDTData.get(cycle); pageCount = 1; // new cycle, restart page num page = new PDPage(); //page break stream = new PDPageContentStream(pdf, page, true, false); stream.beginText(); page.setRotation(PAGE_ROT_DEGREE); //stream.setFont(PDType1Font.COURIER, FONT_SIZE); addBigFontUpdateNumberAndCycle(updateDate, cycle, stream); stream.setFont(PDType1Font.COURIER, FONT_SIZE); // stream.setFont(PDType1Font. int thisCycleRowCount = 0; for (String row : thisCycle) { if (thisCycleRowCount > MAX_NUM_TRANS) { //close the current page setupFootNote(stream, pageCount, cycle, updateDate); pageCount++; stream.endText(); stream.close(); pdf.addPage(page); // start a new page page = new PDPage(); stream = new PDPageContentStream(pdf, page, true, false); page.setRotation(PAGE_ROT_DEGREE); stream.beginText(); stream.setFont(PDType1Font.COURIER, FONT_SIZE); thisCycleRowCount = 0; } stream.setTextRotation(TEXT_ROT_RAD, TRANS_X + thisCycleRowCount * INVERVAL_X, TRANS_Y); stream.drawString(row); thisCycleRowCount++; //System.out.println("Update:" + updateDate + " Cycle: " + cycle + " " + row); } setupFootNote(stream, pageCount, lastCycle, lastUpdate); stream.endText(); stream.close(); pdf.addPage(page); String pdfFileName = pdfFileNameBase + "\\DTL UPDT " + updateDate + " " + cycle + ".pdf"; pdf.save(pdfFileName); pdf.close(); } } } // pdf.save(pdfFileName); // pdf.close(); }
From source file:dtlgenerator.myDataReader.java
private void addBigFontUpdateNumberAndCycle(String updateDate, String cycle, PDPageContentStream stream) throws IOException { stream.setFont(PDType1Font.COURIER, BIG_FONT_SIZE); stream.setTextRotation(TEXT_ROT_RAD, BIG_FONT_UPDT_X, BIG_FONT_UPDT_Y); if (updateDate != null && updateDate.length() >= 5) { updateDate = updateDate.substring(0, 5); // choose the first 5 characters. 10-10 stream.drawString(updateDate);//www . j a v a2s.com } stream.setTextRotation(TEXT_ROT_RAD, BIG_FONT_CYCLE_X, BIG_FONT_CYCLE_Y); stream.drawString(cycle); }
From source file:gamma.cvd.calculator.print.CVDPrint.java
private PDDocument createPdfDocument(CVDPatient patient) throws IOException { PDDocument document = new PDDocument(); List<PDPage> pageList = new ArrayList<>(); PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4); pageList.add(page1);// w ww . j a v a2 s .c o m PDRectangle rect = pageList.get(0).getMediaBox(); document.addPage(pageList.get(0)); PDFont fontHelveticaBold = PDType1Font.HELVETICA_BOLD; PDFont fontCourier = PDType1Font.COURIER; PDFont fontCourierBold = PDType1Font.COURIER_BOLD; PDPageContentStream contentStream = new PDPageContentStream(document, pageList.get(0)); line = 0; contentStream.beginText(); contentStream.setFont(fontHelveticaBold, 18); contentStream.moveTextPositionByAmount(leftMargin, rect.getHeight() - initialLineSpace); contentStream.drawString("Test record for " + patient.getFirstName() + " " + patient.getLastName()); contentStream.endText(); contentStream.setFont(fontCourier, 12); writeLine("Patient no.:", String.valueOf(patient.getPatientId()), contentStream, rect.getHeight() - patientLineSpace); writeLine("First name:", patient.getFirstName(), contentStream, rect.getHeight() - patientLineSpace); writeLine("Last name:", patient.getLastName(), contentStream, rect.getHeight() - patientLineSpace); writeLine("Date of birth:", patient.getBirthdate().toString(), contentStream, rect.getHeight() - patientLineSpace); writeLine("Sex:", String.valueOf(patient.getSex()), contentStream, rect.getHeight() - patientLineSpace); int n = 0; for (CVDRiskData data : patient.getRiskData()) { if (n > 0 && n % 3 == 0) { contentStream.close(); PDPage page = new PDPage(PDPage.PAGE_SIZE_A4); pageList.add(page); document.addPage(pageList.get(n / 3)); contentStream = new PDPageContentStream(document, pageList.get(n / 3)); line = 0; contentStream.beginText(); contentStream.setFont(fontHelveticaBold, 18); contentStream.moveTextPositionByAmount(leftMargin, rect.getHeight() - initialLineSpace); contentStream.drawString("Test record for " + patient.getFirstName() + " " + patient.getLastName() + ", page " + ((n / 3) + 1)); contentStream.endText(); } contentStream.beginText(); contentStream.moveTextPositionByAmount(leftMargin, rect.getHeight() - testDataLineSpace - lineSpace * ++line); contentStream.endText(); contentStream.setFont(fontCourierBold, 12); writeLine("Test ID:", String.valueOf(data.getTestId()), contentStream, rect.getHeight() - testDataLineSpace); contentStream.setFont(fontCourier, 12); writeLine("Test date:", data.getTestDate().toString(), contentStream, rect.getHeight() - testDataLineSpace); writeLine("Cholesterol type:", data.getCholesterolType(), contentStream, rect.getHeight() - testDataLineSpace); writeLine("Cholesterol mmol/L:", String.format("%.2f", data.getCholesterolMmolL()), contentStream, rect.getHeight() - testDataLineSpace); writeLine("HDL mmol/L:", String.format("%.2f", data.getHdlMmolL()), contentStream, rect.getHeight() - testDataLineSpace); writeLine("Diastolic blood pressure:", String.valueOf(data.getBloodPressureDiastolicMmHg()), contentStream, rect.getHeight() - testDataLineSpace); writeLine("Systolic blood pressure:", String.valueOf(data.getBloodPressureSystolicMmHg()), contentStream, rect.getHeight() - testDataLineSpace); if (data.isSmoker()) { writeLine("Patient is smoker:", "Yes", contentStream, rect.getHeight() - testDataLineSpace); } else { writeLine("Patient is smoker:", "No", contentStream, rect.getHeight() - testDataLineSpace); } if (data.isDiabetic()) { writeLine("Patient is diabetic:", "Yes", contentStream, rect.getHeight() - testDataLineSpace); } else { writeLine("Patient is diabetic:", "No", contentStream, rect.getHeight() - testDataLineSpace); } int score = data.calculateRiskScore(); writeLine("Risk score:", String.valueOf(score), contentStream, rect.getHeight() - testDataLineSpace); int riskPercentage = data.getRiskPercentage(score); writeLine("Risk percentage:", new StringBuilder().append(riskPercentage).append(" %").toString(), contentStream, rect.getHeight() - testDataLineSpace); n++; } contentStream.close(); return document; }
From source file:javaexample.StandardFontsDemoPdf.java
License:Open Source License
private void drawFontFeature(String featureName, Object featureValue) throws IOException { // Draws feature name. cos.setFont(PDType1Font.COURIER_BOLD, 8); cos.setNonStrokingColor(Color.BLACK); drawText(featureName, x, y);/* ww w . j a v a 2 s. c o m*/ cos.setFont(PDType1Font.COURIER, 8); drawText("=", x + mm2pt(28), y); // Detects feature value type to set text and color. String text; Color color; if (featureValue == null) { text = "null"; color = NULL_COLOR; } else if (featureValue instanceof Number) { text = String.valueOf(featureValue); color = NUMBER_COLOR; } else if (featureValue instanceof String) { text = "\"" + featureValue + "\""; color = STRING_COLOR; } else if (featureValue instanceof Boolean) { text = String.valueOf(featureValue); color = BOOLEAN_COLOR; } else { text = String.valueOf(featureValue); color = OTHER_COLOR; } // Draws feature value. cos.setNonStrokingColor(color); drawText(text, x + mm2pt(31), y); y -= 12; }
From source file:jgnash.PDFBoxTableTest.java
License:Open Source License
@Test void basicReportTest() throws IOException { Path tempPath = null;/*w w w . j a v a2s .c o m*/ Path tempRasterPath = null; try (final Report report = new SimpleReport()) { tempPath = Files.createTempFile("pdfTest", ".pdf"); tempRasterPath = Files.createTempFile("pdfTest", ".png"); final float padding = 2.5f; report.setTableFont(PDType1Font.COURIER); report.setHeaderFont(PDType1Font.HELVETICA_BOLD); report.setCellPadding(padding); report.setBaseFontSize(9); final PageFormat pageFormat = ReportPrintFactory.getDefaultPage(); pageFormat.setOrientation(PageFormat.LANDSCAPE); report.setPageFormat(pageFormat); report.setFooterFont(PDType1Font.TIMES_ITALIC); report.setEllipsis(""); assertEquals(1, Report.getGroups(new BasicTestReport()).size()); assertEquals(80, ((Report.GroupInfo) Report.getGroups(new BasicTestReport()).toArray()[0]).rows); report.addTable(new BasicTestReport(), "Test Report"); report.addFooter(); report.saveToFile(tempPath); assertTrue(report.isLandscape()); assertEquals(padding, report.getCellPadding()); assertTrue(Files.exists(tempPath)); // Create a PNG file final BufferedImage bim = report.renderImage(0, 300); ImageIOUtil.writeImage(bim, tempRasterPath.toString(), 300); assertTrue(Files.exists(tempRasterPath)); } catch (final IOException e) { e.printStackTrace(); } finally { if (tempPath != null) { Files.deleteIfExists(tempPath); } if (tempRasterPath != null) { Files.deleteIfExists(tempRasterPath); } } }