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

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

Introduction

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

Prototype

public PDDocument() 

Source Link

Document

Creates an empty PDF document.

Usage

From source file:fr.amap.commons.javafx.chart.ChartViewer.java

/**
 * A handler for the export to PDF option in the context menu.
 *//* w  w w  . j av a  2s.c o m*/
private void handleExportToPDF() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setSelectedExtensionFilter(
            new FileChooser.ExtensionFilter("Portable Document Format (PDF)", "pdf"));
    fileChooser.setTitle("Export to PDF");
    File file = fileChooser.showSaveDialog(stage);
    if (file != null) {

        try {

            CanvasPositionsAndSize canvasPositionAndSize = getCanvasPositionAndSize();

            PDDocument doc = new PDDocument();

            PDPage page = new PDPage(new PDRectangle((float) canvasPositionAndSize.totalWidth,
                    (float) canvasPositionAndSize.totalHeight));
            doc.addPage(page);

            BufferedImage image = new BufferedImage((int) canvasPositionAndSize.totalWidth,
                    (int) canvasPositionAndSize.totalHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = image.createGraphics();

            int index = 0;
            for (ChartCanvas canvas : chartCanvasList) {

                Rectangle2D rectangle2D = canvasPositionAndSize.positionsAndSizes.get(index);

                ((Drawable) canvas.chart).draw(g2, new Rectangle((int) rectangle2D.getX(),
                        (int) rectangle2D.getY(), (int) rectangle2D.getWidth(), (int) rectangle2D.getHeight()));
                index++;
            }

            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false);
            PDXObjectImage pdImage = new PDPixelMap(doc, image);
            contentStream.drawImage(pdImage, 0, 0);

            PDPageContentStream cos = new PDPageContentStream(doc, page);
            cos.drawXObject(pdImage, 0, 0, pdImage.getWidth(), pdImage.getHeight());
            cos.close();

            doc.save(file);

        } catch (IOException | COSVisitorException ex) {
            Logger.getLogger(ChartViewer.class.getName()).log(Level.SEVERE, null, ex);
        }
        /*ExportUtils.writeAsPDF(this.chart, (int)canvas.getWidth(),
        (int)canvas.getHeight(), file);*/

        /*ExportUtils.writeAsPDF(this.chart, (int)canvas.getWidth(),
                (int)canvas.getHeight(), file);*/
    }
}

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);//  ww w .ja  v a 2  s .  com
    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:generarPDF.GenerarFactura.java

public PDDocument crearFactura(int facturaID, JFrame dialogo) {

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

        ControladorFactura controladorFactura = new ControladorFactura();
        Factura facturaActual = controladorFactura.getFactura(" where factura_id=" + facturaID).get(0);

        ControladorCliente controladorCliente = new ControladorCliente();
        Cliente cliente = controladorCliente.obtenerClientePorID(facturaActual.getCliente_id());

        System.out.println(cliente.getCliente_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);
        System.out.println("llego aqui -10");

        contenido.drawString("Factura #" + facturaActual.getFactura_id());
        contenido.endText();
        System.out.println("llego aqui -11");

        contenido.beginText();
        contenido.setFont(font, 12);
        contenido.moveTextPositionByAmount(30, 700);
        contenido.drawString(nombreEmpresa + " NIT: " + NITEmpresa);
        contenido.endText();

        contenido.beginText();
        contenido.setFont(font, 12);
        contenido.moveTextPositionByAmount(30, 680);
        contenido.drawString(direccionEmpresa);
        contenido.endText();

        contenido.beginText();
        contenido.setFont(fontNormal, 11);
        contenido.moveTextPositionByAmount(30, 650);
        contenido.drawString("Fecha:" + facturaActual.getFecha());
        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(200, 590);
        contenido.drawString("DETALLE DE LA FACTURA");
        contenido.endText();

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

        //Dibujar tabla de productos
        ControladorFactura_Productos controladorFactura_Productos = new ControladorFactura_Productos();
        ArrayList<Factura_Productos> listaProductosFactura = controladorFactura_Productos
                .getTodosFactura_Productos(" where factura_id=" + facturaID);

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

        contenido.beginText();
        contenido.setFont(fontNormal, 12);
        contenido.moveTextPositionByAmount(60, 560);
        contenido.drawString("Producto");
        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("Valor unitario");
        contenido.endText();
        contenido.drawLine(300, 550, 300, 570);

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

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

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

        int altura = 550;
        ControladorProducto controladorProducto = new ControladorProducto();

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

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

        //Primer pagina
        for (int i = 0; i < listaProductosFactura.size() && altura >= 30; i++) {
            //Imprime por paginas
            Factura_Productos facturaProducto = listaProductosFactura.get(i);
            Productos productoActual = controladorProducto
                    .getProducto(" where producto_id=" + facturaProducto.getProducto_id()).get(0);

            String nombreProducto = productoActual.getNombre();

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

            Double totalProducto = productoActual.getPrecio() * facturaProducto.getUnidades();
            NumberFormat formatter = new DecimalFormat("#0");

            String valorUnitario = String.valueOf(productoActual.getPrecio());
            String unidades = String.valueOf(facturaProducto.getUnidades());
            String valorTotal = String.valueOf(formatter.format(totalProducto));

            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(nombreProducto);
            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(valorUnitario);
            contenido.endText();
            contenido.drawLine(300, altura, 300, altura - 30);

            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(320, altura - 15);
            contenido.drawString(unidades);
            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 = facturaActual.getValor();
            Double ivaCalculado = Math.ceil(valor * Double.parseDouble(IVA) / 100);
            Double subtotal = Math.floor(valor * (1 - Double.parseDouble(IVA) / 100));

            NumberFormat formatter = new DecimalFormat("#0");
            String valorFormateado = formatter.format(valor);

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

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

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

            altura -= 30;
            contenido.beginText();
            contenido.setFont(fontNormal, 12);
            contenido.moveTextPositionByAmount(320, altura - 15);
            contenido.drawString("IVA " + IVA + "%");
            contenido.endText();
            contenido.drawLine(380, altura, 380, altura - 30);

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

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

            contenido.beginText();
            contenido.setFont(font, 12);
            contenido.moveTextPositionByAmount(400, altura - 15);
            contenido.drawString(valorFormateado);
            contenido.endText();
            contenido.drawLine(500, altura, 500, altura - 30);
            //Linea inferior
            contenido.drawLine(320, altura - 30, 500, altura - 30);
            contenido.drawLine(320, altura, 320, altura - 30);

            //Informacion legal
            altura -= 40;
            contenido.beginText();
            contenido.setFont(fontNormal, 10);
            contenido.moveTextPositionByAmount(50, altura);
            contenido.drawString(informacionLegalFactura);
            contenido.endText();

        }

        //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 < listaProductosFactura.size() && altura >= 30; i++) {
                //Imprime por paginas
                Factura_Productos facturaProducto = listaProductosFactura.get(i);
                Productos productoActual = controladorProducto
                        .getProducto(" where producto_id=" + facturaProducto.getProducto_id()).get(0);

                String nombreProducto = productoActual.getNombre();

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

                Double totalProducto = productoActual.getPrecio() * facturaProducto.getUnidades();
                NumberFormat formatter = new DecimalFormat("#0");

                String valorUnitario = String.valueOf(productoActual.getPrecio());
                String unidades = String.valueOf(facturaProducto.getUnidades());
                String valorTotal = String.valueOf(formatter.format(totalProducto));

                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(nombreProducto);
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(70, altura, 70, altura - 30);
                contenidoSiguiente.drawLine(200, altura, 200, altura - 30);

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

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(font, 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);
                indiceProductos = i + 1;
                altura -= 30;
            }
            //Si no cabe mas cierre el flujo.
            if (indiceProductos < listaProductosFactura.size()) {
                contenidoSiguiente.close();
            }
            //En ultima pagina escribir footer
            if (j == totalPaginas - 1 && altura >= 40) {
                Double valor = facturaActual.getValor();
                Double ivaCalculado = Math.ceil(valor * Double.parseDouble(IVA) / 100);
                Double subtotal = Math.floor(valor * (1 - Double.parseDouble(IVA) / 100));
                NumberFormat formatter = new DecimalFormat("#0");
                String valorFormateado = formatter.format(valor);

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

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

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

                altura -= 30;
                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(320, altura - 15);
                contenidoSiguiente.drawString("IVA " + IVA + "%");
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(380, altura, 380, altura - 30);

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

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

                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 12);
                contenidoSiguiente.moveTextPositionByAmount(400, altura - 15);
                contenidoSiguiente.drawString(valorFormateado);
                contenidoSiguiente.endText();
                contenidoSiguiente.drawLine(500, altura, 500, altura - 30);
                //Linea inferior
                contenidoSiguiente.drawLine(320, altura - 30, 500, altura - 30);
                contenidoSiguiente.drawLine(320, altura, 320, altura - 30);

                //Informacion legal
                altura -= 40;
                contenidoSiguiente.beginText();
                contenidoSiguiente.setFont(fontNormal, 10);
                contenidoSiguiente.moveTextPositionByAmount(50, altura);
                contenidoSiguiente.drawString(informacionLegalFactura);
                contenidoSiguiente.endText();

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

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

        }

        contenido.close();
        return document;

    } catch (Exception e) {
        JOptionPane.showMessageDialog(dialogo,
                "Error al crear la factura\nInformacin Tcnica\n" + e.toString(), "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    }

}

From source file:generarPDF.GenerarReporteDiario.java

public PDDocument crearDiario(Calendar fechaInicial, Calendar fechaFinal, DefaultTableModel modeloTabla,
        JFrame dialogo) {/* w w  w  . j  av  a2 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 {//from   ww  w  . j  a  v  a2s  . com

        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;/*  w  w  w  .  ja va 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:GUI.Helper.PDFIOHelper.java

public static void writeSummaryReport(MainController mc) {

    mc.selectStep(6);/*w  w  w .ja  va2 s . c om*/
    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  w w . java  2  s  .co  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:info.informationsea.venn.graphics.VennDrawPDFTest.java

License:Open Source License

@Test
public void testDraw() throws Exception {
    VennFigure<String> vennFigure = new VennFigure<>();
    vennFigure.addShape(new VennFigure.Oval<>(new VennFigure.Point(0, 0), 0, 100, 100));
    vennFigure.addShape(new VennFigure.Text<>(new VennFigure.Point(0, 0), "Normal"));
    vennFigure.addShape(new VennFigure.Oval<>(new VennFigure.Point(50, 50), 0, 50, 100));
    vennFigure.addShape(new VennFigure.Oval<>(new VennFigure.Point(200, 200), Math.PI / 4, 50, 100));
    vennFigure.addShape(new VennFigure.Oval<>(new VennFigure.Point(150, 0), 0, 50, 20, "#00ff00ff"));
    vennFigure.addShape(new VennFigure.Oval<>(new VennFigure.Point(150, 10), 0, 50, 20, "#ff0000ff"));
    vennFigure.addShape(new VennFigure.Oval<>(new VennFigure.Point(150, 20), 0, 50, 20, "#0000ffff"));
    vennFigure.addShape(new VennFigure.Oval<>(new VennFigure.Point(150, 30), 0, 50, 20, "#00ff0050"));
    vennFigure.addShape(new VennFigure.Oval<>(new VennFigure.Point(150, 40), 0, 50, 20, "#00ff0020"));
    vennFigure.addShape(new VennFigure.Oval<>(new VennFigure.Point(150, 100), 0, 50, 20, "#00ff00"));
    vennFigure.addShape(new VennFigure.Text<>(new VennFigure.Point(200, 200), "Rotated"));
    vennFigure.addShape(new VennFigure.Text<>(new VennFigure.Point(100, 100), "Center"));
    vennFigure//w ww . j av  a 2  s  .c  o m
            .addShape(new VennFigure.Text<>(new VennFigure.Point(100, 120), "Left", VennFigure.TextJust.LEFT));
    vennFigure.addShape(
            new VennFigure.Text<>(new VennFigure.Point(100, 140), "Right", VennFigure.TextJust.RIGHT));

    try (PDDocument doc = new PDDocument()) {
        VennDrawPDF.draw(vennFigure, doc);
        doc.save(new File(DIST_DIR, "test.pdf"));
    }
}

From source file:info.informationsea.venn.VennExporter.java

License:Open Source License

public static <T, U> void exportAsPDF(VennFigureParameters<T> parameters, File file) throws IOException {
    try (PDDocument doc = new PDDocument()) {
        VennDrawPDF.draw(VennFigureCreator.createVennFigure(parameters), doc);
        doc.save(file);// ww  w .  j  ava2 s  . c om
    }
}