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:com.vigglet.pdf.PdfBase.java

protected void createPdfPage() {
    doc = new PDDocument();
    page = new PdfPage(doc);
}

From source file:com.vigglet.pdf.PdfUtil.java

public PdfUtil() {
    doc = new PDDocument();
}

From source file:controladores3.controladorGenerarLiquidaciones.java

public boolean generarLiquidaciones()
        throws FileNotFoundException, TransformerException, IOException, FOPException {

    Thread runnable = new Thread() {
        public void run() {
            try {
                modeloFacturas rutas = new modeloFacturas();
                dfs.setCurrencySymbol("$ ");
                dfs.setGroupingSeparator('.');
                dfs.setMonetaryDecimalSeparator('.');
                ((DecimalFormat) FORMAT).setDecimalFormatSymbols(dfs);
                controladores.controladorPrincipal miControlador = new controladorPrincipal();
                modelos.modeloEmpleados liquidaciones = new modeloEmpleados();
                modelos3.modeloRemuneraciones remuneraciones = new modeloRemuneraciones();
                String[][] data = liquidaciones.obtenerRemuneraciones2(getMes(), getYear());
                String[][] imp2cat = remuneraciones.obtenerTablaImpuesto();
                //                    float uf = remuneraciones.obtenerUF() / 100;
                double uf = remuneraciones.obtenerUF();
                int numEmp = data.length;
                String path = "Liquidaciones " + per;
                File dir = new File(path);
                dir.mkdir();//w  w  w  .j a  v a  2 s.  c  o  m
                //                    int bono300 = miControlador.obtenerBono300();
                for (int i = 0; i < numEmp; i++) {
                    String fileName = path + "/" + data[i][0] + ".pdf"; // name of our file
                    try {
                        PDDocument doc = new PDDocument(); // creating instance of pdfDoc
                        PDPage page = new PDPage();
                        doc.addPage(page); // adding page in pdf doc file
                        int base = Integer.parseInt(data[i][2]) * Integer.parseInt(data[i][28]) / 30;
                        //GRATIFICACION
                        int grat = (int) (base * 0.25);
                        //BONO ANTIGUEDAD
                        int bonoAnt = miControlador.obtenerBonoAnt(data[i][5]);
                        //BONO 300
                        //                            int totalBon300 = bono300 * Integer.parseInt(data[i][9]);
                        int totalBon300 = Integer.parseInt(data[i][27]);
                        //BONO ADICIONAL
                        int bonoAd = Integer.parseInt(data[i][11]);
                        //BONO RESPONSABILIDAD
                        int bonoResp = 0;
                        //BONO ADICIONAL
                        double bonoCol1 = Double.parseDouble(data[i][8]);
                        double bonoCol30 = Double.parseDouble(data[i][9]);
                        double bonoCol = bonoCol1 + bonoCol30 / 2;
                        int totalBonCol = (int) Math.round(((double) base * 0.0077777) * bonoCol);
                        //HORAS EXTRA
                        double horasExNor = Double.parseDouble(data[i][12]);
                        double horasExFes = Double.parseDouble(data[i][13]);
                        double horasEx = 0;
                        double bonoHor = 0;
                        double cantHorEx = 0;
                        //total de horas extras normales = 1; festivas = 2
                        double totalHorex = 0;
                        double resHorEx = 0;
                        if (horasExNor > 45) {
                            cantHorEx = 45;
                            totalHorex = 45;
                            resHorEx = horasExNor - 45;
                        } else {
                            cantHorEx = horasExNor;
                            totalHorex = cantHorEx;
                        }
                        if (cantHorEx + horasExFes > 45) {
                            resHorEx = resHorEx + (horasExFes - 45 + cantHorEx) * 2;
                            totalHorex = 45 - cantHorEx;
                            cantHorEx = 45;
                        } else {
                            cantHorEx += horasExFes;
                            totalHorex += horasExFes * 2;
                        }

                        //BONO ASIGNACION VOLUNTARIA
                        double totalBonoAV = base * 0.0077777 * resHorEx;
                        double valorHorEx = (int) ((double) base * 0.0077777 * totalHorex);
                        //TOTAL IMPONIBLE
                        double totImp = base + grat + bonoAnt + bonoAd + bonoResp + totalBonoAV + totalBonCol
                                + totalBon300 + valorHorEx;
                        //DESCUENTO AFP
                        int descAFP = Integer.parseInt(data[i][21]);
                        int totalAFP = (int) (totImp * ((double) descAFP / 10000));
                        int sis = (int) (totImp * 0.0141);
                        //DESCUENTO SALUD
                        double descSalud = 0, totalSalud = 0;
                        String salud;
                        if (data[i][4].toLowerCase().compareTo("fonasa") == 0) {
                            salud = "FONASA";
                            descSalud = Integer.parseInt(data[i][22]);
                            totalSalud = (int) (totImp * ((double) descSalud / 10000));
                        } else {
                            if (data[i][23].compareTo("") == 0) {
                                salud = data[i][4];
                            } else {
                                salud = data[i][23];
                            }
                            descSalud = ((double) Integer.parseInt(data[i][24]) / 1000) * uf;
                            totalSalud = descSalud;
                        }
                        //DESCUENTO CESANTIA
                        int ces = (int) (totImp * 0.006);
                        int cesEmp = (int) (totImp * 0.024);
                        //DESCUENTOS LEGALES
                        double descLegales = ces + totalSalud + totalAFP;
                        //TOTAL TRIBUTABLE
                        double totTrib = totImp - totalAFP - totalSalud - ces;
                        int descRenta = 0;
                        double totAux = 0;
                        for (String[] imp2cat1 : imp2cat) {
                            if (totTrib > Float.parseFloat(imp2cat1[0]) / 10
                                    && totTrib <= Float.parseFloat(imp2cat1[1]) / 10) {
                                descRenta = (int) (totTrib * Float.parseFloat(imp2cat1[2]) / 1000
                                        - Float.parseFloat(imp2cat1[3]) / 100);
                                totAux = totTrib - descRenta;
                                break;
                            }
                        }
                        //CAJA COMPENSACION
                        int caja = Integer.parseInt(data[i][15]);
                        //ASIGNACION FAMILIAR
                        int af = Integer.parseInt(data[i][16]);
                        //LIQ ALCANZADO
                        double liqAl = totAux - caja;
                        //COLACION 
                        int col = Integer.parseInt(data[i][6]);
                        //TRANSPORTE
                        int trans = Integer.parseInt(data[i][7]);
                        //TOTAL NO IMPONIBLE
                        int noImp = trans + col + af;
                        //ANTICIPO ADELANTO PRESTAMOS
                        int antic = Integer.parseInt(data[i][17]);
                        int adel = Integer.parseInt(data[i][18]);
                        int pres = Integer.parseInt(data[i][19]);
                        int cuo = Integer.parseInt(data[i][20]);
                        int cuoPres = 0;
                        int cuores = Math.max(0, Integer.parseInt(data[i][26]) - 1);
                        if (cuo != 0) {
                            cuoPres = pres / cuo;
                        }
                        //DESCUENTOS MENSUALES
                        int descMensuales = caja + antic + adel + cuoPres + descRenta;
                        //TOTAL HABERES
                        double totalHaberes = noImp + totImp;
                        //TOTAL DESCUENTOS
                        int totDesc = antic + adel + cuoPres + caja;
                        //LIQUIDO
                        double liq = liqAl + col + trans + af - antic - adel - cuoPres;

                        PDPageContentStream content = new PDPageContentStream(doc, page);

                        //HEADER

                        content.beginText();
                        content.setFont(PDType1Font.HELVETICA, 10);
                        content.setLeading(14.5f);
                        content.moveTextPositionByAmount(50, 770);
                        content.showText("GRUAS SANTA TERESITA LTDA.");
                        content.newLineAtOffset(200, 0);
                        content.showText("LIQUIDACIN TRABAJADOR");
                        content.newLineAtOffset(200, 0);
                        content.showText(per);
                        content.newLineAtOffset(-400, 0);
                        content.newLine();
                        content.showText("77.037.960-1");
                        content.newLine();
                        content.newLine();
                        content.showText("Nombre: " + data[i][1]);
                        content.newLineAtOffset(400, 0);
                        content.showText("Contrato: " + data[i][25]);
                        content.newLineAtOffset(-400, 0);
                        content.newLine();
                        content.showText("Rut: " + data[i][0]);
                        content.endText();
                        content.drawLine(30, 700, 600, 700);

                        //LEFT SIDE

                        content.beginText();
                        content.setFont(PDType1Font.HELVETICA, 9);
                        content.setLeading(14.5f);
                        content.moveTextPositionByAmount(120, 650);
                        content.showText("HABERES");
                        content.endText();
                        content.drawLine(45, 645, 245, 645);

                        content.beginText();
                        content.moveTextPositionByAmount(50, 635);
                        content.showText("Sueldo base proporcional");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(base));
                        content.newLineAtOffset(-150, -15);
                        double horex = Double.parseDouble(data[i][13]);
                        if (horex > 45) {
                            horex = 45;
                        }
                        content.showText("Horas extra ( " + cantHorEx + " horas )");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(valorHorEx));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Gratificacin:");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(grat));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Bono aos trabajados");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(bonoAnt));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Bono horas");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totalBon300));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Bono asignacin voluntaria");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totalBonoAV));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Bono adicional");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totalBonCol));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Otros bonos");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(bonoAd));
                        content.endText();

                        content.drawLine(45, 515, 245, 515);
                        content.beginText();
                        content.moveTextPositionByAmount(50, 500);
                        content.showText("Imponible");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totImp));
                        content.newLineAtOffset(-150, -15);
                        content.endText();
                        content.drawLine(45, 493, 245, 493);

                        content.beginText();
                        content.moveTextPositionByAmount(50, 470);
                        content.showText("Colacin");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(col));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Transporte");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(trans));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Asignacin familiar");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(af));
                        content.endText();

                        content.drawLine(45, 425, 245, 425);
                        content.beginText();
                        content.moveTextPositionByAmount(50, 410);
                        content.showText("No imponible");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(noImp));
                        content.endText();
                        content.drawLine(45, 403, 245, 403);

                        content.drawLine(45, 380, 245, 380);
                        content.beginText();
                        content.moveTextPositionByAmount(50, 365);
                        content.showText("Total haberes");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totalHaberes));
                        content.endText();

                        content.beginText();
                        content.setFont(PDType1Font.HELVETICA, 9);
                        content.setLeading(14.5f);
                        content.moveTextPositionByAmount(65, 280);
                        content.showText("APORTES LEGALES EMPLEADOR");
                        content.endText();
                        content.drawLine(45, 275, 245, 275);
                        content.beginText();
                        content.moveTextPositionByAmount(50, 265);
                        content.showText("SIS");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(sis));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Seguro de cesanta empleador");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(cesEmp));
                        content.endText();
                        content.drawLine(45, 243, 245, 243);

                        //RIGHT SIDE
                        content.beginText();
                        content.moveTextPositionByAmount(410, 650);
                        content.showText("DESCUENTOS");
                        content.endText();
                        content.drawLine(345, 645, 545, 645);

                        content.beginText();
                        content.moveTextPositionByAmount(350, 635);
                        content.showText("Descuento AFP");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totalAFP));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Descuento salud");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(totalSalud));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Seguro de cesanta trabajador");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(ces));
                        content.endText();

                        content.drawLine(345, 585, 545, 585);
                        content.beginText();
                        content.moveTextPositionByAmount(350, 570);
                        content.showText("Descuentos legales");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(descLegales));
                        content.endText();
                        content.drawLine(345, 563, 545, 563);

                        content.beginText();
                        content.moveTextPositionByAmount(350, 545);
                        content.showText("Impuesto a la renta");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(descRenta));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Caja de compensacin");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(caja));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Anticipo");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(antic));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Adelanto");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(adel));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Prstamo");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(cuoPres));
                        content.newLineAtOffset(-150, -15);
                        content.showText("Cuotas restantes");
                        content.newLineAtOffset(150, 0);
                        content.showText(String.valueOf(cuores));
                        content.endText();

                        content.drawLine(345, 455, 545, 455);
                        content.beginText();
                        content.moveTextPositionByAmount(350, 440);
                        content.showText("Descuentos mensuales");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(descMensuales));
                        content.endText();
                        content.drawLine(345, 433, 545, 433);

                        content.drawLine(345, 400, 545, 400);
                        content.beginText();
                        content.moveTextPositionByAmount(350, 385);
                        content.showText("Total descuentos");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(descLegales + descMensuales));
                        content.endText();
                        content.drawLine(345, 378, 545, 378);

                        //CENTER
                        content.drawLine(180, 335, 400, 335);
                        content.beginText();
                        content.moveTextPositionByAmount(190, 320);
                        content.showText("Total a pago");
                        content.newLineAtOffset(150, 0);
                        content.showText(FORMAT.format(liq));
                        content.endText();
                        content.drawLine(180, 313, 400, 313);

                        content.close();
                        doc.save(fileName); // saving as pdf file with name perm 
                        doc.close(); // cleaning memory       

                    } catch (IOException e) {
                        System.out.println(e.getMessage());
                    }
                }
                JOptionPane.showMessageDialog(null, "Liquidaciones de sueldo generadas con xito",
                        "Operacin exitosa", JOptionPane.INFORMATION_MESSAGE);
                //                    liquidaciones.limpiarRemuneraciones();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    //runnable.run();
    runnable.start();
    return true;
}

From source file:controladores4.controladorReportes.java

public boolean generarInformeCobranza(final JTable tabla, final int[] rows) {
    DateFormat perDate = new SimpleDateFormat("MMMM-yyyy");
    DateFormat date = new SimpleDateFormat("dd-MM-yyyy");
    final String per = date.format(new Date());
    final NumberFormat FORMAT = NumberFormat.getCurrencyInstance();
    final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    Thread runnable = new Thread() {
        public void run() {
            try {
                dfs.setCurrencySymbol("$ ");
                dfs.setGroupingSeparator('.');
                dfs.setMonetaryDecimalSeparator('.');
                ((DecimalFormat) FORMAT).setDecimalFormatSymbols(dfs);
                String path = "Informes de cobranza/" + tabla.getValueAt(rows[0], 2);
                File dir = new File(path);
                dir.mkdirs();/*from  w  w w  . ja va  2s .  co m*/
                String fileName = path + "/" + per + ".pdf"; // name of our file
                PDDocument doc = new PDDocument();
                PDPage page = new PDPage();
                doc.addPage(page);
                PDPageContentStream content = new PDPageContentStream(doc, page);
                int total = 0;
                modeloClientes model = new modeloClientes();
                String[] data = model.obtenerRutContactoPorRazon(tabla.getValueAt(rows[0], 2).toString());
                try {
                    //HEADER
                    content.beginText();
                    content.setFont(PDType1Font.HELVETICA, 10);
                    content.setLeading(14.5f);
                    content.moveTextPositionByAmount(50, 770);
                    content.endText();

                    content.drawLine(30, 750, 600, 750);
                    File imagen = new File(("src/icono/Logo_Gruas.bmp"));
                    String imPath = imagen.getAbsolutePath();
                    System.out.println(imPath);
                    PDImageXObject image = PDImageXObject.createFromFile(imPath, doc);
                    content.drawImage(image, 50, 600);

                    content.beginText();
                    content.moveTextPositionByAmount(400, 680);
                    content.showText("INFORME COBRANZA");
                    content.newLine();
                    content.showText(per);
                    content.newLineAtOffset(-130, -80);
                    content.showText("CLIENTE");
                    content.newLine();
                    content.endText();

                    content.drawLine(30, 580, 600, 580);

                    content.beginText();
                    content.moveTextPositionByAmount(50, 560);
                    content.showText("Rut: ");
                    content.newLineAtOffset(100, 0);
                    content.showText(data[0]);
                    content.newLineAtOffset(-100, -15);
                    content.showText("Razn Social:");
                    content.newLineAtOffset(100, 0);
                    content.showText(data[1]);
                    content.newLineAtOffset(-100, -15);
                    content.showText("Contacto:");
                    content.newLineAtOffset(100, 0);

                    content.newLine();
                    content.endText();

                    content.drawLine(30, 510, 600, 510);

                    content.beginText();
                    content.moveTextPositionByAmount(50, 480);
                    content.showText(
                            "Estimado cliente, las facturas que se exponen a continuacin se encuentran pendientes");
                    content.newLine();
                    content.showText("de pago. Favor regularizar la situacin.");
                    content.endText();

                    content.drawLine(30, 440, 600, 440);

                    content.beginText();
                    content.moveTextPositionByAmount(70, 430);
                    content.showText("N Folio");
                    content.newLineAtOffset(70, 0);
                    content.showText("Fecha");
                    content.newLineAtOffset(70, 0);
                    content.showText("Das emisin");
                    content.newLineAtOffset(80, 0);
                    content.showText("Total factura");
                    content.newLineAtOffset(80, 0);
                    content.showText("Monto abono");
                    content.newLineAtOffset(80, 0);
                    content.showText("Saldo deuda");
                    content.newLineAtOffset(80, 0);
                    content.endText();

                    content.drawLine(30, 425, 600, 425);

                    content.beginText();
                    content.moveTextPositionByAmount(75, 390);
                    for (int row : rows) {
                        String folio = tabla.getValueAt(row, 0).toString();
                        String fecha = tabla.getValueAt(row, 3).toString();
                        String dias = tabla.getValueAt(row, 4).toString();
                        int monto = Integer.parseInt(tabla.getValueAt(row, 7).toString());
                        int abono = Integer.parseInt(tabla.getValueAt(row, 11).toString());
                        int saldo = Integer.parseInt(tabla.getValueAt(row, 12).toString());
                        total += saldo;

                        content.showText(folio);
                        content.newLineAtOffset(60, 0);
                        content.showText(fecha);
                        content.newLineAtOffset(90, 0);
                        content.showText(dias);
                        content.newLineAtOffset(70, 0);
                        content.showText(FORMAT.format(monto));
                        content.newLineAtOffset(80, 0);
                        content.showText(FORMAT.format(abono));
                        content.newLineAtOffset(80, 0);
                        content.showText(FORMAT.format(saldo));
                        content.newLineAtOffset(-380, -15);
                    }

                    content.newLineAtOffset(310, -45);
                    content.showText("Total deuda");
                    content.newLineAtOffset(70, 0);
                    content.showText(FORMAT.format(total));
                    content.endText();

                    content.close();
                    doc.save(fileName); // saving as pdf file with name perm 
                    doc.close(); // cleaning memory 

                } catch (Exception e) {
                    e.printStackTrace();
                }

                JOptionPane.showMessageDialog(null, "Informe de cobranza generado con xito",
                        "Operacin exitosa", JOptionPane.INFORMATION_MESSAGE);
                //                    liquidaciones.limpiarRemuneraciones();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    //runnable.run();
    runnable.start();
    return true;
}

From source file:controldeadministradores.Admin.java

public void crearPDF(String file, String body) throws Exception {
    String outputFileName = file + ".pdf";
    //        if (args.length > 0)
    //            outputFileName = args[0];

    // Create a document and add a page to it
    PDDocument document = new PDDocument();
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    // PDPage.PAGE_SIZE_LETTER is also possible
    PDRectangle rect = page1.getMediaBox();
    // rect can be used to get the page width and height
    document.addPage(page1);/*from w  w  w . ja va  2  s.c o  m*/

    // Create a new font object selecting one of the PDF base fonts
    PDFont fontPlain = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;
    PDFont fontItalic = PDType1Font.HELVETICA_OBLIQUE;
    PDFont fontMono = PDType1Font.COURIER;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream cos = new PDPageContentStream(document, page1);

    int line = 0;

    // Define a text content stream using the selected font, move the cursor and draw some text
    cos.beginText();
    cos.setFont(fontPlain, 14);
    cos.moveTextPositionByAmount(100, rect.getHeight() - 50 * (++line));
    cos.drawString("Reporte de " + file);
    cos.endText();

    String[] txtLine = body.split("-");
    for (int k = 0; k < txtLine.length; k++) {
        cos.beginText();
        cos.setFont(fontPlain, 12);
        cos.moveTextPositionByAmount(100, rect.getHeight() - 50 * (++line));
        cos.drawString(txtLine[k]);
        cos.endText();
        cos.close();
    }

    // Make sure that the content stream is closed:

    // Save the results and ensure that the document is properly closed:
    document.save(outputFileName);
    document.close();
}

From source file:controller.PDFServlet.java

License:Apache License

/**
 * This method processes requests from the progress note page for both HTTP
 * <code>GET</code> and <code>POST</code> methods. The progress note data
 * retrieved from the request is written as a PDF document.
 *
 * @param request servlet request/*from   ww  w  . j av a 2  s. c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    ProgressNote progressNote = (ProgressNote) session.getAttribute(SessionObjectUtility.PROGRESS_NOTE);
    Patient patient = progressNote.getPatient();
    response.setContentType("text/html;charset=UTF-8");
    int yPosition = 705;
    int xPosition = 70;
    int lineCount;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    String yesOrNo;
    String nextYesOrNo;
    try (PDDocument doc = new PDDocument()) {

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

        try {
            PDPageContentStream content = new PDPageContentStream(doc, page);

            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TITLE_FONT_SIZE);
            content.moveTextPositionByAmount(225, MAXIMUM_Y_POSITION);
            content.drawString("Progress Note");
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, DATE_FONT_SIZE);
            content.moveTextPositionByAmount(245, 725);
            content.drawString(progressNote.getDateCreated().toString());
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Patient Name: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString(patient.getFirstName() + " " + patient.getLastName());
            content.endText();

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Telephone: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(patient.getContactNumber()));
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   DOB: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + patient.getBirthDate());
            content.endText();

            String[] noteLines = getNoteLines((String) nullCheck(progressNote.getPatient().getAddress()),
                    ADDRESS_LINE_LENGTH);

            lineCount = 1;
            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.moveTextPositionByAmount(xPosition, yPosition);
                if (lineCount == 1) {
                    content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
                    content.drawString("Address: ");
                }
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.drawString(s);
                content.endText();
                lineCount++;
            }

            noteLines = getNoteLines((String) nullCheck(patient.getEmailAddress()), ADDRESS_LINE_LENGTH);

            lineCount = 1;
            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.moveTextPositionByAmount(xPosition, yPosition);
                if (lineCount == 1) {
                    content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
                    content.drawString("Email Address: ");
                }
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.drawString(s);
                content.endText();
                lineCount++;
            }

            if (progressNote.getAllergicToMedications() == true) {
                yesOrNo = "yes";
            } else {
                yesOrNo = "no";
            }
            if (progressNote.getMedicalInsurance() == true) {
                nextYesOrNo = "yes";
            } else {
                nextYesOrNo = "no";
            }

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Allergic to medications: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString(yesOrNo);
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("  Medical Insurance: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString(nextYesOrNo);
            content.endText();

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Shoe Size: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getShoeSize()));
            content.endText();

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Allergies: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getAllergies()));
            content.endText();

            noteLines = getNoteLines((String) nullCheck(progressNote.getMedications()), ADDRESS_LINE_LENGTH);

            lineCount = 1;
            for (String s : noteLines) {
                yPosition -= 20;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.moveTextPositionByAmount(xPosition, yPosition);
                if (lineCount == 1) {
                    content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
                    content.drawString("Medications: ");
                }
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.drawString(s);
                content.endText();
                lineCount++;
            }

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Weight(lbs): ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getWeight()));
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   Height(in.): ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            if ((progressNote.getHeightFeet() != null) && (progressNote.getHeightInches() != null)) {
                content.drawString(
                        "" + ((progressNote.getHeightFeet() * 12) + (progressNote.getHeightInches())));
            }
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   BMI: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getBmi()));
            content.endText();

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Waist(in.): ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getWaist()));
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   BP: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            if ((progressNote.getBloodPressureSystole() != null)
                    && (progressNote.getBloodPressureDiastole() != null)) {
                content.drawString(
                        progressNote.getBloodPressureSystole() + "/" + progressNote.getBloodPressureDiastole());
            }
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   Pulse: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getPulse()));
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   Respirations: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getRespirations()));
            content.endText();

            if (progressNote.getFootScreening() == true) {
                yesOrNo = "yes";
            } else {
                yesOrNo = "no";
            }
            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Temperature: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getTemperature()));
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   Foot Screening: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString(yesOrNo);
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.drawString("   Glucose: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getGlucose()));
            content.endText();

            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("A1C: ");
            content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
            content.drawString("" + nullCheck(progressNote.getA1c()));
            content.endText();

            /* nurse or dietitian note */
            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Nurse/Dietitian Note: ");
            content.endText();

            noteLines = getNoteLines((String) nullCheck(progressNote.getNurseOrDietitianNote()),
                    NOTE_LINE_LENGTH);

            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.moveTextPositionByAmount(xPosition, yPosition);
                content.drawString(s);
                content.endText();
            }

            /* subjective section */
            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Subjective: ");
            content.endText();

            noteLines = getNoteLines((String) nullCheck(progressNote.getSubjective()), NOTE_LINE_LENGTH);

            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.moveTextPositionByAmount(xPosition, yPosition);
                content.drawString(s);
                content.endText();
            }

            /* objective section */
            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Objective: ");
            content.endText();

            noteLines = getNoteLines((String) nullCheck(progressNote.getObjective()), NOTE_LINE_LENGTH);

            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.moveTextPositionByAmount(xPosition, yPosition);
                content.drawString(s);
                content.endText();
            }

            /* assessment section */
            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Assessment: ");
            content.endText();

            noteLines = getNoteLines((String) nullCheck(progressNote.getAssessment()), NOTE_LINE_LENGTH);

            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.moveTextPositionByAmount(xPosition, yPosition);
                content.drawString(s);
                content.endText();
            }

            /* plan section */
            yPosition -= LINE_HEIGHT;
            if (yPosition < MINIMUM_Y_POSITION) {
                content.close();
                page = new PDPage();
                doc.addPage(page);
                content = new PDPageContentStream(doc, page);
                yPosition = MAXIMUM_Y_POSITION;
            }
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
            content.moveTextPositionByAmount(xPosition, yPosition);
            content.drawString("Plan: ");
            content.endText();

            noteLines = getNoteLines((String) nullCheck(progressNote.getPlan()), NOTE_LINE_LENGTH);

            for (String s : noteLines) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.moveTextPositionByAmount(xPosition, yPosition);
                content.drawString(s);
                content.endText();
            }

            for (NoteAuthor na : progressNote.getUpdatedBy()) {
                yPosition -= LINE_HEIGHT;
                if (yPosition < MINIMUM_Y_POSITION) {
                    content.close();
                    page = new PDPage();
                    doc.addPage(page);
                    content = new PDPageContentStream(doc, page);
                    yPosition = MAXIMUM_Y_POSITION;
                }
                content.beginText();
                content.setFont(PDType1Font.HELVETICA_BOLD, TEXT_FONT_SIZE);
                content.moveTextPositionByAmount(xPosition, yPosition);
                content.drawString("Updated by: ");
                content.setFont(PDType1Font.HELVETICA, TEXT_FONT_SIZE);
                content.drawString(na.getFirstName() + " " + na.getLastName() + ", " + na.getJobTitle() + ", "
                        + na.getTimeStamp());
                content.endText();
            }
            content.close();
        } catch (IOException e) {
            Logger.getLogger(PDFServlet.class.getName()).log(Level.SEVERE,
                    "An IOException occurred when creating the PDF content.", e);
        }
        doc.addPage(page);
        doc.save(output);
        doc.close();
        String pdfFileName = "pdf-test.pdf";
        response.setContentType("application/pdf");
        response.addHeader("Content-Type", "application/force-download");
        response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);

        response.getOutputStream().write(output.toByteArray());

    } catch (IOException | COSVisitorException e) {
        Logger.getLogger(PDFServlet.class.getName()).log(Level.SEVERE,
                "An exception occurred when creating the PDF document.", e);
    }
}

From source file:correccioncolorpdfs.CorrectorColorUI.java

private void transformarPDF() {
    try {/* w w  w. j a  v  a 2 s.c o  m*/
        //@see http://stackoverflow.com/questions/18189314/convert-a-pdf-file-to-image
        String rutaPDFOriginal = rutaPDF + nombrePDF; // Pdf files are read from this folder
        //String destinationDir = "D:\\Desarrollo\\pruebas\\reportes_negros\\imagenes\\"; // converted images from pdf document are saved here

        File pdfOriginal = new File(rutaPDFOriginal);
        //            File destinationFile = new File(destinationDir);
        //            if (!destinationFile.exists()) {
        //                destinationFile.mkdir();
        //                System.out.println("Folder Created -> " + destinationFile.getAbsolutePath());
        //            }
        if (pdfOriginal.exists()) {
            //System.out.println("Images copied to Folder: " + destinationFile.getName());
            PDDocument document = PDDocument.load(rutaPDFOriginal);

            //Documento Fondo Blanco
            PDDocument documentoCool = new PDDocument();

            List<PDPage> list = document.getDocumentCatalog().getAllPages();
            System.out.println("Total files to be converted -> " + list.size());

            String nombrePDFOriginal = pdfOriginal.getName().replace(".pdf", "");
            int pageNumber = 1;
            for (PDPage page : list) {
                BufferedImage image = page.convertToImage();

                //Inviertiendo colores
                //@see http://stackoverflow.com/questions/8662349/convert-negative-image-to-positive
                for (int x = 0; x < image.getWidth(); x++) {
                    for (int y = 0; y < image.getHeight(); y++) {
                        int rgba = image.getRGB(x, y);
                        //Hexa a reemplazar e9e9e1 R=233|G=233|B=225
                        Color col = new Color(rgba, true);
                        col = new Color(255 - col.getRed(), 255 - col.getGreen(), 255 - col.getBlue());

                        //Si color es igual al invertido - cambiarlo a blanco
                        if (col.getRGB() == -1447455) {
                            col = new Color(255, 255, 255);
                        }
                        //System.out.println("col.getR = " + col.getRGB());
                        image.setRGB(x, y, col.getRGB());
                    }
                }
                //                    File outputfile = new File(destinationDir + fileName + "_" + pageNumber + ".png");
                //                    System.out.println("Image Created -> " + outputfile.getName());
                //                    ImageIO.write(image, "png", outputfile);
                pageNumber++;

                //Crear pagina nueva para el PDF Convertido
                float width = image.getWidth();
                float height = image.getHeight();
                PDPage paginaSinFondo = new PDPage(new PDRectangle(width, height));
                documentoCool.addPage(paginaSinFondo);
                PDXObjectImage img = new PDJpeg(documentoCool, image);
                PDPageContentStream contentStream = new PDPageContentStream(documentoCool, paginaSinFondo);
                contentStream.drawImage(img, 0, 0);
                contentStream.close();

            }
            document.close();
            rutaPDFImprimible = rutaPDF + nombrePDFOriginal + "_imprimible.pdf";
            documentoCool.save(rutaPDFImprimible);
            documentoCool.close();

            estadoConversion(true);
        } else {
            JOptionPane.showMessageDialog(this,
                    "No se logr identificar la ruta del archivo, por favor verifique que el archivo si existe o no halla sido movido durante el proceso.",
                    "Ruta de archivo no encontrada", JOptionPane.WARNING_MESSAGE);
        }

    } catch (IOException | COSVisitorException | HeadlessException e) {
        estadoConversion(false);
        JOptionPane.showMessageDialog(this, e.getMessage(), "Error durante el proceso de conversin",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:costumetrade.common.util.PdfUtils.java

License:Open Source License

public static PDDocument createImagePdf(File file) {

    PDPageContentStream contentStream = null;
    try {/*from   w w  w. j  a v a2  s .c o m*/
        BufferedImage bimg = ImageIO.read(file);
        PDDocument document = new PDDocument();
        PDPage page = new PDPage(new PDRectangle(bimg.getWidth(), bimg.getHeight()));
        document.addPage(page);
        PDImageXObject image = PDImageXObject.createFromFileByExtension(file, document);
        contentStream = new PDPageContentStream(document, page);
        contentStream.drawImage(image, 0, 0);
        return document;
    } catch (IOException e) {
        throw new RuntimeException("?PDF", e);
    } finally {
        IOUtils.closeQuietly(contentStream);
    }

}

From source file:CTRL.ExportController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w w . ja v a  2s .c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    HttpSession session = request.getSession();

    LijstLesmomentenViewModel vmLesmomentenFinal = (LijstLesmomentenViewModel) session
            .getAttribute("vmLesmomentenFinal");

    // Create a document and add a page to it
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);

    // Create a new font object selecting one of the PDF base fonts
    PDFont font = PDType1Font.HELVETICA_BOLD;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
    contentStream.beginText();
    contentStream.setFont(font, 16);
    contentStream.moveTextPositionByAmount(60, 700);

    // Titel
    contentStream.drawString("Lessenrooster");

    contentStream.setFont(font, 10);
    contentStream.moveTextPositionByAmount(0, -20);

    int recordTeller = 0;
    for (Lesmoment l : vmLesmomentenFinal.getLesmomenten()) {

        Calendar c = Calendar.getInstance();
        c.setTime(l.getDatum());
        int dag = c.get(Calendar.DAY_OF_WEEK);

        String strDag = "";

        switch (dag) {
        case 0:
            strDag = "Zondag";
            break;
        case 1:
            strDag = "Maandag";
            break;
        case 2:
            strDag = "Dinsdag";
            break;
        case 3:
            strDag = "Woensdag";
            break;
        case 4:
            strDag = "Donderdag";
            break;
        case 5:
            strDag = "Vrijdag";
            break;
        case 6:
            strDag = "Zaterdag";
            break;
        }

        //Nieuwe page beginnen wanner 25 records werden weggeschreven
        if (recordTeller == 25) {
            recordTeller = 0;
            contentStream.endText();
            contentStream.close();

            page = new PDPage();
            document.addPage(page);
            contentStream = new PDPageContentStream(document, page);
            contentStream.beginText();
            contentStream.setFont(font, 10);
            contentStream.moveTextPositionByAmount(60, 700);
        } else {
            recordTeller++;
        }

        contentStream.drawString(l.getDatum().toString() + "     " + strDag + "     " + l.getBeginuur()
                + "     " + l.getEinduur() + "     " + l.getLokaal() + "     " + l.getModule().getCode()
                + "     " + l.getModule().getNaam());
        contentStream.moveTextPositionByAmount(0, -20);
    }

    contentStream.endText();

    // Make sure that the content stream is closed:
    contentStream.close();

    try {
        // Save the results and ensure that the document is properly closed:
        document.save("C:\\Temp\\test.pdf");
    } catch (COSVisitorException ex) {
        Logger.getLogger(ExportController.class.getName()).log(Level.SEVERE, null, ex);
    }
    document.close();

    //Teruggaan naar resultaat pagina
    RequestDispatcher dispatcher = request.getRequestDispatcher("Resultaat.jsp");
    dispatcher.forward(request, response);
}

From source file:ddf.catalog.transformer.input.pdf.GeoPdfDocumentGenerator.java

License:Open Source License

public static PDDocument generateEmptyPdf() {
    PDDocument pdDocument = new PDDocument();
    pdDocument.addPage(new PDPage());
    return pdDocument;
}