Example usage for com.itextpdf.text Document addHeader

List of usage examples for com.itextpdf.text Document addHeader

Introduction

In this page you can find the example usage for com.itextpdf.text Document addHeader.

Prototype


public boolean addHeader(String name, String content) 

Source Link

Document

Adds a user defined header to the document.

Usage

From source file:Beans.ArchAssistantBean.java

public void GenerarReporteQAW(Proyecto pro) throws FileNotFoundException, DocumentException, IOException {

    Rationaleqaw ratq, ratq4;//from   w  w  w  .  j av a 2s  .c om
    String paso = pro.getProAvance();
    Paragraph parrafo;
    int anexo = 1;
    GuardarArchivo arch = new GuardarArchivo();
    List<File> archivos = null;
    FileOutputStream archivo = new FileOutputStream(System.getProperty("user.home") + File.separator
            + "Downloads" + File.separator + "InformeQAW" + pro.getProNombre() + ".pdf");
    String razonamiento;
    Document documento = new Document();
    PdfWriter.getInstance(documento, archivo);
    List<Atributocalidad> listaAtributos = ListarAtr();
    List<Atributocalidad> atrEscogidos;

    documento.open();
    documento.addHeader("ArchAssistant", "ArchAssistant");
    //documento.setMargins(2, 2, 4, 4);
    parrafo = new Paragraph("INFORME QAW ", chapterFont);
    parrafo.setAlignment(1);
    documento.add(parrafo);
    parrafo = new Paragraph("Proyecto " + pro.getProNombre(), chapterFont);
    parrafo.setAlignment(1);
    documento.add(parrafo);
    parrafo = new Paragraph("ArchAssistant\n\n", blueFontArchAssistant);
    parrafo.setAlignment(1);
    documento.add(parrafo);
    documento.add(new Paragraph("\n\n" + pro.getProDescripcion(), paragraphFont));
    parrafo = new Paragraph("Autor: " + pro.getTblUsuarioidUsuario().getUsuNombre(), blueFont);
    parrafo.setAlignment(2);
    documento.add(parrafo);
    for (int i = 1; i <= 8; i++) {
        ratq = obtenerRationaleQAW(pro.getProID(), "qaw" + String.valueOf(i));
        ratq4 = obtenerRationaleQAW(pro.getProID(), "qaw4");

        documento.add(new Paragraph("QAW paso " + i + "\n", categoryFont));
        if (ratq != null) {
            archivos = arch.listarArchivos(ratq.getRatQawArchivo());
            razonamiento = ratq.getRatQawDescripcion();
            if (razonamiento != null) {
                if (ratq.getRatQawPaso().equals("qaw4")) {
                    ratq4 = ratq;
                    atrEscogidos = ObtenerAtributosEscogidos(ratq);
                    documento.add(new Paragraph("Atributos de Calidad:\n", subcategoryFont));
                    for (Atributocalidad atr : listaAtributos) {
                        for (Atributocalidad atrEsc : atrEscogidos) {
                            if (atr.getAcID() == atrEsc.getAcID()) {
                                documento.add(new Paragraph(atr.getAcNombre(), blueFont));
                            }
                        }
                    }
                    int indiceAtribs = 0;
                    if (razonamiento != null || razonamiento != "") {
                        indiceAtribs = razonamiento.indexOf("~|~|") + 4;
                    }
                    documento.add(new Paragraph("Justificacin de las decisiones", smallBold));
                    documento.add(new Paragraph(razonamiento.substring(indiceAtribs) + "\n", paragraphFont));
                } else {
                    if (ratq.getRatQawPaso().equals("qaw5")) {
                        documento.add(new Paragraph("Escenarios generados en la lluvia de ideas:\n",
                                subcategoryFont));
                        atrEscogidos = ObtenerAtributosEscogidos(ratq4);
                        for (Atributocalidad atr : atrEscogidos) {
                            documento.add(new Paragraph("\n" + atr.getAcNombre() + "\n\n", smallBold));
                            PdfPTable tabla = new PdfPTable(4);

                            tabla.addCell("Nombre");
                            tabla.addCell("Estimulo");
                            tabla.addCell("Ambiente");
                            tabla.addCell("Respuesta");

                            List<Escenario> listaEsc = ListEscenarios(pro);

                            for (Escenario esce : listaEsc) {
                                if (esce.getTblAtributoCalidadacID().getAcID() == atr.getAcID()) {
                                    tabla.addCell(esce.getEscNombre());
                                    tabla.addCell(esce.getEscEstimulo());
                                    tabla.addCell(esce.getEscAmbiente());
                                    tabla.addCell(esce.getEscRespuesta());
                                }
                            }
                            documento.add(tabla);
                        }
                    }
                    if (ratq.getRatQawPaso().equals("qaw6")) {
                        documento.add(new Paragraph("Escenarios consolodados:\n", subcategoryFont));
                        atrEscogidos = ObtenerAtributosEscogidos(ratq4);
                        for (Atributocalidad atr : atrEscogidos) {
                            documento.add(new Paragraph("\n" + atr.getAcNombre() + "\n\n", smallBold));
                            PdfPTable tabla = new PdfPTable(4);
                            tabla.addCell("Nombre");
                            tabla.addCell("Estimulo");
                            tabla.addCell("Ambiente");
                            tabla.addCell("Respuesta");

                            List<Escenario> listaEsc = ListEscenarios(pro);

                            for (Escenario esce : listaEsc) {
                                if (esce.getTblAtributoCalidadacID().getAcID() == atr.getAcID()) {
                                    tabla.addCell(esce.getEscNombre());
                                    tabla.addCell(esce.getEscEstimulo());
                                    tabla.addCell(esce.getEscAmbiente());
                                    tabla.addCell(esce.getEscRespuesta());
                                }
                            }
                            documento.add(tabla);
                        }
                    }
                    if (ratq.getRatQawPaso().equals("qaw7")) {
                        documento.add(new Paragraph("Escenarios priorizados:\n\n", subcategoryFont));

                        PdfPTable tabla = new PdfPTable(6);
                        tabla.addCell("Nombre");
                        tabla.addCell("Estimulo");
                        tabla.addCell("Ambiente");
                        tabla.addCell("Respuesta");
                        tabla.addCell("Atributo");
                        tabla.addCell("Voto");

                        List<Escenario> listaEsc = ListEscenarios(pro);

                        Collections.sort(listaEsc, new Comparator() {
                            @Override
                            public int compare(Object o1, Object o2) {
                                Escenario esc1, esc2;
                                esc1 = (Escenario) o1;
                                esc2 = (Escenario) o2;
                                return new Integer(esc1.getEscPrioridad())
                                        .compareTo(new Integer(esc2.getEscPrioridad()));

                            }
                        });

                        for (Escenario esce : listaEsc) {
                            tabla.addCell(esce.getEscNombre());
                            tabla.addCell(esce.getEscEstimulo());
                            tabla.addCell(esce.getEscAmbiente());
                            tabla.addCell(esce.getEscRespuesta());
                            tabla.addCell(esce.getTblAtributoCalidadacID().getAcNombre());
                            tabla.addCell(String.valueOf(esce.getEscPrioridad()));

                        }
                        documento.add(tabla);
                    }
                    if (ratq.getRatQawPaso().equals("qaw8")) {
                        documento.add(new Paragraph("Escenarios Refinados:\n\n", subcategoryFont));

                        PdfPTable tabla = new PdfPTable(9);
                        tabla.addCell("Nombre");
                        tabla.addCell("Estimulo");
                        tabla.addCell("Fuente");
                        tabla.addCell("Ambiente");
                        tabla.addCell("Artefacto");
                        tabla.addCell("Respuesta");
                        tabla.addCell("Medida");
                        tabla.addCell("Atributo");
                        tabla.addCell("Prioridad");

                        List<Escenario> listaEsc = ListEscenarios(pro);

                        Collections.sort(listaEsc, new Comparator() {
                            @Override
                            public int compare(Object o1, Object o2) {
                                Escenario esc1, esc2;
                                esc1 = (Escenario) o1;
                                esc2 = (Escenario) o2;
                                return new Integer(esc1.getEscPrioridad())
                                        .compareTo(new Integer(esc2.getEscPrioridad()));

                            }
                        });

                        for (Escenario esce : listaEsc) {
                            tabla.addCell(esce.getEscNombre());
                            tabla.addCell(esce.getEscEstimulo());
                            tabla.addCell(esce.getEscFuente());
                            tabla.addCell(esce.getEscAmbiente());
                            tabla.addCell(esce.getEscArtefacto());
                            tabla.addCell(esce.getEscRespuesta());
                            tabla.addCell(esce.getEscMedidaRespuesta());
                            tabla.addCell(esce.getTblAtributoCalidadacID().getAcNombre());
                            tabla.addCell(String.valueOf(esce.getEscPrioridad()));

                        }
                        documento.add(tabla);
                    }
                    documento.add(new Paragraph("Justificacin de las decisiones", smallBold));
                    documento.add(new Paragraph(razonamiento + "\n", paragraphFont));
                }
            }
            if (archivos != null) {
                documento.add(new Paragraph("Archivos anexos:\n", smallBold));
                for (File archi : archivos) {
                    documento.add(new Paragraph("Anexo" + anexo + ": " + archi.getName(), blueFont));
                    anexo++;
                }
            }
        } else {
            documento.add(new Paragraph("No se registr informacin para este paso\n\n", paragraphFont));
        }
    }
    documento.close();
    archivo.close();

}

From source file:com.automaster.autoview.server.servlet.PdfServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*  w  w w .j  a  v  a2 s .c  o m*/
        this.dataAtual = new Date(System.currentTimeMillis());
        this.cnpjUn = null;

        String tempoDecorrido = " 0";
        int codVeiculo = Integer.parseInt(request.getParameter("cod"));
        String placa = request.getParameter("placa");
        Timestamp dataInicio = new Timestamp(Long.parseLong(request.getParameter("dataInicio")));
        Timestamp dataFim = new Timestamp(Long.parseLong(request.getParameter("dataFim")));

        TimeZone timeZonePadrao = TimeZone.getTimeZone(ZoneId.of("-3"));
        //System.out.println("Time zone : " + timeZonePadrao);

        ZzzPosPlacaVeiculoDAO zzzPosPlacaVeiculoDAO = new ZzzPosPlacaVeiculoDAO();
        VeiculoDAO veiculoDAO = new VeiculoDAO();
        TreeMap<String, String> veiculo = veiculoDAO.buscarVeiculoPorCodigo(codVeiculo);
        placa = veiculo.get("placa");
        //System.out.println("PLACA: "+veiculo.get("placa"));
        ArrayList<TreeMap<String, String>> posicoes = zzzPosPlacaVeiculoDAO
                .buscarPosicoesPorIntervaloData(placa, dataInicio, dataFim);
        int codCliente = Integer.parseInt(veiculo.get("clienteCodCliente"));
        //System.out.println("COD CLIENTE: "+codCliente);
        ClienteDAO clienteDAO = null;
        clienteDAO = new ClienteDAO();
        TreeMap<String, String> infoClienteUnidade = clienteDAO.buscarPorCodClienteSimplificado(codCliente);
        // Get the text that will be added to the PDF
        // step 1
        Document document = new Document();
        document.addHeader("Adriano", "AutoMaster");
        document.addCreator("Adriano Vale");
        document.addAuthor("Adriano Vale");
        document.addCreationDate();
        document.setPageSize(PageSize.A4.rotate());
        // step 2
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        TableHeader event = new TableHeader();
        writer.setPageEvent(event);
        // step 3
        document.open();
        // step 4
        //getServletContext().getRealPath("/")
        String url = getServletContext().getRealPath("/");
        //"D:\\Users\\Adriano\\Documents\\NetBeansProjects\\JRGWT\\web\\imagens\\logo.jpg"
        Image logo = Image.getInstance(url + "/imagens/logo.jpg");
        logo.setAlignment(Element.ALIGN_CENTER);

        Paragraph titulo = new Paragraph("Relatrio de Posies",
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 20, Font.BOLD));
        titulo.setAlignment(Element.ALIGN_CENTER);

        Paragraph tituloPlaca = new Paragraph("Veculo: " + placa,
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 16, Font.BOLD));
        tituloPlaca.setAlignment(Element.ALIGN_CENTER);

        SimpleDateFormat dataFormatadaCabecalho = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        dataFormatadaCabecalho.setTimeZone(timeZonePadrao);

        Date dataHoraInicio0 = new Date(Long.parseLong(request.getParameter("dataInicio")));
        Date dataHoraFim0 = new Date(Long.parseLong(request.getParameter("dataFim")));
        Paragraph periodo = new Paragraph(
                "Perodo: De: " + dataFormatadaCabecalho.format(dataHoraInicio0) + " at: "
                        + dataFormatadaCabecalho.format(dataHoraFim0),
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 16, Font.BOLD));
        periodo.setSpacingAfter(10.0f);
        periodo.setAlignment(Element.ALIGN_CENTER);
        //PdfPTable tabela = new PdfPTable(new float[]{0.11f, 0.095f, 0.06f, 0.065f, 0.085f, 0.06f, 0.04f, 0.065f, 0.055f, 0.06f, 0.24f, 0.065f});
        PdfPTable tabela = new PdfPTable(new float[] { 0.07f, 0.045f, 0.045f, 0.27f });
        tabela.setWidthPercentage(98.0f);
        tabela.setHorizontalAlignment(Element.ALIGN_CENTER);
        PdfPCell tituloData = new PdfPCell(Phrase.getInstance("Data e Hora"));
        tituloData.setHorizontalAlignment(Element.ALIGN_CENTER);
        tabela.addCell(tituloData);
        //tabela.addCell("Data e hora");
        PdfPCell tituloVel = new PdfPCell(Phrase.getInstance("Velocidade"));
        tituloVel.setHorizontalAlignment(Element.ALIGN_CENTER);
        tabela.addCell(tituloVel);
        PdfPCell tituloIgn = new PdfPCell(Phrase.getInstance("Ignio"));
        tituloIgn.setHorizontalAlignment(Element.ALIGN_CENTER);
        tabela.addCell(tituloIgn);
        //tabela.addCell("Latitude");
        //tabela.addCell("Longitude");
        //tabela.addCell("Satlite");
        //tabela.addCell("GPS");
        //tabela.addCell("Entrada");
        //tabela.addCell("Sada");
        //tabela.addCell("Evento");
        PdfPCell tituloEnd = new PdfPCell(Phrase.getInstance("Endereo"));
        tituloEnd.setHorizontalAlignment(Element.ALIGN_CENTER);
        tabela.addCell(tituloEnd);
        //tabela.addCell("Direo");
        double latAnt = 0;
        double lonAnt = 0;
        double latAtual = 0;
        double lonAtual = 0;
        double distanciaTotal = 0;
        double distancia = 0;
        event.setHeader("AutoMaster");

        for (int i = 0; i < posicoes.size(); i++) {
            //for (int col = 0; col < posicoes.get(i).size(); col++) {
            if (i == 0) {
                distancia = 0;
                //System.out.println("linha 00 - PDF");
            } else {
                //System.out.println("linha 01 - PDF");
                latAnt = Double.parseDouble(posicoes.get(i - 1).get("lat"));
                lonAnt = Double.parseDouble(posicoes.get(i - 1).get("lon"));
                latAtual = Double.parseDouble(posicoes.get(i).get("lat"));
                lonAtual = Double.parseDouble(posicoes.get(i).get("lon"));
                //System.out.println("linha 02 - PDF");
                if (latAnt == latAtual && lonAnt == lonAtual) {
                    distancia = 0;
                } else {
                    distancia = caculaDistanciaEntreDoisPontos(latAnt, lonAnt, latAtual, lonAtual);
                    //System.out.println("linha 03 - PDF");
                }

            }
            distanciaTotal = distanciaTotal + distancia;
            //System.out.println("linha 04 - PDF");
            //TimeZone.setDefault(timeZoneMundial);
            Date dataHora0 = new Date(Long.parseLong(posicoes.get(i).get("dataHora")));
            //System.out.println("dataHora0 : "+dataHora0.toString());
            //TimeZone.setDefault(timeZoneCliente);
            //Date dataHora = new Date(dataHora0.getTime());
            SimpleDateFormat dataFormatada = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            dataFormatada.setTimeZone(timeZonePadrao);
            //System.out.println("dataFormatada : "+dataFormatada);
            PdfPCell celData = new PdfPCell(Phrase.getInstance(dataFormatada.format(dataHora0)));
            celData.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabela.addCell(celData);
            //tabela.addCell(dataFormatada);
            PdfPCell celVel = new PdfPCell(Phrase.getInstance(posicoes.get(i).get("vel")));
            celVel.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabela.addCell(celVel);
            PdfPCell celIgn = new PdfPCell(Phrase
                    .getInstance(posicoes.get(i).get("ign").equalsIgnoreCase("True") ? "Ligada" : "Desligada"));
            celIgn.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabela.addCell(celIgn);
            //tabela.addCell(posicoes.get(i).get("lat"));
            //tabela.addCell(posicoes.get(i).get("lon"));
            //tabela.addCell(posicoes.get(i).get("sat"));
            //tabela.addCell(posicoes.get(i).get("gps"));
            //tabela.addCell(posicoes.get(i).get("entrada"));
            //tabela.addCell(posicoes.get(i).get("saida"));
            //tabela.addCell(posicoes.get(i).get("evento"));
            PdfPCell celEnd = new PdfPCell(
                    Phrase.getInstance(posicoes.get(i).get("endereco") == null ? "Sem endereo"
                            : posicoes.get(i).get("endereco")));
            celEnd.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabela.addCell(celEnd);
            //tabela.addCell(posicoes.get(i).get("direcao"));
            //}
        }
        //System.out.println("linha 05 - PDF");
        tempoDecorrido = calculaDatas(Long.parseLong(posicoes.get(0).get("dataHora")),
                Long.parseLong(posicoes.get(posicoes.size() - 1).get("dataHora")));
        //System.out.println("linha 06 - PDF");
        int index = 0;
        String kms = "0";
        String m = "";
        double metros = 0;
        //System.out.println("linha 07 - PDF");
        if (distanciaTotal > 0) {
            //System.out.println("linha 08 - PDF");
            BigDecimal decimalFormatado = new BigDecimal(distanciaTotal).setScale(2, RoundingMode.HALF_EVEN);
            //System.out.println("linha 09 - PDF");
            index = String.valueOf(decimalFormatado).indexOf(".");
            kms = String.valueOf(decimalFormatado).substring(0, index);
            m = "0" + (String.valueOf(decimalFormatado).substring(index));
            metros = Double.parseDouble(m) * 1000;
            //System.out.println("linha 10 - PDF");
        }
        /*document.add(new Paragraph(String.format(
         "You have submitted the following text using the %s method:",
         request.getMethod())));
         document.add(new Paragraph(text));*/
        //System.out.println("linha 11 - PDF");
        Paragraph kilometragem = new Paragraph(
                "Percorridos: " + kms + " KM e " + String.valueOf(metros) + " metros. Tempo: " + tempoDecorrido,
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 16, Font.BOLD));
        //System.out.println("linha 12 - PDF");
        periodo.setSpacingAfter(10.0f);
        periodo.setAlignment(Element.ALIGN_CENTER);
        // step 5
        document.add(logo);
        document.add(titulo);
        document.add(tituloPlaca);
        document.add(periodo);
        document.add(tabela);
        document.add(kilometragem);
        String dia = new SimpleDateFormat("dd").format(dataAtual);
        String ano = new SimpleDateFormat("yyyy").format(dataAtual);
        int mes = dataAtual.getMonth();
        String mesEscrito = null;
        switch (mes) {
        case 0:
            mesEscrito = "janeiro";
            break;
        case 1:
            mesEscrito = "fevereiro";
            break;
        case 2:
            mesEscrito = "maro";
            break;
        case 3:
            mesEscrito = "abril";
            break;
        case 4:
            mesEscrito = "maio";
            break;
        case 5:
            mesEscrito = "junho";
            break;
        case 6:
            mesEscrito = "julho";
            break;
        case 7:
            mesEscrito = "agosto";
            break;
        case 8:
            mesEscrito = "setembro";
            break;
        case 9:
            mesEscrito = "outubro";
            break;
        case 10:
            mesEscrito = "novembro";
            break;
        case 11:
            mesEscrito = "dezembro";
            break;
        }
        String textRodape = infoClienteUnidade.get("cidadeUnidade") + " , "
                + infoClienteUnidade.get("estadoUnidade") + "    " + dia + "  de  " + mesEscrito + "  de  "
                + ano + ".";
        Paragraph localData = new Paragraph(textRodape,
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 12, Font.PLAIN));
        localData.setAlignment(Element.ALIGN_RIGHT);
        localData.setSpacingBefore(30.0f);
        localData.setSpacingAfter(10.0f);
        document.add(localData);
        Image assinatura = Image.getInstance(url + "/imagens/assinatura.png");
        assinatura.setAlignment(Element.ALIGN_CENTER);
        assinatura.scaleAbsolute(185, 91);
        document.add(assinatura);
        Paragraph infoEmpresa1 = new Paragraph("AUTO MASTER LTDA",
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 12, Font.BOLD));
        infoEmpresa1.setAlignment(Element.ALIGN_CENTER);
        infoEmpresa1.setSpacingAfter(1f);
        document.add(infoEmpresa1);
        Paragraph infoEmpresa2 = new Paragraph("___________________________",
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 12, Font.BOLD));
        infoEmpresa2.setAlignment(Element.ALIGN_CENTER);
        document.add(infoEmpresa2);
        String cnpjEmpresa = formataCNPJ(infoClienteUnidade.get("cnpjUnidade"));
        Paragraph infoEmpresa3 = new Paragraph(cnpjEmpresa,
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 12, Font.BOLD));
        infoEmpresa3.setAlignment(Element.ALIGN_CENTER);
        document.add(infoEmpresa3);
        document.close();
        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=Historico-" + placa + ".pdf");
        // the contentlength
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
        os.close();
    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }
    //        response.setContentType("text/html;charset=UTF-8");
    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet PdfServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet PdfServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:com.automated_attendence.servlets.PublishAttendance.java

public void createPdf(String filename, int loop, String course, String dept, String year_id, String semester_id,
        int totalClass) throws DocumentException, IOException {
    // step 1/*from  ww w. j a  v  a  2 s  . co  m*/
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4
    //document.add(new Paragraph("Hello World!"));
    // step 5
    document.addHeader("name", "yeamin");
    document.addTitle("Attendence");
    document.add(new Paragraph(String.format(
            "              ResultSheet of Course id %s,Department %s,Year ID  %s,Semester ID %s :", course,
            dept, year_id, semester_id)));
    document.add(new Paragraph(
            String.format("\n                                                                Total Class : %d ",
                    totalClass)));
    document.add(new Paragraph("      "));
    PdfPTable table = new PdfPTable(2);
    PdfPCell c1;

    c1 = new PdfPCell(new Phrase("Reg no"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Attendence"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    table.setHeaderRows(1);
    for (int i = 1; i <= loop; ++i) {
        //table.addCell(i+"");
        //table.addCell(i*i+"");
        table.addCell(student_reg_arrary[i]);
        // System.err.println(student_reg_arrary[i]);
        table.addCell(student_present_day[i]);
        // System.err.println(student_present_day[i]);

    }
    //document.addAuthor("me");
    document.add(table);
    document.close();
}

From source file:com.github.ossdevs.jhocr.converter.HocrToPdf.java

License:Open Source License

/**
 * This is the old <code>convert()</code> method, almost untouched.<br>
 * This method will be used if {@link #pdfFormat} is not set.
 *
 * @return true if the conversion was successful.
 */// w w w.  ja  v a2s. co m
private boolean convertSimple() {
    boolean result = false;

    Document document = new Document();

    try {
        PdfWriter writer = PdfWriter.getInstance(document, getOutputStream());

        document.open();
        document.addHeader(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE);
        document.setMargins(0, 0, 0, 0);

        /**
         * TODO add documentation
         */
        for (HocrDocumentItem item : getItems()) {

            HocrParser parser = new HocrParser(item.getHocrInputStream());

            HocrDocument hocrDocument = parser.parse();

            /**
             * TODO add documentation
             * TODO add multipage image support
             */
            if (hocrDocument.getPages().size() > 1) {
                throw new UnsupportedOperationException(
                        "Multipage tif are not yet implemented, please report: http://code.google.com/p/jhocr/issues/list");
            }

            /**
             * TODO add documentation
             */
            for (HocrPage hocrPage : hocrDocument.getPages()) {
                HocrPageProcessor pageProcessor = new HocrPageProcessor(hocrPage, item.getImageInputStream(),
                        isUseImageDpi());

                if (pageProcessor.isInitialized()) {
                    pageProcessor.process(document, writer);
                }
            }
        }

        if (!outlines.isEmpty()) {
            writer.setOutlines(outlines);
        }

        /**
         * Closing the document body stream.
         */
        document.close();
        getOutputStream().close();
        result = true;

    } catch (UnsupportedOperationException e) {
        document.close();
        logger.error("This operation is not yet implemented.", e);
        result = false;
    } catch (DocumentException e) {
        document.close();
        logger.error("exception while genrating the PDF.", e);
        result = false;
    } catch (IOException e) {
        document.close();
        logger.error("FileSystem I/O Exception, please check the log and file system persmissions.", e);
        result = false;
    }

    return result;
}

From source file:com.github.ossdevs.jhocr.converter.HocrToPdf.java

License:Open Source License

/**
 * @param pdfXConformance determines into which format the PDF-X will be converted.
 * @return true if the conversion was successful.
 *//*w ww .  j  a  v a2  s .  co m*/
private boolean convertToPDFX(int pdfXConformance) {
    boolean result = false;
    Document document = new Document();

    try {
        PdfWriter writer = PdfWriter.getInstance(document, getOutputStream());
        writer.setPDFXConformance(pdfXConformance);

        document.open();
        document.addHeader(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE);
        document.setMargins(0, 0, 0, 0);

        /**
         * TODO add documentation
         */
        for (HocrDocumentItem item : getItems()) {

            HocrParser parser = new HocrParser(item.getHocrInputStream());

            HocrDocument hocrDocument = parser.parse();

            /**
             * TODO add documentation
             * TODO add multipage image support
             */
            if (hocrDocument.getPages().size() > 1) {
                throw new UnsupportedOperationException(
                        "Multipage tif are not yet implemented, please report: http://code.google.com/p/jhocr/issues/list");
            }

            /**
             * TODO add documentation
             */
            for (HocrPage hocrPage : hocrDocument.getPages()) {
                HocrPageProcessor pageProcessor = new HocrPageProcessor(hocrPage, item.getImageInputStream(),
                        isUseImageDpi());

                if (pageProcessor.isInitialized()) {
                    pageProcessor.process(document, writer);
                }
            }
        }

        if (!outlines.isEmpty()) {
            writer.setOutlines(outlines);
        }

        /**
         * Closing the document body stream.
         */
        document.close();
        getOutputStream().close();
        result = true;

    } catch (UnsupportedOperationException e) {
        document.close();
        logger.error("This operation is not yet implemented.", e);
        result = false;
    } catch (DocumentException e) {
        document.close();
        logger.error("exception while genrating the PDF.", e);
        result = false;
    } catch (IOException e) {
        document.close();
        logger.error("FileSystem I/O Exception, please check the log and file system persmissions.", e);
        result = false;
    }

    return result;

}

From source file:com.github.ossdevs.jhocr.converter.HocrToPdf.java

License:Open Source License

/**
 * @param pdfConformanceLevel determines into which format the PDF-A&/B will be converted.
 * @return true if the conversion was successful.
 *//*ww w .  j  a  va 2 s  .  com*/
private boolean convertToPDFA(PdfAConformanceLevel pdfConformanceLevel) {
    boolean result = false;
    Document document = new Document();

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    if (classLoader == null) {
        classLoader = Class.class.getClassLoader();
    }

    try {
        PdfAWriter writer = PdfAWriter.getInstance(document, getOutputStream(), pdfConformanceLevel);
        writer.createXmpMetadata();

        document.open();
        document.addHeader(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE);
        document.setMargins(0, 0, 0, 0);

        /**
         * TODO add documentation
         */
        for (HocrDocumentItem item : getItems()) {

            HocrParser parser = new HocrParser(item.getHocrInputStream());

            HocrDocument hocrDocument = parser.parse();

            /**
             * TODO add documentation
             * TODO add multipage image support
             */
            if (hocrDocument.getPages().size() > 1) {
                throw new UnsupportedOperationException(
                        "Multipage tif are not yet implemented, please report: http://code.google.com/p/jhocr/issues/list");
            }

            /**
             * TODO add documentation
             */
            for (HocrPage hocrPage : hocrDocument.getPages()) {
                HocrPageProcessor pageProcessor = new HocrPageProcessor(hocrPage, item.getImageInputStream(),
                        isUseImageDpi());

                if (pageProcessor.isInitialized()) {
                    pageProcessor.process(document, writer);
                }
            }
        }

        if (!outlines.isEmpty()) {
            writer.setOutlines(outlines);
        }

        InputStream is = this.getClass().getResourceAsStream("/sRGB.profile");

        ICC_Profile icc = ICC_Profile.getInstance(is);
        writer.setOutputIntents(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE, "http://www.color.org",
                "sRGB IEC61966-2.1", icc);

        /**
         * Closing the document body stream.
         */
        document.close();
        getOutputStream().close();
        result = true;

    } catch (UnsupportedOperationException e) {
        document.close();
        logger.error("This operation is not yet implemented.", e);
        result = false;
    } catch (DocumentException e) {
        document.close();
        logger.error("exception while genrating the PDF.", e);
        result = false;
    } catch (IOException e) {
        document.close();
        logger.error("FileSystem I/O Exception, please check the log and file system persmissions.", e);
        result = false;
    }

    return result;

}

From source file:com.havoc.hotel.util.BookingPdf.java

public static String generateBookingPDF(Booking booking)
        throws DocumentException, FileNotFoundException, IOException {
    Document document = new Document(PageSize.A4);
    String bookingname = booking.getFirstName() + " " + booking.getLastName();
    document.addHeader("HOTEL HAVOC", "Hotel havoc Booking confirmation");
    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(FILE + "Booking" + "" + booking.getCustomer().getFirstName() + ".pdf "));
    writer.setViewerPreferences(PdfWriter.PageModeUseOC);
    writer.setPdfVersion(PdfWriter.VERSION_1_7);
    document.open();/*ww w.j ava2 s . com*/
    String html = htmlTemplate(booking);

    List unorderedList = new List(List.UNORDERED);

    unorderedList.add(new ListItem("Name       :" + booking.getFirstName() + " " + booking.getLastName()));
    //        unorderedList.add(new ListItem("Room Price :" + booking.getRoom().getRoomPrice()));
    unorderedList.add(new ListItem("Total Price :" + booking.getTotalPrice()));
    unorderedList.add(new ListItem("check in   :" + booking.getCheckinDate()));
    unorderedList.add(new ListItem("Total Nights:" + booking.getTotalNights()));
    unorderedList.add(new ListItem("check out  :" + booking.getCheckoutDate()));
    unorderedList.add(new ListItem("Booked By  :" + booking.getCustomer().getUsername()));

    document.add(unorderedList);
    document.close();
    return bookingname;

}

From source file:com.unicauca.coordinacionpis.managedbean.RegistroFormatoAController.java

public void agregarMetadatos() {
    // create document and writer
    Document document = new Document(PageSize.A4);
    PdfWriter writer;//from w  w  w  . jav a  2  s .  c o m
    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\aguaabril2016.pdf"));
        // add meta-data to pdf
        document.addAuthor("Memorynotfound");
        document.addCreationDate();
        document.addCreator("Memorynotfound.com");
        document.addTitle("Add meta data to PDF");
        document.addSubject("how to add meta data to pdf using itext");
        document.addKeywords(metadatosAnteproyectos.getTitulo() + "," + metadatosAnteproyectos.getProfesor());
        document.addLanguage(Locale.ENGLISH.getLanguage());
        document.addHeader("type", "tutorial, example");

        // add xmp meta data
        writer.createXmpMetadata();

        document.open();
        document.add(new Paragraph("Add meta-data to PDF using iText"));
        document.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(RegistroOfertaAcademicaController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(RegistroOfertaAcademicaController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:es.jscan.Pantallas.PantallaPrincipal.java

License:Apache License

@Action
public Boolean guardarPdf() {
    if (contimagen < 1) {
        return false;
    }//from   w  w  w  .j  av  a 2  s  .c om

    final PantallaBarra pantbarra = new PantallaBarra(PantallaPrincipal.this, false);
    pantbarra.setTitle("Generando fichero de destino");
    pantbarra.botonParar.setVisible(false);
    errorpdf = false;

    new Thread() {
        @Override
        public void run() {
            Document pdfDocument = new Document();
            //                Document pdfDocument = new Document(PageSize.A4, 0, 0, 0, 0);
            Calendar cal = Calendar.getInstance();
            String anio = String.valueOf(cal.get(Calendar.YEAR));
            String mes = String.valueOf((cal.get(Calendar.MONTH) + 1)).length() == 1
                    ? "0" + String.valueOf((cal.get(Calendar.MONTH) + 1))
                    : String.valueOf((cal.get(Calendar.MONTH) + 1));
            String dia = String.valueOf(cal.get(Calendar.DAY_OF_MONTH)).length() == 1
                    ? "0" + String.valueOf(cal.get(Calendar.DAY_OF_MONTH))
                    : String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
            String hora = String.valueOf(cal.get(Calendar.HOUR_OF_DAY)).length() == 1
                    ? "0" + String.valueOf(cal.get(Calendar.HOUR_OF_DAY))
                    : String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
            String minuto = String.valueOf(cal.get(Calendar.MINUTE)).length() == 1
                    ? "0" + String.valueOf(cal.get(Calendar.MINUTE))
                    : String.valueOf(cal.get(Calendar.MINUTE));
            String segundo = String.valueOf(cal.get(Calendar.SECOND)).length() == 1
                    ? "0" + String.valueOf(cal.get(Calendar.SECOND))
                    : String.valueOf(cal.get(Calendar.SECOND));

            try {
                if (DEBUG) {
                    Utilidades.escribeLog("Generando PDFs -guardarPdf-");
                }
                if (contimagen < 2) {
                    pantbarra.barra.setMinimum(1);
                    pantbarra.barra.setMaximum(2);
                } else {
                    pantbarra.barra.setMinimum(1);
                    pantbarra.barra.setMaximum(rutaboton.length);
                }
                pantbarra.barra.setValue(1);
                pantbarra.setTitle(pantbarra.getTitle());
                pantbarra.validate();

                String nombrefichero = "Documentacion.pdf";
                String ruta = rutalote + separador + nombrefichero + ".pdf";

                if (!textoFichero.getText().isEmpty()) {
                    nombrefichero = textoFichero.getText() + ".pdf";
                }

                if (!textoDirectorio.getText().isEmpty()) {
                    ruta = textoDirectorio.getText();
                    ruta = ruta + separador + nombrefichero;
                }

                FileOutputStream ficheroPdf = new FileOutputStream(ruta);
                File filename = new File(rutaboton[0].toString());
                java.awt.image.BufferedImage imagen = javax.imageio.ImageIO.read(filename);
                com.itextpdf.text.Image imagenpdf = com.itextpdf.text.Image.getInstance(imagen, null);
                pdfDocument.setPageSize(new Rectangle(imagenpdf.getWidth(), imagenpdf.getHeight()));
                PdfWriter writer = PdfWriter.getInstance(pdfDocument, ficheroPdf);
                writer.open();
                pdfDocument.open();
                pdfDocument.addHeader("IP", lote.substring(16, 19) + "." + lote.substring(19, 22) + "."
                        + lote.substring(22, 25) + "." + lote.substring(25, 28));
                pdfDocument.addHeader("fechadigita",
                        lote.substring(6, 8) + "/" + lote.substring(4, 6) + "/" + lote.substring(0, 4) + " "
                                + lote.substring(9, 11) + ":" + lote.substring(11, 13) + ":"
                                + lote.substring(13, 15));
                pdfDocument.addHeader("fechacreacion",
                        dia + "/" + mes + "/" + anio + " " + hora + ":" + minuto + ":" + segundo);

                for (int i = 0; i < rutaboton.length; i++) {
                    filename = new File(rutaboton[i].toString());
                    imagen = javax.imageio.ImageIO.read(filename);
                    imagenpdf = com.itextpdf.text.Image.getInstance(imagen, null);
                    //                        imagenpdf.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
                    //                        imagenpdf.setAlignment(com.itextpdf.text.Image.ALIGN_JUSTIFIED_ALL);
                    //                        com.itextpdf.text.Image instance = com.itextpdf.text.Image.getInstance(imagenpdf);
                    //                        pdfDocument.setPageSize(new com.itextpdf.text.Rectangle(PageSize.A4.getWidth(), PageSize.A4.getHeight()));
                    pantbarra.barra.setValue(i);
                    pantbarra.setTitle(titulo + "     " + (i + 1) + " de " + rutaboton.length);
                    pdfDocument.setPageSize(new Rectangle(imagenpdf.getWidth(), imagenpdf.getHeight()));
                    //                        pdfDocument.add(instance);
                    pdfDocument.add(imagenpdf);
                    pdfDocument.newPage();
                    pantbarra.validate();
                }
                pdfDocument.close();
                writer.close();
            } catch (Exception e) {
                Utilidades.escribeLog("Error Generando PDFs -guardarPdf- " + e.getMessage());
                errorpdf = true;
            }
            pantbarra.dispose();
        }
    }.start();
    pantbarra.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
    pantbarra.setVisible(false);
    pantbarra.setVisible(true);
    return !errorpdf;
}

From source file:org.opentox.io.publishable.PDFObject.java

License:Open Source License

public void publish(YaqpIOStream stream) throws YaqpException {
    if (stream == null) {
        throw new NullPointerException("Cannot public pdf to a null output stream");
    }//www  .j av a  2 s. c om
    try {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, (OutputStream) stream.getStream());
        } catch (ClassCastException ex) {
            throw new ClassCastException("The stream you provided is not a valid output stream");
        }
        doc.open();
        doc.addAuthor(pdfAuthor);
        doc.addCreationDate();
        doc.addProducer();
        doc.addSubject(subject);
        doc.addCreator(pdfCreator);
        doc.addTitle(pdfTitle);
        doc.addKeywords(pdfKeywords);
        doc.addHeader("License", "GNU GPL v3");
        Image image = null;
        try {
            image = Image.getInstance(new URL(OpenToxLogoUrl));
        } catch (Exception ex) {// OpenTox Logo was not found on the web...
            try {// use the cached image instead
                YaqpLogger.LOG.log(new Trace(getClass(), "OpenTox Logo not found at " + OpenToxLogoUrl));
                image = Image.getInstance(alternativeLogoPath);
            } catch (Exception ex1) {// if no image at local folder
                YaqpLogger.LOG.log(new Debug(getClass(),
                        "OpenTox Logo not found at " + alternativeLogoPath + " :: " + ex1));
            }
        }
        if (image != null) {
            image.scalePercent(40);
            image.setAnnotation(new Annotation(0, 0, 0, 0, "http://opentox.org"));
            Chunk ck_ot = new Chunk(image, -5, -30);
            doc.add(ck_ot);
        }
        try {
            Image yaqp = Image.getInstance(yaqpLogo);
            yaqp.scalePercent(30);
            yaqp.setAnnotation(new Annotation(0, 0, 0, 0, "https://opentox.ntua.gr"));
            yaqp.setAlt("YAQP(R), yet another QSAR Project");
            Chunk ck_yaqp = new Chunk(yaqp, 15, -30);
            doc.add(ck_yaqp);
        } catch (Exception ex) {
            YaqpLogger.LOG
                    .log(new Warning(getClass(), "YAQP Logo not found at " + kinkyDesignLogo + " :: " + ex));
        }
        doc.add(new Paragraph("\n\n\n"));
        for (Element e : elements) {
            doc.add(e);
        }
        doc.close();
    } catch (DocumentException ex) {
        String message = "Error while generating PDF representation.";
        YaqpLogger.LOG.log(new Warning(getClass(), message));
        throw new YaqpException(XPDF18, message, ex);
    }

}