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

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

Introduction

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

Prototype

public PDPage() 

Source Link

Document

Creates a new PDPage instance for embedding, with a size of U.S.

Usage

From source file:generarPDF.GenerarReporteDiario.java

public PDDocument crearDiario(Calendar fechaInicial, Calendar fechaFinal, DefaultTableModel modeloTabla,
        JFrame dialogo) {//from   ww  w  .  j a v  a 2  s. c o  m
    PDDocument document = new PDDocument();

    try {

        PDPage pagina1 = new PDPage();
        document.addPage(pagina1);

        PDFont font = PDType1Font.HELVETICA_BOLD;
        PDFont fontNormal = PDType1Font.HELVETICA;

        PDPageContentStream contenido = new PDPageContentStream(document, pagina1);

        int annioInicial = fechaInicial.get(Calendar.YEAR);
        int mesInicial = fechaInicial.get(Calendar.MONTH) + 1;
        int diaInicial = fechaInicial.get(Calendar.DAY_OF_MONTH);

        String cadenaFechaInicial = annioInicial + "/" + mesInicial + "/" + diaInicial;

        int annioFinal = fechaFinal.get(Calendar.YEAR);
        int mesFinal = fechaFinal.get(Calendar.MONTH) + 1;
        int diaFinal = fechaFinal.get(Calendar.DAY_OF_MONTH);
        String cadenaFechaFinal = annioFinal + "/" + mesFinal + "/" + diaFinal;

        contenido.beginText();
        contenido.setFont(font, 16);
        contenido.moveTextPositionByAmount(30, 730);
        contenido.drawString("Diario, desde: " + cadenaFechaInicial + " hasta: " + cadenaFechaFinal);
        contenido.endText();

        contenido.drawLine(30, 680, 500, 680);
        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(200, 660);
        contenido.drawString("DETALLE DEL FLUJO");
        contenido.endText();
        contenido.drawLine(30, 640, 500, 640);

        /*
         * Caben en la pagina
         * Primera pagina 14
         * Seguientes paginas 21
         * Footer cuenta como 3 mas
         */
        double totalEspaciosNecesarios = modeloTabla.getRowCount() + 3 + 1;
        double totalPaginas = 1;
        int indiceProductos = 0;

        if (Math.floor(totalEspaciosNecesarios / 20) == 0) {
            totalPaginas = 1;
        } else {
            totalEspaciosNecesarios -= 20;
            totalPaginas += (int) Math.ceil(totalEspaciosNecesarios / 24);
        }

        /*
         Encabezado tabla
         */
        contenido.drawLine(30, 620, 500, 620);

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(60, 605);
        contenido.drawString("Nmero factura");
        contenido.endText();
        contenido.drawLine(30, 600, 30, 620);
        contenido.drawLine(200, 600, 200, 620);

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(220, 605);
        contenido.drawString("Fecha");
        contenido.endText();
        contenido.drawLine(300, 600, 300, 620);

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(320, 605);
        contenido.drawString("Tipo");
        contenido.endText();
        contenido.drawLine(380, 600, 380, 620);

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(400, 605);
        contenido.drawString("Valor");
        contenido.endText();
        contenido.drawLine(500, 600, 500, 620);
        contenido.drawLine(500, 600, 500, 620);

        contenido.drawLine(30, 600, 500, 600);

        int altura = 600;
        /*
         Generar informes
         */
        for (int i = 0; i < modeloTabla.getRowCount() && altura >= 30; i++) {
            //Imprime por paginas

            String numeroFactura = String.valueOf(modeloTabla.getValueAt(i, 1));
            String fecha = String.valueOf(modeloTabla.getValueAt(i, 2));
            fecha = fecha.substring(0, 10);
            String tipo = String.valueOf(modeloTabla.getValueAt(i, 3));
            String valor = String.valueOf(modeloTabla.getValueAt(i, 4));

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(40, altura - 15);
            contenido.drawString(numeroFactura);
            contenido.endText();

            contenido.drawLine(30, altura, 30, altura - 30);
            contenido.drawLine(200, altura, 200, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(220, altura - 15);
            contenido.drawString(fecha);
            contenido.endText();

            contenido.drawLine(300, altura, 300, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(330, altura - 15);
            contenido.drawString(tipo);
            contenido.endText();
            contenido.drawLine(380, altura, 380, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(420, altura - 15);
            contenido.drawString(valor);
            contenido.endText();

            contenido.drawLine(500, altura, 500, altura - 30);

            //Linea inferior
            contenido.drawLine(30, altura - 30, 500, altura - 30);
            altura -= 30;
            indiceProductos = i + 1;
        }
        //Escribir paginas siguientes

        for (int j = 1; j < totalPaginas; j++) {
            altura = 600;
            PDPage paginaSiguiente = new PDPage();
            document.addPage(paginaSiguiente);
            PDPageContentStream contenidoSiguiente = new PDPageContentStream(document, paginaSiguiente);

            for (int i = indiceProductos; i < modeloTabla.getRowCount() && altura >= 30; i++) {
                //Imprime por paginas

                String numeroFactura = String.valueOf(modeloTabla.getValueAt(i, 1));
                String fecha = String.valueOf(modeloTabla.getValueAt(i, 2));
                fecha = fecha.substring(0, 10);
                String tipo = String.valueOf(modeloTabla.getValueAt(i, 3));
                String valor = String.valueOf(modeloTabla.getValueAt(i, 4));

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(40, altura - 15);
                contenidoSiguiente.drawString(numeroFactura);
                contenidoSiguiente.endText();

                contenidoSiguiente.drawLine(30, altura, 30, altura - 30);
                contenidoSiguiente.drawLine(200, altura, 200, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(220, altura - 15);
                contenidoSiguiente.drawString(fecha);
                contenidoSiguiente.endText();

                contenidoSiguiente.drawLine(300, altura, 300, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(330, altura - 15);
                contenidoSiguiente.drawString(tipo);
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(380, altura, 380, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(420, altura - 15);
                contenidoSiguiente.drawString(valor);
                contenidoSiguiente.endText();

                contenidoSiguiente.drawLine(500, altura, 500, altura - 30);

                //Linea inferior
                contenidoSiguiente.drawLine(30, altura - 30, 500, altura - 30);
                altura -= 30;
                indiceProductos = i + 1;
            }
            contenidoSiguiente.close();
        }

        contenido.close();

    } catch (Exception e) {
        JOptionPane.showMessageDialog(dialogo,
                "Se ha presentado un error al generar el diario\nInformacin tcnica\n" + e.toString());
    }
    return document;
}

From source file:generarPDF.ReporteFlujosCliente.java

private PDDocument crearInformeMovimientosCliente(ArrayList<Integer> flujosID, int cliente_id,
        Calendar fechaInicial, Calendar fechaFinal) {

    try {//  w  w w  .ja  v a  2 s . c o  m

        ControladorCliente controladorCliente = new ControladorCliente();
        Cliente cliente = controladorCliente.obtenerClientePorID(cliente_id);

        PDDocument document = new PDDocument();

        PDPage pagina1 = new PDPage();
        document.addPage(pagina1);

        PDFont font = PDType1Font.HELVETICA_BOLD;
        PDFont fontNormal = PDType1Font.HELVETICA;

        PDPageContentStream contenido = new PDPageContentStream(document, pagina1);

        contenido.beginText();
        contenido.setFont(font, 16);
        contenido.moveTextPositionByAmount(30, 730);
        contenido.drawString("Reporte de movimientos del cliente");
        contenido.endText();

        contenido.beginText();
        contenido.setFont(font, 12);
        contenido.moveTextPositionByAmount(30, 700);
        contenido.drawString("Minimarket Barrio Nuevo.       NIT: 1234567898-9");
        contenido.endText();

        contenido.beginText();
        contenido.setFont(font, 12);
        contenido.moveTextPositionByAmount(30, 680);
        contenido.drawString("Calle Falsa 1 2 3");
        contenido.endText();

        Calendar fecha = new GregorianCalendar();
        //Obtenemos el valor del ao, mes, da,
        //hora, minuto y segundo del sistema
        //usando el mtodo get y el parmetro correspondiente
        int annio = fecha.get(Calendar.YEAR);
        int mes = fecha.get(Calendar.MONTH);
        int dia = fecha.get(Calendar.DAY_OF_MONTH);

        contenido.beginText();
        contenido.setFont(fontNormal, 11);
        contenido.moveTextPositionByAmount(30, 650);
        contenido.drawString("Fecha: " + annio + "/" + (mes + 1) + "/" + dia);
        contenido.endText();

        contenido.beginText();
        contenido.setFont(fontNormal, 11);
        contenido.moveTextPositionByAmount(30, 635);
        contenido.drawString("Nombre: " + cliente.getNombre());
        contenido.endText();

        contenido.beginText();
        contenido.setFont(fontNormal, 11);
        contenido.moveTextPositionByAmount(30, 620);
        contenido.drawString("Direccin: " + cliente.getDireccion());
        contenido.endText();

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(110, 590);

        SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd");
        String formattedInicial = formato.format(fechaInicial.getTime());
        String formattedFinal = formato.format(fechaFinal.getTime());

        contenido.drawString("DETALLE DE LOS MOVIMIENTOS entre: " + formattedInicial + " y " + formattedFinal);
        contenido.endText();

        //Dibujar lineas
        contenido.drawLine(30, 600, 500, 600);
        contenido.drawLine(30, 585, 500, 585);

        contenido.drawLine(30, 570, 500, 570);

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(60, 560);
        contenido.drawString("Factura");
        contenido.endText();
        contenido.drawLine(30, 550, 30, 570);
        contenido.drawLine(200, 550, 200, 570);

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(220, 560);
        contenido.drawString("Tipo flujo");
        contenido.endText();
        contenido.drawLine(300, 550, 300, 570);

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(320, 560);
        contenido.drawString("Fecha");
        contenido.endText();
        contenido.drawLine(380, 550, 380, 570);

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(400, 560);
        contenido.drawString("Valor");
        contenido.endText();
        contenido.drawLine(500, 550, 500, 570);
        contenido.drawLine(500, 550, 500, 570);

        contenido.drawLine(30, 550, 500, 550);

        int altura = 550;
        /*
         * Caben en la pagina
         * Primera pagina 14
         * Seguientes paginas 21
         * Footer cuenta como 3 mas
         */
        int indiceProductos = 0;
        double totalEspaciosNecesarios = flujosID.size() + 3 + 1;
        double totalPaginas = 1;

        if (Math.floor(totalEspaciosNecesarios / 17) == 0) {
            totalPaginas = 1;
        } else {
            totalEspaciosNecesarios -= 17;
            totalPaginas += (int) Math.ceil(totalEspaciosNecesarios / 21);
        }
        double abonos = 0.0;
        double deudas = 0.0;
        for (int i = 0; i < flujosID.size(); i++) {
            ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
            Flujo_Factura flujoFactura = controladorFlujoFactura
                    .getFlujo_Factura(" where flujo_id=" + flujosID.get(i));

            if (flujoFactura.getTipo_flujo().equals("abono")) {
                abonos += flujoFactura.getValor();
            } else {
                deudas += flujoFactura.getValor();
            }
        }
        //Primer pagina
        for (int i = 0; i < flujosID.size() && altura >= 30; i++) {
            //Imprime por paginas
            ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
            Flujo_Factura flujoFactura = controladorFlujoFactura
                    .getFlujo_Factura(" where flujo_id=" + flujosID.get(i));

            String facturaID = String.valueOf(flujoFactura.getFactura_id());

            if (facturaID.length() > 25) {
                facturaID = facturaID.substring(0, 26);
            }

            String tipoFlujo = flujoFactura.getTipo_flujo();

            String fechaFlujo = flujoFactura.getFecha();
            fechaFlujo = fechaFlujo.substring(0, 10);
            String valorTotal = String.valueOf(flujoFactura.getValor());

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(40, altura - 15);
            contenido.drawString(String.valueOf(i + 1));
            contenido.endText();
            contenido.drawLine(30, altura, 30, altura - 30);
            contenido.drawLine(200, altura, 200, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(70, altura - 15);
            contenido.drawString(facturaID);
            contenido.endText();
            contenido.drawLine(70, altura, 70, altura - 30);
            contenido.drawLine(200, altura, 200, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(220, altura - 15);
            contenido.drawString(tipoFlujo);
            contenido.endText();
            contenido.drawLine(300, altura, 300, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(310, altura - 15);
            contenido.drawString(fechaFlujo);
            contenido.endText();
            contenido.drawLine(380, altura, 380, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(400, altura - 15);
            contenido.drawString(valorTotal);
            contenido.endText();
            contenido.drawLine(500, altura, 500, altura - 30);
            //Linea inferior
            contenido.drawLine(30, altura - 30, 500, altura - 30);
            altura -= 30;
            indiceProductos = i + 1;
        }
        //Escribir footer si paginas es igual a 1
        if (totalPaginas == 1) {
            Double valor = abonos - deudas;

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(300, altura - 15);
            contenido.drawString("Abonado por el cliente");
            contenido.endText();
            contenido.drawLine(380, altura, 380, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(400, altura - 15);
            contenido.drawString(String.valueOf(abonos));
            contenido.endText();
            contenido.drawLine(500, altura, 500, altura - 30);

            //Linea inferior
            contenido.drawLine(300, altura, 300, altura - 30);
            contenido.drawLine(300, altura - 30, 500, altura - 30);

            altura -= 30;
            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(300, altura - 15);
            contenido.drawString("Prestado al cliente");
            contenido.endText();
            contenido.drawLine(380, altura, 380, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(400, altura - 15);
            contenido.drawString(String.valueOf(deudas));
            contenido.endText();
            contenido.drawLine(500, altura, 500, altura - 30);
            //Linea inferior
            contenido.drawLine(300, altura, 300, altura - 30);
            contenido.drawLine(300, altura - 30, 500, altura - 30);
            altura -= 30;

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(300, altura - 15);
            contenido.drawString("Total flujos");
            contenido.endText();
            contenido.drawLine(380, altura, 380, altura - 30);

            contenido.beginText();
            contenido.setFont(font, 12);
            contenido.moveTextPositionByAmount(400, altura - 15);
            contenido.drawString(String.valueOf(valor));
            contenido.endText();
            contenido.drawLine(500, altura, 500, altura - 30);
            //Linea inferior
            contenido.drawLine(300, altura - 30, 500, altura - 30);
            contenido.drawLine(300, altura, 300, altura - 30);

        }

        //Siguientes paginas
        for (int j = 1; j < totalPaginas; j++) {
            altura = 650;
            PDPage paginaSiguiente = new PDPage();
            document.addPage(paginaSiguiente);

            PDPageContentStream contenidoSiguiente = new PDPageContentStream(document, paginaSiguiente);
            //Escribir paginas
            for (int i = indiceProductos; i < flujosID.size() && altura >= 30; i++) {
                //Imprime por paginas
                //Imprime por paginas
                ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
                Flujo_Factura flujoFactura = controladorFlujoFactura
                        .getFlujo_Factura(" where flujo_id=" + flujosID.get(i));

                String facturaID = String.valueOf(flujoFactura.getFactura_id());

                if (facturaID.length() > 25) {
                    facturaID = facturaID.substring(0, 26);
                }

                String tipoFlujo = flujoFactura.getTipo_flujo();

                String fechaFlujo = flujoFactura.getFecha();
                fechaFlujo = fechaFlujo.substring(0, 10);
                String valorTotal = String.valueOf(flujoFactura.getValor());

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(40, altura - 15);
                contenidoSiguiente.drawString(String.valueOf(i + 1));
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(30, altura, 30, altura - 30);
                contenidoSiguiente.drawLine(200, altura, 200, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(70, altura - 15);
                contenidoSiguiente.drawString(facturaID);
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(70, altura, 70, altura - 30);
                contenidoSiguiente.drawLine(200, altura, 200, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(220, altura - 15);
                contenidoSiguiente.drawString(tipoFlujo);
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(300, altura, 300, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(310, altura - 15);
                contenidoSiguiente.drawString(fechaFlujo);
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(380, altura, 380, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(400, altura - 15);
                contenidoSiguiente.drawString(valorTotal);
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(500, altura, 500, altura - 30);
                //Linea inferior
                contenidoSiguiente.drawLine(30, altura - 30, 500, altura - 30);
                altura -= 30;
                indiceProductos = i + 1;
            }
            //Si no cabe mas cierre el flujo.
            if (indiceProductos < flujosID.size()) {
                contenidoSiguiente.close();
            }
            //En ultima pagina escribir footer
            if (j == totalPaginas - 1 && altura >= 40) {
                Double valor = abonos - deudas;

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(300, altura - 15);
                contenidoSiguiente.drawString("Abonado por el cliente");
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(380, altura, 380, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(400, altura - 15);
                contenidoSiguiente.drawString(String.valueOf(abonos));
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(500, altura, 500, altura - 30);

                //Linea inferior
                contenidoSiguiente.drawLine(300, altura, 300, altura - 30);
                contenidoSiguiente.drawLine(300, altura - 30, 500, altura - 30);

                altura -= 30;
                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(300, altura - 15);
                contenidoSiguiente.drawString("Prestado al cliente");
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(380, altura, 380, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(400, altura - 15);
                contenidoSiguiente.drawString(String.valueOf(deudas));
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(500, altura, 500, altura - 30);
                //Linea inferior
                contenidoSiguiente.drawLine(300, altura, 300, altura - 30);
                contenidoSiguiente.drawLine(300, altura - 30, 500, altura - 30);
                altura -= 30;

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(300, altura - 15);
                contenidoSiguiente.drawString("Total flujo");
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(380, altura, 380, altura - 30);

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(font, 12);
                contenidoSiguiente.moveTextPositionByAmount(400, altura - 15);
                contenidoSiguiente.drawString(String.valueOf(valor));
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(500, altura, 500, altura - 30);
                //Linea inferior
                contenidoSiguiente.drawLine(300, altura - 30, 500, altura - 30);
                contenidoSiguiente.drawLine(300, altura, 300, altura - 30);

                contenidoSiguiente.close();
            } else {
                contenidoSiguiente.close();
            }

            System.out.println("Pagina numero: " + j + " De  " + totalPaginas);

        }

        contenido.close();
        return document;

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error al crear la factura ", "Error", JOptionPane.ERROR_MESSAGE);
        return null;
    }

}

From source file:geotheme.pdf.generatePDF.java

License:Open Source License

public ByteArrayOutputStream createPDFFromImage(wmsParamBean wpb, String host)
        throws IOException, COSVisitorException {
    PDDocument doc = null;/*from  w  ww.j  a  v  a  2 s  .c  o  m*/
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    OutputStreamWriter wr = null;
    OutputStreamWriter wl = null;
    URLConnection geoConn = null;
    URLConnection legConn = null;

    int width = 500;
    int height = 500;

    wpb.setBBOX(retainAspectRatio(wpb.getBBOX()));

    StringBuffer sb = new StringBuffer();
    sb.append(this.pdfURL);
    sb.append("&layers=").append(this.pdfLayers);
    sb.append("&bbox=").append(wpb.getBBOX());
    sb.append("&Format=image/jpeg");
    sb.append("&width=").append(width);
    sb.append("&height=").append(height);

    try {
        wpb.setREQUEST("GetMap");
        wpb.setWIDTH(Integer.toString(width));
        wpb.setHEIGHT(Integer.toString(height));

        URL url = new URL(host);
        URL urll = new URL(host);
        URL osm = new URL(sb.toString());

        geoConn = url.openConnection();
        geoConn.setDoOutput(true);

        legConn = urll.openConnection();
        legConn.setDoOutput(true);

        wr = new OutputStreamWriter(geoConn.getOutputStream(), "UTF-8");
        wr.write(wpb.getURL_PARAM());

        wr.flush();

        wpb.setREQUEST("GetLegendGraphic");
        wpb.setTRANSPARENT("FALSE");
        wpb.setWIDTH("");
        wpb.setHEIGHT("");

        wl = new OutputStreamWriter(legConn.getOutputStream(), "UTF-8");
        wl.write(wpb.getURL_PARAM() + "&legend_options=fontSize:9;");
        wl.flush();

        doc = new PDDocument();

        PDPage page = new PDPage(/*PDPage.PAGE_SIZE_A4*/);
        doc.addPage(page);

        BufferedImage img = ImageIO.read(geoConn.getInputStream());
        BufferedImage leg = ImageIO.read(legConn.getInputStream());

        PDXObjectImage ximage = new PDPixelMap(doc, img);
        PDXObjectImage xlegend = new PDPixelMap(doc, leg);
        PDXObjectImage xosm = new PDJpeg(doc, osm.openStream());

        PDPageContentStream contentStream = new PDPageContentStream(doc, page);

        PDFont font = PDType1Font.HELVETICA_OBLIQUE;

        contentStream.beginText();
        contentStream.setFont(font, 8);
        contentStream.moveTextPositionByAmount(450, 10);
        Date date = new Date();
        contentStream.drawString(date.toString());
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(font, 8);
        contentStream.moveTextPositionByAmount(10, 10);
        contentStream.drawString("GeoFuse Report: mario.basa@gmail.com");
        contentStream.endText();

        contentStream.drawImage(xosm, 20, 160);
        contentStream.drawImage(ximage, 20, 160);
        contentStream.drawImage(xlegend, width - xlegend.getWidth() - 3, 170);

        contentStream.beginText();
        contentStream.setFont(font, 50);
        contentStream.moveTextPositionByAmount(20, 720);
        contentStream.drawString(wpb.getPDF_TITLE());
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(font, 18);
        contentStream.moveTextPositionByAmount(20, 695);
        contentStream.drawString(wpb.getPDF_NOTE());
        contentStream.endText();

        contentStream.setStrokingColor(180, 180, 180);

        float bx[] = { 10f, 10f, 30 + width, 30 + width, 10f };
        float by[] = { 150f, 170 + height, 170 + height, 150f, 150f };
        contentStream.drawPolygon(bx, by);

        contentStream.close();

        doc.save(baos);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (doc != null) {
            doc.close();
        }

        if (wr != null) {
            wr.close();
        }

        if (wl != null) {
            wl.close();
        }
    }

    return baos;
}

From source file:gov.samhsa.c2s.common.pdfbox.enhance.HexPdf.java

License:Apache License

/**
 * Close the current page (if any), and open a new one. Cursor position is
 * reset to top-left corner of writable area (within margins)
 *
 * @see #closePage()/*from w w  w . j  av a2s .c o  m*/
 */
public void newPage() {

    numPages++;
    if (currentPage != null) {
        closePage();
    }

    currentPage = new PDPage();
    float x1 = this.pageSize.getLowerLeftX();
    float y1 = this.pageSize.getLowerLeftY();
    float x2 = this.pageSize.getUpperRightX();
    float y2 = this.pageSize.getUpperRightY();
    float w = this.pageSize.getWidth();
    float h = this.pageSize.getHeight();
    if (orientation == HexPdf.PORTRAIT) {
        pageWidth = w;
        pageHeight = h;
        currentPage.setMediaBox(new PDRectangle(new BoundingBox(x1, y1, x2, y2)));
    } else {
        pageWidth = h;
        pageHeight = w;
        currentPage.setMediaBox(new PDRectangle(new BoundingBox(y1, x1, y2, x2)));
    }

    setDimensions();
    cursorX = contentStartX;
    cursorY = contentStartY;
    try {
        cs = new PDPageContentStream(this, currentPage);
        cs.setFont(font, fontSize);
    } catch (IOException ex) {
        Logger.getLogger(HexPdf.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:GUI.Helper.PDFIOHelper.java

public static void writeSummaryReport(MainController mc) {

    mc.selectStep(6);/*from   ww  w .  j  av  a2 s  .co  m*/
    FileChooser fc = new FileChooser();
    fc.setTitle("Save WZITS Tool Project");
    fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File (.pdf)", "*.pdf"));
    if (mc.getProject().getSaveFile() != null) {
        File initDir = mc.getProject().getSaveFile().getParentFile();
        if (initDir.isDirectory()) {
            fc.setInitialDirectory(initDir);
        }
    }
    File saveFile = fc.showSaveDialog(MainController.getWindow()); //mc.getMainWindow()
    if (saveFile != null) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                boolean exportSuccess = true;
                try {
                    PDDocument doc = new PDDocument();
                    for (int factSheetIdx = 1; factSheetIdx <= 8; factSheetIdx++) {

                        Node n = mc.goToFactSheet(factSheetIdx, true);
                        MainController.getStage().show();
                        BorderPane bp = (BorderPane) ((ScrollPane) n).getContent();

                        PDPage page = new PDPage();
                        doc.addPage(page);

                        PDPageContentStream content = new PDPageContentStream(doc, page);

                        WritableImage wi = bp.snapshot(new SnapshotParameters(), null);

                        double prefHeight = wi.getHeight();
                        double prefWidth = wi.getWidth();
                        BufferedImage bi = SwingFXUtils.fromFXImage(wi, null);

                        PDImageXObject ximage = LosslessFactory.createFromImage(doc, bi);
                        int drawWidth = (int) Math.min(MAX_DRAW_WIDTH, Math.round(WIDTH_FACTOR * prefWidth));
                        int drawHeight = (int) Math.round(HEIGHT_FACTOR * prefHeight);
                        int numPages = (int) Math.ceil(drawHeight / MAX_DRAW_HEIGHT);
                        drawHeight = (int) Math.min(MAX_DRAW_HEIGHT, drawHeight);
                        content.drawImage(ximage, MARGIN_LEFT_X, MARGIN_TOP_Y - drawHeight, drawWidth,
                                drawHeight);
                        content.fillAndStroke();
                        content.close();
                    }
                    drawReportHeaderFooter(doc, mc.getProject(), true);
                    doc.save(saveFile);
                    doc.close();
                } catch (IOException ie) {
                    System.out.println("ERROR");
                    exportSuccess = false;
                }
                if (exportSuccess) {
                    Alert al = new Alert(Alert.AlertType.CONFIRMATION);
                    al.setTitle("WZITS Tool");
                    al.setHeaderText("Fact sheet export successful");
                    al.showAndWait();
                } else {
                    Alert al = new Alert(Alert.AlertType.WARNING);
                    al.setTitle("WZITS Tool");
                    al.setHeaderText("Fact sheet export failed");
                    al.showAndWait();
                }
                mc.selectStep(6);
            }
        });
    }
}

From source file:GUI.Helper.PDFIOHelper.java

public static void writeStepSummary(MainController mc, int factSheetIdx) {
    Node n = mc.goToFactSheet(factSheetIdx, false);
    FileChooser fc = new FileChooser();
    fc.setTitle("Save WZITS Tool Project");
    fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File (.pdf)", "*.pdf"));
    if (mc.getProject().getSaveFile() != null) {
        File initDir = mc.getProject().getSaveFile().getParentFile();
        if (initDir.isDirectory()) {
            fc.setInitialDirectory(initDir);
        }/*from   w ww  . j a v a2  s.  c  o  m*/
    }
    File saveFile = fc.showSaveDialog(MainController.getWindow()); //mc.getMainWindow()
    if (saveFile != null) {

        BorderPane bp = (BorderPane) ((ScrollPane) n).getContent();
        //Scene scene = new Scene(bp);
        //n.applyCss();
        //bp.applyCss();
        //WritableImage wi = scene.snapshot(null);

        WritableImage wi = bp.snapshot(new SnapshotParameters(), null);

        double prefHeight = wi.getHeight();
        double prefWidth = wi.getWidth();

        BufferedImage bi = SwingFXUtils.fromFXImage(wi, null);
        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        boolean exportSuccess = false;
        try {
            //ImageIO.write(bi, "png", new File("test.png"));
            PDPageContentStream content = new PDPageContentStream(doc, page);
            PDImageXObject ximage = LosslessFactory.createFromImage(doc, bi);
            int drawWidth = (int) Math.min(MAX_DRAW_WIDTH, Math.round(WIDTH_FACTOR * prefWidth));
            int drawHeight = (int) Math.round(HEIGHT_FACTOR * prefHeight);
            int numPages = (int) Math.ceil(drawHeight / MAX_DRAW_HEIGHT);
            drawHeight = (int) Math.min(MAX_DRAW_HEIGHT, drawHeight);
            content.drawImage(ximage, MARGIN_LEFT_X, MARGIN_TOP_Y - drawHeight, drawWidth, drawHeight);
            content.fillAndStroke();
            content.close();
            drawReportHeaderFooter(doc, mc.getProject(), true);
            doc.save(saveFile);
            doc.close();
            exportSuccess = true;
        } catch (IOException ie) {
            System.out.println("ERROR");
        }
        if (exportSuccess) {
            Alert al = new Alert(Alert.AlertType.CONFIRMATION);
            al.setTitle("WZITS Tool");
            al.setHeaderText("Fact sheet export successful");
            al.showAndWait();
        } else {
            Alert al = new Alert(Alert.AlertType.WARNING);
            al.setTitle("WZITS Tool");
            al.setHeaderText("Fact sheet export failed");
            al.showAndWait();
        }
    }
}

From source file:jgnash.PDFBoxTableTest.java

License:Open Source License

@Test
void simpleTest() throws IOException {

    Path tempPath = null;/*from  w  w w. j  a  va2 s. com*/

    try (PDDocument doc = new PDDocument()) {
        tempPath = Files.createTempFile("test", ".pdf");
        System.out.println(tempPath);

        PDPage page = new PDPage();
        doc.addPage(page);

        PDFont font = PDType1Font.HELVETICA;

        try (final PDPageContentStream contents = new PDPageContentStream(doc, page)) {
            contents.beginText();
            contents.setFont(font, 11);
            contents.newLineAtOffset(100, 700);
            contents.showText("Hello World!");
            contents.endText();
        }

        doc.save(tempPath.toFile());
    } catch (final IOException e) {
        e.printStackTrace();
    } finally {
        if (tempPath != null) {
            Files.deleteIfExists(tempPath);
        }
    }
}

From source file:johnbrooksupgrade.PDFService.java

private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
    Salesman = txtNewUser.getText().isEmpty() ? cmbSalesPerson.getSelectedItem().toString()
            : txtNewUser.getText();/*from   ww w . j  a  v a  2  s  .c  o m*/
    Date = DateInput.getText();
    String ClientName = ClientnameInput.getText();
    String ProjectName = ProjectNameInput.getText();

    if (Branch == null) {
        JOptionPane.showMessageDialog(null, "Please Select a branch and try again.", "Error",
                JOptionPane.ERROR_MESSAGE);
    } else {
        /*** 
         * This is the logic that prints the information to a PDF 
         ***/

        //We want to save the file to Windows' temporary files folder so it can be loaded from there straight away
        //This temporary file is deleted when the program is exited
        File myfile = new File("C:\\Windows\\Temp\\ConveyorFile.pdf");

        //creates a new pdf
        if ((myfile) != null) {
            try {
                PDDocument doc;
                PDPage page;

                doc = new PDDocument();

                // Create a new blank page and add it to the document
                page = new PDPage();
                doc.addPage(page);
                PDFont font = PDType1Font.COURIER_BOLD;
                PDPageContentStream content = new PDPageContentStream(doc, page);
                content.beginText();
                content.setFont(font, 30);

                // creates a new page and gives it formatting of text
                content.moveTextPositionByAmount(110, 600);
                content.drawString("Technical Specifications ");
                PDFont font2 = PDType1Font.COURIER;
                content.setFont(font, 14);
                content.moveTextPositionByAmount(-50, -65);
                content.drawString("Date:" + Date);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Sales person: " + Salesman);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Client Name: " + ClientName);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Project Name: " + ProjectName);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Branch: " + Branch);
                content.moveTextPositionByAmount(0, -32);

                // Specifications    
                content.setFont(PDType1Font.COURIER_BOLD, 20);
                content.drawString("Specifications");
                content.moveTextPositionByAmount(0, -10);
                content.setFont(font, 14);
                content.moveTextPositionByAmount(10, -14);
                content.drawString("Speed of Belt M/pm: " + mainDataEntry.Speedofbeltanswer29f);
                content.moveTextPositionByAmount(0, -14);
                content.drawString(
                        "Drum/Sprocket  Mtrs: " + String.format("%.2f", mainDataEntry.Drumdiameterinput1));
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Metres per minute: " + mainDataEntry.getMetresperminuteanswer4f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Metres per hour: " + mainDataEntry.getMetresperhouranswer5f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Product per hour: " + mainDataEntry.getLengthperhouranswer7f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Kg's per hour: " + mainDataEntry.getKgsperhouranswer9f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Kg at any given time: " + mainDataEntry.getKgatanygiventimeanswer10f());
                content.moveTextPositionByAmount(-10, -28);

                // Results
                content.setFont(PDType1Font.COURIER_BOLD, 20);
                content.drawString("Results");
                content.moveTextPositionByAmount(0, -10);
                content.setFont(font, 14);
                content.moveTextPositionByAmount(10, -14);
                content.drawString("RPM: " + String.format("%.2f", mainDataEntry.getRpmconveyor34()));
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Application Factor: " + mainDataEntry.getRadiananswer25f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Pull Force Kg/f: " + mainDataEntry.PullForce);
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Nm Torque: " + mainDataEntry.getNmanswer15f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Service Factor: " + mainDataEntry.getServicefactor17f());
                content.moveTextPositionByAmount(0, -14);
                content.drawString("Design Kw: " + mainDataEntry.getDesignkwanswer18f());
                content.moveTextPositionByAmount(-10, -28);

                // Gearbox recommendations 

                // only bother with section if the gearbox details aren't empty
                if (!mainDataEntry.GearboxDetailsForPDF.isEmpty()) {
                    content.setFont(PDType1Font.COURIER_BOLD, 20);
                    content.drawString("Gearbox/Motor Recommendations");
                    content.moveTextPositionByAmount(2, -25);
                    content.setFont(PDType1Font.COURIER_BOLD, 18);
                    content.drawString(mainDataEntry.GearboxType + ":");
                    content.setFont(font, 14);
                    content.moveTextPositionByAmount(10, -25);

                    String[] display;

                    // For the brooks cyclo we need to split the string by these values
                    // then write each index of the resulting array separately so the
                    // result doesn't just run off the page
                    display = mainDataEntry.GearboxDetailsForPDF.get(0).split("Ratio: |Overload ");

                    // Only need to do this when the string has been split out by Ratio or Overload
                    // i.e. this is only the case for brooks cyclo, the other two types fit the page fine
                    if (display.length > 1) {
                        display[1] = "Ratio: " + display[1];
                        content.drawString(display[0]);
                        content.moveTextPositionByAmount(0, -14);
                        content.drawString(display[1]);

                        if (display.length > 2) {
                            display[2] = "Overload " + display[2];
                            content.moveTextPositionByAmount(0, -14);
                            content.drawString(display[2]);
                        }
                    } else {
                        // first option must exist for the program to get this far
                        content.drawString(mainDataEntry.GearboxDetailsForPDF.get(0));
                    }

                    content.moveTextPositionByAmount(0, -14);

                    // only bother with the second option if it exists
                    if (mainDataEntry.GearboxDetailsForPDF.size() > 1) {
                        display = mainDataEntry.GearboxDetailsForPDF.get(1).split("Ratio: |Overload ");

                        if (display.length > 1) {
                            content.moveTextPositionByAmount(0, -15);
                            display[1] = "Ratio: " + display[1];
                            content.drawString(display[0]);
                            content.moveTextPositionByAmount(0, -14);
                            content.drawString(display[1]);

                            if (display.length > 2) {
                                display[2] = "Overload " + display[2];
                                content.moveTextPositionByAmount(0, -14);
                                content.drawString(display[2]);
                            }
                        } else {
                            content.moveTextPositionByAmount(0, -14);
                            content.drawString(mainDataEntry.GearboxDetailsForPDF.get(1));
                        }
                    }
                }

                content.endText();

                image2 = ImageIO.read(new File("logosmall.jpg"));
                BufferedImage logo = image2;
                // writes the image to the file

                PDXObjectImage jblogo = new PDPixelMap(doc, logo);

                content.drawImage(jblogo, 20, 650);
                //postions image
                content.close();
                doc.getDocument();
                doc.save(myfile.getAbsolutePath());

                // open the file 
                Desktop.getDesktop().open(myfile);

                doc.close();
                close();
                //saves pdf and closes it
            } catch (IOException | COSVisitorException ie) {
                JOptionPane.showMessageDialog(null, ie.getMessage(), "Error!", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }
}

From source file:model.util.pdf.PDFUtils.java

License:Apache License

/**
 * Test: Create pdf from image and pdf file.
 *
 * @param _inputFile    pdf input//from  w  w w  .  j  a v  a 2s.c o m
 * @param _imagePath    image input
 * @param _outputFile    pdf output
 *
 * @throws IOException occurs if reading the data fails.
 */
public void saveAsPdf(String _imagePath, String _outputFile) throws IOException {

    PDDocument doc = null;
    try {

        // create new document and insert empty page to the document.
        doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

        // createFromFile is the easiest way with an image file
        // if you already have the image in a BufferedImage, 
        // call LosslessFactory.createFromImage() instead
        PDImageXObject pdImage = PDImageXObject.createFromFile(_imagePath, doc);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        // reduce this value if the image is too large
        float scale = 1f;
        contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth() * scale, pdImage.getHeight() * scale);

        contentStream.close();
        doc.save(_outputFile);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}

From source file:net.heksemann.hexpdf.HexPDF.java

License:Apache License

/**
 * Close the current page (if any), and open a new one. Cursor position is
 * reset to top-left corner of writable area (within margins)
 *
 * @see #closePage()/*from  w  ww  .  jav a2s .c  o m*/
 */
public void newPage() {

    numPages++;
    if (currentPage != null) {
        closePage();
    }

    currentPage = new PDPage();
    float x1 = this.pageSize.getLowerLeftX();
    float y1 = this.pageSize.getLowerLeftY();
    float x2 = this.pageSize.getUpperRightX();
    float y2 = this.pageSize.getUpperRightY();
    float w = this.pageSize.getWidth();
    float h = this.pageSize.getHeight();
    if (orientation == HexPDF.PORTRAIT) {
        pageWidth = w;
        pageHeight = h;
        currentPage.setMediaBox(new PDRectangle(new BoundingBox(x1, y1, x2, y2)));
    } else {
        pageWidth = h;
        pageHeight = w;
        currentPage.setMediaBox(new PDRectangle(new BoundingBox(y1, x1, y2, x2)));
    }

    setDimensions();
    cursorX = contentStartX;
    cursorY = contentStartY;
    try {
        cs = new PDPageContentStream(this, currentPage);
        cs.setFont(font, fontSize);
    } catch (IOException ex) {
        Logger.getLogger(HexPDF.class.getName()).log(Level.SEVERE, null, ex);
    }
}