Example usage for com.lowagie.text Paragraph setAlignment

List of usage examples for com.lowagie.text Paragraph setAlignment

Introduction

In this page you can find the example usage for com.lowagie.text Paragraph setAlignment.

Prototype

public void setAlignment(String alignment) 

Source Link

Document

Sets the alignment of this paragraph.

Usage

From source file:Agenda.java

public void preparaPDF(Object document) throws IOException, BadElementException, DocumentException {
    //criando novo pdf
    Document pdf = (Document) document;

    //abrindo documento
    pdf.open();/*w w  w.  java 2 s  .co m*/

    //modificando caracteristicas do documento
    pdf.setPageSize(PageSize.A4);

    //        //VERSAO FUNCIONAL    
    //        //criando paragrafo no texto
    //            Paragraph p = new Paragraph("Relatrio Contatos",            
    //            //editando configuracoes de fontes do texto
    //            FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new Color(255,150,255)));
    //            
    //        //definindo alinhamento
    //            p.setAlignment(Element.ALIGN_CENTER);
    //        
    //        //adiciona as modificaes ao documento
    //            pdf.add(p);

    //VERSAO CORRETA
    Paragraph p = new Paragraph();
    p.setFont(FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new Color(255, 255, 0)));
    p.add(new Phrase("Relatrio Contatos"));
    p.setAlignment(Element.ALIGN_CENTER);
    pdf.add(p);
}

From source file:airportpainter.util.AirportPainter.java

License:Open Source License

private void createSheetsRunways(Airport airport, Document document) {
    notifyAction("createSheetsRunways");

    PdfPTable table = new PdfPTable(6);

    // titles// w ww.j  a v a 2s . com
    com.lowagie.text.Font fontTitle = new com.lowagie.text.Font(com.lowagie.text.Font.TIMES_ROMAN, 8,
            com.lowagie.text.Font.NORMAL);
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(borderWidth);
        cell.setBorderWidthBottom(borderWidthThin);
        cell.setBorderWidthRight(borderWidthThin);
        cell.setBorderWidthLeft(borderWidth);
        Paragraph p = new Paragraph("RWY N" + degrees, fontTitle);
        p.setLeading((p.leading() / 2) + 2);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        table.addCell(cell);
    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(borderWidth);
        cell.setBorderWidthBottom(borderWidthThin);
        cell.setBorderWidthRight(borderWidthThin);
        cell.setBorderWidthLeft(borderWidthThin);
        Paragraph p = new Paragraph("Dimension (ft) - Surface", fontTitle);
        p.setLeading((p.leading() / 2) + 2);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        table.addCell(cell);
    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(borderWidth);
        cell.setBorderWidthBottom(borderWidthThin);
        cell.setBorderWidthRight(borderWidthThin);
        cell.setBorderWidthLeft(borderWidthThin);
        Paragraph p = new Paragraph("TORA (ft)", fontTitle);
        p.setLeading((p.leading() / 2) + 2);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        table.addCell(cell);
    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(borderWidth);
        cell.setBorderWidthBottom(borderWidthThin);
        cell.setBorderWidthRight(borderWidthThin);
        cell.setBorderWidthLeft(borderWidthThin);
        Paragraph p = new Paragraph("LDA (ft)", fontTitle);
        p.setLeading((p.leading() / 2) + 2);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        table.addCell(cell);
    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(borderWidth);
        cell.setBorderWidthBottom(borderWidthThin);
        cell.setBorderWidthRight(borderWidthThin);
        cell.setBorderWidthLeft(borderWidthThin);
        Paragraph p = new Paragraph("Strength", fontTitle);
        p.setLeading((p.leading() / 2) + 2);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        table.addCell(cell);

    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidthTop(borderWidth);
        cell.setBorderWidthBottom(borderWidthThin);
        cell.setBorderWidthRight(borderWidth);
        cell.setBorderWidthLeft(borderWidthThin);
        Paragraph p = new Paragraph("Lights", fontTitle);
        p.setLeading((p.leading() / 2) + 2);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        table.addCell(cell);
    }

    // data
    com.lowagie.text.Font fontData = new com.lowagie.text.Font(com.lowagie.text.Font.TIMES_ROMAN, 10,
            com.lowagie.text.Font.NORMAL);
    int rc = 0;
    for (final Runway runway : airport.getRunways()) {
        {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidthLeft(borderWidth);
            if (rc < airport.getRunways().size() - 1) {
                // thin bottom if not last runway
                cell.setBorderWidthBottom(borderWidthThin);
            } else {
                cell.setBorderWidthBottom(borderWidth);
            }
            cell.setBorderWidthRight(borderWidthThin);
            Paragraph p = new Paragraph(runway.getNumber() + "\r\n" + runway.getOppositeNumber(), fontData);
            p.setLeading((p.leading() / 2) + 2);
            p.setAlignment(Element.ALIGN_CENTER);
            cell.addElement(p);
            table.addCell(cell);
        }
        {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidthLeft(borderWidthThin);
            if (rc < airport.getRunways().size() - 1) {
                // thin bottom if not last runway
                cell.setBorderWidthBottom(borderWidthThin);
            } else {
                cell.setBorderWidthBottom(borderWidth);
            }
            cell.setBorderWidthRight(borderWidthThin);
            String runwayLength = new Integer(runway.getLength()).toString() + " x "
                    + new Integer(runway.getWidth()).toString() + " " + runway.getSurfaceName();
            Paragraph p = new Paragraph(runwayLength, fontData);
            p.setLeading((p.leading() / 2) + 2);
            p.setAlignment(Element.ALIGN_CENTER);
            cell.addElement(p);
            table.addCell(cell);

        }
        {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidthLeft(borderWidthThin);
            if (rc < airport.getRunways().size() - 1) {
                // thin bottom if not last runway
                cell.setBorderWidthBottom(borderWidthThin);
            } else {
                cell.setBorderWidthBottom(borderWidth);
            }
            cell.setBorderWidthRight(borderWidthThin);
            Paragraph p = new Paragraph(runway.getLength() + "\r\n" + runway.getLength(), fontData);
            p.setLeading((p.leading() / 2) + 2);
            p.setAlignment(Element.ALIGN_CENTER);
            cell.addElement(p);
            table.addCell(cell);
        }
        {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidthLeft(borderWidthThin);
            if (rc < airport.getRunways().size() - 1) {
                // thin bottom if not last runway
                cell.setBorderWidthBottom(borderWidthThin);
            } else {
                cell.setBorderWidthBottom(borderWidth);
            }
            cell.setBorderWidthRight(borderWidthThin);
            Paragraph p = new Paragraph((runway.getLength() - runway.getDisplacement()) + "\r\n"
                    + (runway.getLength() - runway.getDisplacementOpposite()), fontData);
            p.setLeading((p.leading() / 2) + 2);
            p.setAlignment(Element.ALIGN_CENTER);
            cell.addElement(p);
            table.addCell(cell);
        }
        {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidthLeft(borderWidthThin);
            if (rc < airport.getRunways().size() - 1) {
                // thin bottom if not last runway
                cell.setBorderWidthBottom(borderWidthThin);
            } else {
                cell.setBorderWidthBottom(borderWidth);
            }
            cell.setBorderWidthRight(borderWidthThin);
            Paragraph p = new Paragraph("to do...", fontData);
            p.setLeading((p.leading() / 2) + 2);
            p.setAlignment(Element.ALIGN_CENTER);
            cell.addElement(p);
            table.addCell(cell);
        }
        {
            PdfPCell cell = new PdfPCell();
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setBorderWidthLeft(borderWidthThin);
            cell.setBorderWidthRight(borderWidth);
            if (rc < airport.getRunways().size() - 1) {
                // thin bottom if not last runway
                cell.setBorderWidthBottom(borderWidthThin);
            } else {
                cell.setBorderWidthBottom(borderWidth);
            }
            Paragraph p = new Paragraph();
            p.setLeading((p.leading() / 2) + 2);
            p.setAlignment(Element.ALIGN_CENTER);
            try {
                if (runway.hasALSF_I(true) || runway.hasALSF_I(false) || runway.hasALSF_II(true)
                        || runway.hasALSF_II(false) || runway.hasPapi(true) || runway.hasPapi(false)
                        || runway.hasSALSF(true) || runway.hasSALSF(false) || runway.hasSSLP(true)
                        || runway.hasSSLP(false) || runway.hasVasi(true) || runway.hasVasi(false)) {
                    p.add(new Chunk(Image.getInstance(getClass().getResource(Main.imgFolder + "light.png")), 0,
                            0));
                } else {
                    p.add(new Chunk("--", fontData));
                }
            } catch (BadElementException ex) {
                Logger.getLogger(AirportPainter.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(AirportPainter.class.getName()).log(Level.SEVERE, null, ex);
            }
            cell.addElement(p);
            table.addCell(cell);
        }

        rc++;

    }

    float[] widths2 = { 1f, 2f, 1f, 1f, 2f, 1f };
    try {
        table.setWidths(widths2);
    } catch (DocumentException ex) {
        Logger.getLogger(AirportPainter.class.getName()).log(Level.SEVERE, null, ex);
    }

    table.setWidthPercentage(100);
    try {
        document.add(table);
    } catch (DocumentException ex) {
        Logger.getLogger(AirportPainter.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:airportpainter.util.AirportPainter.java

License:Open Source License

private void createSheets2ILS(Airport airport, Document document) {
    // FREQs Nearest Navaid
    notifyAction("createSheets2ILS");
    PdfPTable table = new PdfPTable(2);
    {//from  ww w  .j a v a2 s.c  o  m
        PdfPCell cell = new PdfPCell();
        {
            Paragraph p = new Paragraph("(TWR)", new com.lowagie.text.Font(com.lowagie.text.Font.TIMES_ROMAN, 8,
                    com.lowagie.text.Font.NORMAL));
            p.setLeading((p.leading() / 2) + 2);
            cell.addElement(p);
        }

        List<ATCFreq> tempFreqsTwr = _airport.getATCFreqs("54");
        List<ATCFreq> tempFreqsGnd = _airport.getATCFreqs("53");
        if (tempFreqsTwr.size() > 0 || tempFreqsGnd.size() > 0) {

            if (tempFreqsTwr.size() > 0) {
                Paragraph p = new Paragraph();
                p.setLeading((p.leading() / 2) + 6);
                Chunk c = new Chunk(airport.getName().toUpperCase() + " APPROACH ", new com.lowagie.text.Font(
                        com.lowagie.text.Font.TIMES_ROMAN, 8, com.lowagie.text.Font.NORMAL));
                p.add(c);
                for (final ATCFreq tower : tempFreqsTwr) {
                    Chunk c2 = new Chunk((tower.getFreq() + "        ").substring(0, 9) + " ",
                            new com.lowagie.text.Font(com.lowagie.text.Font.TIMES_ROMAN, 8,
                                    com.lowagie.text.Font.BOLD));
                    p.add(c2);

                }
                cell.addElement(p);

            }

            if (tempFreqsGnd.size() > 0) {
                Paragraph p = new Paragraph();
                p.setLeading((p.leading() / 2) + 6);
                Chunk c = new Chunk("GROUND ", new com.lowagie.text.Font(com.lowagie.text.Font.TIMES_ROMAN, 8,
                        com.lowagie.text.Font.NORMAL));
                p.add(c);
                for (final ATCFreq tower : tempFreqsGnd) {
                    Chunk c2 = new Chunk((tower.getFreq() + "        ").substring(0, 9) + " ",
                            new com.lowagie.text.Font(com.lowagie.text.Font.TIMES_ROMAN, 8,
                                    com.lowagie.text.Font.BOLD));
                    p.add(c2);

                }
                cell.addElement(p);

            }

        }

        cell.setBorderWidth(borderWidth);
        cell.setBorderWidthTop(borderWidthThin);
        cell.setBorderWidthRight(borderWidthThin);

        //cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);
    }

    {
        com.lowagie.text.Font font = new com.lowagie.text.Font(com.lowagie.text.Font.TIMES_ROMAN,
                com.lowagie.text.Font.DEFAULTSIZE, com.lowagie.text.Font.NORMAL);
        PdfPCell cell = new PdfPCell();

        Paragraph p = new Paragraph();
        p.setLeading((p.leading()) + 6);
        Chunk c = new Chunk("ATIS ",
                new com.lowagie.text.Font(com.lowagie.text.Font.TIMES_ROMAN, 8, com.lowagie.text.Font.NORMAL));
        p.add(c);

        for (final Atis atis : _airport.getAtises()) {
            Chunk c2 = new Chunk((atis.getFreq() + "        ").substring(0, 9) + " ", new com.lowagie.text.Font(
                    com.lowagie.text.Font.TIMES_ROMAN, 8, com.lowagie.text.Font.BOLD));
            p.add(c2);
        }

        cell.addElement(p);

        /// ILS table
        {
            height1 = 0;
            PdfPTable tableILS = new PdfPTable(4);
            tableILS.setWidthPercentage(100);

            // titles
            com.lowagie.text.Font fontTitle = new com.lowagie.text.Font(com.lowagie.text.Font.TIMES_ROMAN, 8,
                    com.lowagie.text.Font.NORMAL);
            {
                PdfPCell cellTitle = new PdfPCell();
                cellTitle.setVerticalAlignment(Element.ALIGN_CENTER);
                cellTitle.setBorderWidth(borderWidthThin);
                Paragraph pt = new Paragraph("RWY", fontTitle);
                pt.setLeading((pt.leading() / 2) + 2);
                pt.setAlignment(Element.ALIGN_CENTER);
                cellTitle.addElement(pt);
                tableILS.addCell(cellTitle);
            }
            {
                PdfPCell cellTitle = new PdfPCell();
                cellTitle.setVerticalAlignment(Element.ALIGN_CENTER);
                cellTitle.setBorderWidth(borderWidthThin);
                Paragraph pt = new Paragraph("ILS", fontTitle);
                pt.setLeading((pt.leading() / 2) + 2);
                pt.setAlignment(Element.ALIGN_CENTER);
                cellTitle.addElement(pt);
                tableILS.addCell(cellTitle);
            }
            {
                PdfPCell cellTitle = new PdfPCell();
                cellTitle.setVerticalAlignment(Element.ALIGN_CENTER);
                cellTitle.setBorderWidth(borderWidthThin);
                Paragraph pt = new Paragraph("RWY", fontTitle);
                pt.setLeading((pt.leading() / 2) + 2);
                pt.setAlignment(Element.ALIGN_CENTER);
                cellTitle.addElement(pt);
                tableILS.addCell(cellTitle);
            }
            {
                PdfPCell cellTitle = new PdfPCell();
                cellTitle.setVerticalAlignment(Element.ALIGN_CENTER);
                cellTitle.setBorderWidth(borderWidthThin);
                Paragraph pt = new Paragraph("ILS", fontTitle);
                pt.setLeading((pt.leading() / 2) + 2);
                pt.setAlignment(Element.ALIGN_CENTER);
                cellTitle.addElement(pt);
                tableILS.addCell(cellTitle);
            }

            int pos = 0;
            int rs = airport.getRunways().size();
            for (final Runway runway : airport.getRunways()) {
                if (runway.getIlsFreq() != 0) {
                    height1 = height1 + 10;
                    {
                        PdfPCell cellFreq = new PdfPCell();
                        cellFreq.setVerticalAlignment(Element.ALIGN_CENTER);
                        cellFreq.setBorderWidth(borderWidthThin);
                        if (pos > 0) {
                            cellFreq.setBorderWidthTop(0);
                        }
                        if (pos < rs - 1) {
                            cellFreq.setBorderWidthBottom(0);
                        }

                        Paragraph pt = new Paragraph(runway.getNumber(), fontTitle);
                        pt.setLeading((pt.leading() / 2) + 2);
                        pt.setAlignment(Element.ALIGN_CENTER);
                        cellFreq.addElement(pt);
                        tableILS.addCell(cellFreq);
                    }
                    {
                        PdfPCell cellFreq = new PdfPCell();
                        cellFreq.setVerticalAlignment(Element.ALIGN_CENTER);
                        cellFreq.setBorderWidth(borderWidthThin);
                        if (pos > 0) {
                            cellFreq.setBorderWidthTop(0);
                        }
                        if (pos < rs - 1) {
                            cellFreq.setBorderWidthBottom(0);
                        }

                        Paragraph pt = new Paragraph(
                                runway.getIlsFreq() + " " + "... "
                                        + new Integer((int) runway.getHeading()).toString() + degrees,
                                fontTitle);
                        pt.setLeading((pt.leading() / 2) + 2);
                        pt.setAlignment(Element.ALIGN_CENTER);
                        cellFreq.addElement(pt);
                        tableILS.addCell(cellFreq);
                    }
                } /*else {
                  {
                      PdfPCell cellFreq = new PdfPCell();
                      cellFreq.setVerticalAlignment(Element.ALIGN_CENTER);
                      cellFreq.setBorderWidth(borderWidthThin);
                      if (pos>0) {
                          cellFreq.setBorderWidthTop(0);
                      }
                      if (pos<rs-1) {
                          cellFreq.setBorderWidthBottom(0);
                      }
                          
                      Paragraph pt=new Paragraph( "",fontTitle);
                      pt.setLeading((pt.leading()/2)+2);
                      pt.setAlignment(Element.ALIGN_CENTER);
                      cellFreq.addElement(pt);
                      tableILS.addCell(cellFreq);
                  }
                  {
                      PdfPCell cellFreq = new PdfPCell();
                      cellFreq.setVerticalAlignment(Element.ALIGN_CENTER);
                      cellFreq.setBorderWidth(borderWidthThin);
                      if (pos>0) {
                          cellFreq.setBorderWidthTop(0);
                      }
                      if (pos<rs-1) {
                          cellFreq.setBorderWidthBottom(0);
                      }
                          
                      Paragraph pt=new Paragraph( "",fontTitle);
                      pt.setLeading((pt.leading()/2)+2);
                      pt.setAlignment(Element.ALIGN_CENTER);
                      cellFreq.addElement(pt);
                      tableILS.addCell(cellFreq);
                  }
                          
                  }*/

                if (runway.getIlsOppositeFreq() != 0) {
                    {
                        PdfPCell cellFreq = new PdfPCell();
                        cellFreq.setVerticalAlignment(Element.ALIGN_CENTER);
                        cellFreq.setBorderWidth(borderWidthThin);
                        if (pos > 0) {
                            cellFreq.setBorderWidthTop(0);
                        }
                        if (pos < rs - 1) {
                            cellFreq.setBorderWidthBottom(0);
                        }

                        Paragraph pt = new Paragraph(runway.getOppositeNumber(), fontTitle);
                        pt.setLeading((pt.leading() / 2) + 2);
                        pt.setAlignment(Element.ALIGN_CENTER);
                        cellFreq.addElement(pt);
                        tableILS.addCell(cellFreq);
                    }
                    {
                        PdfPCell cellFreq = new PdfPCell();
                        cellFreq.setVerticalAlignment(Element.ALIGN_CENTER);
                        cellFreq.setBorderWidth(borderWidthThin);
                        if (pos > 0) {
                            cellFreq.setBorderWidthTop(0);
                        }
                        if (pos < rs - 1) {
                            cellFreq.setBorderWidthBottom(0);
                        }

                        Paragraph pt = new Paragraph(runway.getIlsOppositeFreq() + " " + "... "
                                + new Integer((int) (runway.getHeading() + 180) % 180).toString() + degrees,
                                fontTitle);
                        pt.setLeading((pt.leading() / 2) + 2);
                        pt.setAlignment(Element.ALIGN_CENTER);
                        cellFreq.addElement(pt);
                        tableILS.addCell(cellFreq);
                    }
                } else {
                    {
                        PdfPCell cellFreq = new PdfPCell();
                        cellFreq.setVerticalAlignment(Element.ALIGN_CENTER);
                        cellFreq.setBorderWidth(borderWidthThin);
                        if (pos > 0) {
                            cellFreq.setBorderWidthTop(0);
                        }
                        if (pos < rs - 1) {
                            cellFreq.setBorderWidthBottom(0);
                        }

                        Paragraph pt = new Paragraph("", fontTitle);
                        pt.setLeading((pt.leading() / 2) + 2);
                        pt.setAlignment(Element.ALIGN_CENTER);
                        cellFreq.addElement(pt);
                        tableILS.addCell(cellFreq);
                    }
                    {
                        PdfPCell cellFreq = new PdfPCell();
                        cellFreq.setVerticalAlignment(Element.ALIGN_CENTER);
                        cellFreq.setBorderWidth(borderWidthThin);
                        if (pos > 0) {
                            cellFreq.setBorderWidthTop(0);
                        }
                        if (pos < rs - 1) {
                            cellFreq.setBorderWidthBottom(0);
                        }

                        Paragraph pt = new Paragraph("", fontTitle);
                        pt.setLeading((pt.leading() / 2) + 2);
                        pt.setAlignment(Element.ALIGN_CENTER);
                        cellFreq.addElement(pt);
                        tableILS.addCell(cellFreq);
                    }

                }

                pos++;

            }

            float[] widths2 = { 1f, 3f, 1f, 3f };
            try {
                tableILS.setWidths(widths2);
            } catch (DocumentException ex) {
                Logger.getLogger(AirportPainter.class.getName()).log(Level.SEVERE, null, ex);
            }

            cell.addElement(tableILS);
        }

        cell.setBorderWidth(borderWidth);
        cell.setVerticalAlignment(Element.ALIGN_TOP);

        table.addCell(cell);
    }

    table.setWidthPercentage(100);
    try {
        document.add(table);
    } catch (DocumentException ex) {
        Logger.getLogger(AirportPainter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ambit.data.qmrf.Qmrf_Xml_Pdf.java

License:Open Source License

public void xml2pdf(InputSource xml, OutputStream pdf) {

    try {/*  w w  w.j a  va 2s  .  c  o  m*/
        Document document = new Document(PageSize.A4, 80, 50, 30, 65);

        PdfWriter writer = PdfWriter.getInstance(document, pdf);
        //writer.setViewerPreferences(PdfWriter.HideMenubar| PdfWriter.HideToolbar);
        writer.setViewerPreferences(PdfWriter.PageModeUseThumbs | PdfWriter.PageModeUseOutlines);
        //PdfOutline root = writer.getDirectContent().getRootOutline();
        //new PdfOutline(root, new PDFAction("http://nina.acad.bg/qmrf"), "a bookmark");

        //writer.addFileAttachment(arg0, arg1, arg2, arg3)

        if (docBuilder == null)
            docBuilder = docBuilderFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new SimpleErrorHandler(getClass().getName()));
        QMRFSchemaResolver resolver = new QMRFSchemaResolver("http://ambit.acad.bg/qmrf/qmrf.dtd", null);
        resolver.setIgnoreSystemID(true);
        docBuilder.setEntityResolver(resolver);

        org.w3c.dom.Document doc = null;
        try {
            doc = docBuilder.parse(xml);
        } catch (Exception x) {
            document.addCreationDate();
            document.addCreator(getClass().getName());
            document.open();
            document.add(new Paragraph(new Chunk(x.getMessage())));
            document.close();
            return;
        }

        document.addCreationDate();
        document.addCreator(getClass().getName());
        document.addKeywords(replaceTags(findNodeValue("keywords", doc)));
        document.addTitle(replaceTags(findNodeValue("QSAR_title", doc)));

        try {
            NodeList info = doc.getElementsByTagName("QMRF");
            for (int i = 0; i < info.getLength(); i++)
                document.addSubject(findAttributeValue("name", info.item(i)) + '.'
                        + findAttributeValue("version", info.item(i)));
        } catch (Exception x) {
            document.addSubject("QMRF");
        }
        try {
            document.addAuthor(listNodeAttributes(doc, "qmrf_authors", "author_ref", "author", att_author,
                    new Boolean(true)));
        } catch (Exception x) {
            document.addAuthor(getClass().getName());
        }

        document.open();
        PdfContentByte cb = writer.getDirectContent();

        try {
            headerTable(document, doc);
        } catch (Exception x) {
            document.add(new Paragraph(new Chunk(x.getMessage())));
            document.close();
            return;
        }

        PdfOutline root = writer.getDirectContent().getRootOutline();

        for (int i = 0; i < subchapters.length; i++)

            try {
                int align = Paragraph.ALIGN_LEFT;
                if (Mode.chapter == (Mode) subchapters[i][2]) {
                    document.add(new Paragraph(new Chunk('\n')));
                    PdfPTable table = new PdfPTable(1);

                    table.setWidthPercentage(100);

                    StringBuffer b = new StringBuffer();
                    b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter, doc));
                    b.append('.');
                    b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_name, doc));

                    String bookmark = b.toString();

                    Chunk title = new Chunk(bookmark);
                    title.setLocalDestination(bookmark);
                    title.setFont(bfont);

                    PdfDestination destination = new PdfDestination(PdfDestination.FITH);
                    PdfOutline outline = new PdfOutline(root, destination, bookmark);

                    Paragraph p = new Paragraph(title);

                    PdfPCell cell = new PdfPCell(p);
                    cell.setBackgroundColor(chapterColor);
                    table.addCell(cell);
                    document.add(table);
                    float pos = writer.getVerticalPosition(false);
                    if (pos < 90)
                        document.newPage();
                } else {
                    Phrase phrase = new Phrase();
                    switch ((Mode) subchapters[i][2]) {
                    case title: {
                        StringBuffer b = new StringBuffer();
                        String cn = findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter,
                                doc);
                        if (cn == null)
                            break;

                        b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter, doc));
                        b.append('.');
                        b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_name, doc));

                        String subchapterBookmark = b.toString();
                        b.append(':');

                        Chunk title = new Chunk(b.toString());
                        title.setLocalDestination(subchapterBookmark);
                        title.setFont(bfont);
                        phrase.add(title);

                        PdfDestination destination = new PdfDestination(PdfDestination.FITBH);
                        PdfOutline outline = new PdfOutline(root, destination, subchapterBookmark);

                        break;

                    }
                    case text: {
                        createNodePhrase(subchapters[i][0].toString(), doc, phrase, font);
                        align = Paragraph.ALIGN_JUSTIFIED;
                        break;
                    }
                    case answer: {
                        String a = findAnswer(subchapters[i][0].toString(), doc);
                        if (a != null) {
                            Chunk answer = new Chunk(a);
                            answer.setFont(font);
                            phrase.add(answer);
                        }
                        break;
                    }
                    case dataset: {
                        StringBuffer b = new StringBuffer();
                        b.append(findDataAvailable(subchapters[i][0].toString(), doc));
                        Chunk dataset = new Chunk(b.toString());
                        dataset.setFont(font);
                        phrase.add(dataset);
                        break;
                    }
                    case attachments: {
                        PdfPTable table = getAttachmentsAsTable(doc, "attachment_training_data");
                        if (table != null) {
                            phrase.add(new Paragraph("Training set(s)"));
                            phrase.add(table);
                        }
                        table = getAttachmentsAsTable(doc, "attachment_validation_data");
                        if (table != null) {
                            phrase.add(new Paragraph("Test set(s)"));
                            phrase.add(table);
                        }
                        table = getAttachmentsAsTable(doc, "attachment_documents");
                        if (table != null) {
                            phrase.add(new Paragraph("Supporting information"));
                            phrase.add(table);
                        }
                        break;
                        /*
                        StringBuffer b = new StringBuffer();
                        b.append("Training set(s)\n");
                         b.append(listAttachments(doc,"attachment_training_data"));
                         b.append("Test set(s)\n");
                         b.append(listAttachments(doc,"attachment_validation_data"));
                         b.append("Supporting information\n");
                         b.append(listAttachments(doc,"attachment_documents"));
                        Chunk attachments = new Chunk(b.toString());
                        attachments.setFont(font);
                        phrase.add(attachments);
                                
                        break;
                        */
                    }
                    case reference: {
                        try {
                            String value = listNodeAttributes(doc, subchapters[i][0].toString(),
                                    subchapters[i][3].toString(), subchapters[i][4].toString(),
                                    (String[]) subchapters[i][5], (Boolean) subchapters[i][6]);

                            Chunk reference = new Chunk(value);
                            reference.setFont(font);
                            align = Paragraph.ALIGN_JUSTIFIED;
                            phrase.add(reference);
                        } catch (Exception x) {

                        }
                        break;

                    }
                    }

                    Paragraph p = new Paragraph(phrase);
                    p.setAlignment(align);
                    document.add(p);
                    float pos = writer.getVerticalPosition(false);
                    /*
                    cb.moveTo(0, pos);
                    cb.lineTo(PageSize.A4.width(), pos);
                    cb.stroke();
                    */
                    if (pos < 90)
                        document.newPage();
                }
            } catch (Exception x) {
                x.printStackTrace();
            }

        document.close();

    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
    }
}

From source file:ambit2.data.qmrf.Qmrf_Xml_Pdf.java

License:Open Source License

public void xml2pdf(InputSource xml, OutputStream pdf) {

    try {/* ww w  .j  a va  2s  .  c  o m*/
        Document document = new Document(PageSize.A4, 80, 50, 30, 65);

        PdfWriter writer = PdfWriter.getInstance(document, pdf);
        //writer.setViewerPreferences(PdfWriter.HideMenubar| PdfWriter.HideToolbar);
        writer.setViewerPreferences(PdfWriter.PageModeUseThumbs | PdfWriter.PageModeUseOutlines);
        //PdfOutline root = writer.getDirectContent().getRootOutline();
        //new PdfOutline(root, new PDFAction("http://nina.acad.bg/qmrf"), "a bookmark");

        //writer.addFileAttachment(arg0, arg1, arg2, arg3)

        if (docBuilder == null)
            docBuilder = docBuilderFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new SimpleErrorHandler(getClass().getName()));
        QMRFSchemaResolver resolver = new QMRFSchemaResolver("http://ambit2.acad.bg/qmrf/qmrf.dtd", null);
        resolver.setIgnoreSystemID(true);
        docBuilder.setEntityResolver(resolver);

        org.w3c.dom.Document doc = null;
        try {
            doc = docBuilder.parse(xml);
        } catch (Exception x) {
            document.addCreationDate();
            document.addCreator(getClass().getName());
            document.open();
            document.add(new Paragraph(new Chunk(x.getMessage())));
            document.close();
            return;
        }

        document.addCreationDate();
        document.addCreator(getClass().getName());
        document.addKeywords(replaceTags(findNodeValue("keywords", doc)));
        document.addTitle(replaceTags(findNodeValue("QSAR_title", doc)));

        try {
            NodeList info = doc.getElementsByTagName("QMRF");
            for (int i = 0; i < info.getLength(); i++)
                document.addSubject(findAttributeValue("name", info.item(i)) + '.'
                        + findAttributeValue("version", info.item(i)));
        } catch (Exception x) {
            document.addSubject("QMRF");
        }
        try {
            document.addAuthor(listNodeAttributes(doc, "qmrf_authors", "author_ref", "author", att_author,
                    new Boolean(true)));
        } catch (Exception x) {
            document.addAuthor(getClass().getName());
        }

        document.open();
        PdfContentByte cb = writer.getDirectContent();

        try {
            headerTable(document, doc);
        } catch (Exception x) {
            document.add(new Paragraph(new Chunk(x.getMessage())));
            document.close();
            return;
        }

        PdfOutline root = writer.getDirectContent().getRootOutline();

        for (int i = 0; i < subchapters.length; i++)

            try {
                int align = Paragraph.ALIGN_LEFT;
                if (Mode.chapter == (Mode) subchapters[i][2]) {
                    document.add(new Paragraph(new Chunk('\n')));
                    PdfPTable table = new PdfPTable(1);

                    table.setWidthPercentage(100);

                    StringBuffer b = new StringBuffer();
                    b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter, doc));
                    b.append('.');
                    b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_name, doc));

                    String bookmark = b.toString();

                    Chunk title = new Chunk(bookmark);
                    title.setLocalDestination(bookmark);
                    title.setFont(bfont);

                    PdfDestination destination = new PdfDestination(PdfDestination.FITH);
                    PdfOutline outline = new PdfOutline(root, destination, bookmark);

                    Paragraph p = new Paragraph(title);

                    PdfPCell cell = new PdfPCell(p);
                    cell.setBackgroundColor(chapterColor);
                    table.addCell(cell);
                    document.add(table);
                    float pos = writer.getVerticalPosition(false);
                    if (pos < 90)
                        document.newPage();
                } else {
                    Phrase phrase = new Phrase();
                    switch ((Mode) subchapters[i][2]) {
                    case title: {
                        StringBuffer b = new StringBuffer();
                        String cn = findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter,
                                doc);
                        if (cn == null)
                            break;

                        b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter, doc));
                        b.append('.');
                        b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_name, doc));

                        String subchapterBookmark = b.toString();
                        b.append(':');

                        Chunk title = new Chunk(b.toString());
                        title.setLocalDestination(subchapterBookmark);
                        title.setFont(bfont);
                        phrase.add(title);

                        PdfDestination destination = new PdfDestination(PdfDestination.FITBH);
                        PdfOutline outline = new PdfOutline(root, destination, subchapterBookmark);

                        break;

                    }
                    case text: {
                        createNodePhrase(subchapters[i][0].toString(), doc, phrase, font);
                        align = Paragraph.ALIGN_JUSTIFIED;
                        break;
                    }
                    case answer: {
                        String a = findAnswer(subchapters[i][0].toString(), doc);
                        if (a != null) {
                            Chunk answer = new Chunk(a);
                            answer.setFont(font);
                            phrase.add(answer);
                        }
                        break;
                    }
                    case dataset: {
                        StringBuffer b = new StringBuffer();
                        b.append(findDataAvailable(subchapters[i][0].toString(), doc));
                        Chunk dataset = new Chunk(b.toString());
                        dataset.setFont(font);
                        phrase.add(dataset);
                        break;
                    }
                    case attachments: {
                        PdfPTable table = getAttachmentsAsTable(doc, "attachment_training_data");
                        if (table != null) {
                            phrase.add(new Paragraph("Training set(s)"));
                            phrase.add(table);
                        }
                        table = getAttachmentsAsTable(doc, "attachment_validation_data");
                        if (table != null) {
                            phrase.add(new Paragraph("Test set(s)"));
                            phrase.add(table);
                        }
                        table = getAttachmentsAsTable(doc, "attachment_documents");
                        if (table != null) {
                            phrase.add(new Paragraph("Supporting information"));
                            phrase.add(table);
                        }
                        break;
                        /*
                        StringBuffer b = new StringBuffer();
                        b.append("Training set(s)\n");
                         b.append(listAttachments(doc,"attachment_training_data"));
                         b.append("Test set(s)\n");
                         b.append(listAttachments(doc,"attachment_validation_data"));
                         b.append("Supporting information\n");
                         b.append(listAttachments(doc,"attachment_documents"));
                        Chunk attachments = new Chunk(b.toString());
                        attachments.setFont(font);
                        phrase.add(attachments);
                                
                        break;
                        */
                    }
                    case reference: {
                        try {
                            String value = listNodeAttributes(doc, subchapters[i][0].toString(),
                                    subchapters[i][3].toString(), subchapters[i][4].toString(),
                                    (String[]) subchapters[i][5], (Boolean) subchapters[i][6]);

                            Chunk reference = new Chunk(value);
                            reference.setFont(font);
                            align = Paragraph.ALIGN_JUSTIFIED;
                            phrase.add(reference);
                        } catch (Exception x) {

                        }
                        break;

                    }
                    }

                    Paragraph p = new Paragraph(phrase);
                    p.setAlignment(align);
                    document.add(p);
                    float pos = writer.getVerticalPosition(false);
                    /*
                    cb.moveTo(0, pos);
                    cb.lineTo(PageSize.A4.width(), pos);
                    cb.stroke();
                    */
                    if (pos < 90)
                        document.newPage();
                }
            } catch (Exception x) {
                x.printStackTrace();
            }

        document.close();

    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
    }
}

From source file:be.fedict.eid.applet.service.impl.PdfGenerator.java

License:Open Source License

public byte[] generatePdf(EIdData eIdData) throws DocumentException {
    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, baos);

    document.open();/*from  www. ja  v a2  s .c o  m*/

    Paragraph titleParagraph = new Paragraph("eID Identity Data");
    titleParagraph.setAlignment(Paragraph.ALIGN_CENTER);

    Font titleFont = titleParagraph.getFont();
    titleFont.setSize((float) 20.0);
    titleFont.setStyle(Font.BOLD);
    titleParagraph.setSpacingAfter(20);
    document.add(titleParagraph);

    if (null != eIdData && null != eIdData.getIdentity()) {
        if (null != eIdData.getPhoto()) {
            try {
                Image image = createImageFromPhoto(eIdData.getPhoto());
                document.add(image);
            } catch (Exception e) {
                LOG.error("Error getting photo: " + e.getMessage());
            }

            Identity identity = eIdData.getIdentity();

            // metadata
            setDocumentMetadata(document, identity.firstName, identity.name);
            writer.createXmpMetadata();

            // create a table with the data of the eID card
            PdfPTable table = new PdfPTable(2);
            table.getDefaultCell().setBorder(0);

            table.addCell("Name");
            table.addCell(identity.name);

            table.addCell("First name");
            String firstName = identity.firstName;
            if (null != identity.middleName) {
                firstName += " " + identity.middleName;
            }
            table.addCell(firstName);

            table.addCell("Nationality");
            table.addCell(identity.nationality);

            table.addCell("National Registration Number");
            table.addCell(identity.nationalNumber);

            table.addCell("Gender");
            table.addCell(identity.gender.toString());

            table.addCell("Date of birth");
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            table.addCell(formatter.format(identity.dateOfBirth.getTime()));

            table.addCell("Place of birth");
            table.addCell(identity.placeOfBirth);

            if (null != eIdData.getAddress()) {
                Address address = eIdData.getAddress();
                table.addCell("Address");
                PdfPCell cell = new PdfPCell();
                cell.setBorder(0);
                cell.addElement(new Paragraph(address.streetAndNumber));
                cell.addElement(new Paragraph(address.zip + " " + address.municipality));
                table.addCell(cell);
            }

            document.add(table);

            // TODO: to be tested
            /*
            try {
                Image barcodeImage =
                    createBarcodeImage(identity.nationalNumber, identity.cardNumber);
                    
                barcodeImage.setAlignment(Element.ALIGN_CENTER);
                Paragraph barcodePara = new Paragraph();
                barcodePara.add(barcodeImage);
                    
                document.add(barcodeImage);
            } catch (Exception e) {
                LOG.error("Error adding barcode: " + e.getMessage());
            }
            */
        } else {
            document.add(new Paragraph("No eID identity data available."));
        }
    }
    document.close();
    return baos.toByteArray();
}

From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java

License:Open Source License

/**
 * Produce a human readable export of the given tsl to the given file.
 * /*from   w  ww.j ava 2 s  . c  o m*/
 * @param tsl
 *            the TrustServiceList to export
 * @param pdfFile
 *            the file to generate
 * @return
 * @throws IOException
 */
public void humanReadableExport(final TrustServiceList tsl, final File pdfFile) {
    Document document = new Document();
    OutputStream outputStream;
    try {
        outputStream = new FileOutputStream(pdfFile);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("file not found: " + pdfFile.getAbsolutePath(), e);
    }
    try {
        final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);
        pdfWriter.setPDFXConformance(PdfWriter.PDFA1B);

        // title
        final EUCountry country = EUCountry.valueOf(tsl.getSchemeTerritory());
        final String title = country.getShortSrcLangName() + " (" + country.getShortEnglishName()
                + "): Trusted List";

        Phrase footerPhrase = new Phrase("PDF document generated on " + new Date().toString() + ", page ",
                headerFooterFont);
        HeaderFooter footer = new HeaderFooter(footerPhrase, true);
        document.setFooter(footer);

        Phrase headerPhrase = new Phrase(title, headerFooterFont);
        HeaderFooter header = new HeaderFooter(headerPhrase, false);
        document.setHeader(header);

        document.open();
        addTitle(title, title0Font, Paragraph.ALIGN_CENTER, 0, 20, document);

        addLongItem("Scheme name", tsl.getSchemeName(), document);
        addLongItem("Legal Notice", tsl.getLegalNotice(), document);

        // information table
        PdfPTable informationTable = createInfoTable();
        addItemRow("Scheme territory", tsl.getSchemeTerritory(), informationTable);
        addItemRow("Scheme status determination approach",
                substringAfter(tsl.getStatusDeterminationApproach(), "StatusDetn/"), informationTable);
        /*
        final List<String> schemeTypes = new ArrayList<String>();
        for (final String schemeType : tsl.getSchemeTypes()) {
           schemeTypes.add(schemeType);
        }
        */
        final List<String> schemeTypes = new ArrayList<String>();
        List<NonEmptyMultiLangURIType> uris = tsl.getSchemeTypes();
        for (NonEmptyMultiLangURIType uri : uris) {
            schemeTypes.add(uri.getValue());
        }
        addItemRow("Scheme type community rules", schemeTypes, informationTable);

        addItemRow("Issue date", tsl.getListIssueDateTime().toString(), informationTable);
        addItemRow("Next update", tsl.getNextUpdate().toString(), informationTable);
        addItemRow("Historical information period", tsl.getHistoricalInformationPeriod().toString() + " days",
                informationTable);
        addItemRow("Sequence number", tsl.getSequenceNumber().toString(), informationTable);
        addItemRow("Scheme information URIs", tsl.getSchemeInformationUris(), informationTable);

        document.add(informationTable);

        addTitle("Scheme Operator", title1Font, Paragraph.ALIGN_CENTER, 0, 10, document);

        informationTable = createInfoTable();
        addItemRow("Scheme operator name", tsl.getSchemeOperatorName(), informationTable);
        PostalAddressType schemeOperatorPostalAddress = tsl.getSchemeOperatorPostalAddress(Locale.ENGLISH);
        addItemRow("Scheme operator street address", schemeOperatorPostalAddress.getStreetAddress(),
                informationTable);
        addItemRow("Scheme operator postal code", schemeOperatorPostalAddress.getPostalCode(),
                informationTable);
        addItemRow("Scheme operator locality", schemeOperatorPostalAddress.getLocality(), informationTable);
        addItemRow("Scheme operator state", schemeOperatorPostalAddress.getStateOrProvince(), informationTable);
        addItemRow("Scheme operator country", schemeOperatorPostalAddress.getCountryName(), informationTable);

        List<String> schemeOperatorElectronicAddressess = tsl.getSchemeOperatorElectronicAddresses();
        addItemRow("Scheme operator contact", schemeOperatorElectronicAddressess, informationTable);
        document.add(informationTable);

        addTitle("Trust Service Providers", title1Font, Paragraph.ALIGN_CENTER, 10, 2, document);

        List<TrustServiceProvider> trustServiceProviders = tsl.getTrustServiceProviders();
        for (TrustServiceProvider trustServiceProvider : trustServiceProviders) {
            addTitle(trustServiceProvider.getName(), title1Font, Paragraph.ALIGN_LEFT, 10, 2, document);

            PdfPTable providerTable = createInfoTable();
            addItemRow("Service provider trade name", trustServiceProvider.getTradeNames(), providerTable);
            addItemRow("Information URI", trustServiceProvider.getInformationUris(), providerTable);
            PostalAddressType postalAddress = trustServiceProvider.getPostalAddress();
            addItemRow("Service provider street address", postalAddress.getStreetAddress(), providerTable);
            addItemRow("Service provider postal code", postalAddress.getPostalCode(), providerTable);
            addItemRow("Service provider locality", postalAddress.getLocality(), providerTable);
            addItemRow("Service provider state", postalAddress.getStateOrProvince(), providerTable);
            addItemRow("Service provider country", postalAddress.getCountryName(), providerTable);
            document.add(providerTable);

            List<TrustService> trustServices = trustServiceProvider.getTrustServices();
            for (TrustService trustService : trustServices) {
                addTitle(trustService.getName(), title2Font, Paragraph.ALIGN_LEFT, 10, 2, document);
                PdfPTable serviceTable = createInfoTable();
                addItemRow("Type", substringAfter(trustService.getType(), "Svctype/"), serviceTable);
                addItemRow("Status", substringAfter(trustService.getStatus(), "Svcstatus/"), serviceTable);
                addItemRow("Status starting time", trustService.getStatusStartingTime().toString(),
                        serviceTable);
                document.add(serviceTable);

                addTitle("Service digital identity (X509)", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document);
                final X509Certificate certificate = trustService.getServiceDigitalIdentity();
                final PdfPTable serviceIdentityTable = createInfoTable();
                addItemRow("Version", Integer.toString(certificate.getVersion()), serviceIdentityTable);
                addItemRow("Serial number", certificate.getSerialNumber().toString(), serviceIdentityTable);
                addItemRow("Signature algorithm", certificate.getSigAlgName(), serviceIdentityTable);
                addItemRow("Issuer", certificate.getIssuerX500Principal().toString(), serviceIdentityTable);
                addItemRow("Valid from", certificate.getNotBefore().toString(), serviceIdentityTable);
                addItemRow("Valid to", certificate.getNotAfter().toString(), serviceIdentityTable);
                addItemRow("Subject", certificate.getSubjectX500Principal().toString(), serviceIdentityTable);
                addItemRow("Public key", certificate.getPublicKey().toString(), serviceIdentityTable);
                // TODO certificate policies
                addItemRow("Subject key identifier", toHex(getSKId(certificate)), serviceIdentityTable);
                addItemRow("CRL distribution points", getCrlDistributionPoints(certificate),
                        serviceIdentityTable);
                addItemRow("Authority key identifier", toHex(getAKId(certificate)), serviceIdentityTable);
                addItemRow("Key usage", getKeyUsage(certificate), serviceIdentityTable);
                addItemRow("Basic constraints", getBasicConstraints(certificate), serviceIdentityTable);

                byte[] encodedCertificate;
                try {
                    encodedCertificate = certificate.getEncoded();
                } catch (CertificateEncodingException e) {
                    throw new RuntimeException("cert: " + e.getMessage(), e);
                }
                addItemRow("SHA1 Thumbprint", DigestUtils.shaHex(encodedCertificate), serviceIdentityTable);
                addItemRow("SHA256 Thumbprint", DigestUtils.sha256Hex(encodedCertificate),
                        serviceIdentityTable);
                document.add(serviceIdentityTable);

                //add Scheme service definition 
                if (null != trustService.getSchemeServiceDefinitionURI()) {
                    addTitle("Scheme Service Definition URI", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document);
                    final PdfPTable schemeServiceDefinitionURITabel = createInfoTable();
                    for (NonEmptyMultiLangURIType uri : trustService.getSchemeServiceDefinitionURI().getURI()) {
                        addItemRow(uri.getLang(), uri.getValue(), schemeServiceDefinitionURITabel);
                    }
                    document.add(schemeServiceDefinitionURITabel);
                }

                List<ExtensionType> extensions = trustService.getExtensions();
                for (ExtensionType extension : extensions) {
                    printExtension(extension, document);
                }

                addLongMonoItem("The decoded certificate:", certificate.toString(), document);
                addLongMonoItem("The certificate in PEM format:", toPem(certificate), document);

                ServiceHistoryType serviceHistoryType = trustService.getServiceHistoryInstanceType();

                if (null != serviceHistoryType) {

                    for (ServiceHistoryInstanceType serviceHistoryInstanceType : serviceHistoryType
                            .getServiceHistoryInstance()) {
                        PdfPTable serviceHistoryTable = createInfoTable();

                        //Service approval history information
                        addTitle("Service approval history information", title3Font, Paragraph.ALIGN_LEFT, 10,
                                2, document);

                        // service type identifier
                        //5.6.2 Service name
                        InternationalNamesType i18nServiceName = serviceHistoryInstanceType.getServiceName();
                        String servName = TrustServiceListUtils.getValue(i18nServiceName, Locale.ENGLISH);
                        addItemRow("Name", servName, serviceHistoryTable);
                        //5.6.1 Service type identifier
                        addItemRow("Type", substringAfter(serviceHistoryInstanceType.getServiceTypeIdentifier(),
                                "Svctype/"), serviceHistoryTable);
                        addItemRow("Status", serviceHistoryInstanceType.getServiceStatus(),
                                serviceHistoryTable);
                        //5.6.4 Service previous status
                        addItemRow("Previous status", serviceHistoryInstanceType.getServiceStatus(),
                                serviceHistoryTable);
                        //5.6.5 Previous status starting date and time
                        addItemRow(
                                "Previous starting time", new DateTime(serviceHistoryInstanceType
                                        .getStatusStartingTime().toGregorianCalendar()).toString(),
                                serviceHistoryTable);
                        //5.6.3 Service digital identity
                        final X509Certificate previousCertificate = trustService.getServiceDigitalIdentity(
                                serviceHistoryInstanceType.getServiceDigitalIdentity());

                        document.add(serviceHistoryTable);

                        addTitle("Service digital identity (X509)", title4Font, Paragraph.ALIGN_LEFT, 2, 0,
                                document);

                        final PdfPTable serviceIdentityTableHistory = createInfoTable();
                        addItemRow("Version", Integer.toString(previousCertificate.getVersion()),
                                serviceIdentityTableHistory);
                        addItemRow("Serial number", previousCertificate.getSerialNumber().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Signature algorithm", previousCertificate.getSigAlgName(),
                                serviceIdentityTableHistory);
                        addItemRow("Issuer", previousCertificate.getIssuerX500Principal().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Valid from", previousCertificate.getNotBefore().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Valid to", previousCertificate.getNotAfter().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Subject", previousCertificate.getSubjectX500Principal().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Public key", previousCertificate.getPublicKey().toString(),
                                serviceIdentityTableHistory);
                        // TODO certificate policies
                        addItemRow("Subject key identifier", toHex(getSKId(previousCertificate)),
                                serviceIdentityTableHistory);
                        addItemRow("CRL distribution points", getCrlDistributionPoints(previousCertificate),
                                serviceIdentityTableHistory);
                        addItemRow("Authority key identifier", toHex(getAKId(previousCertificate)),
                                serviceIdentityTableHistory);
                        addItemRow("Key usage", getKeyUsage(previousCertificate), serviceIdentityTableHistory);
                        addItemRow("Basic constraints", getBasicConstraints(previousCertificate),
                                serviceIdentityTableHistory);

                        byte[] encodedHistoryCertificate;
                        try {
                            encodedHistoryCertificate = previousCertificate.getEncoded();
                        } catch (CertificateEncodingException e) {
                            throw new RuntimeException("cert: " + e.getMessage(), e);
                        }
                        addItemRow("SHA1 Thumbprint", DigestUtils.shaHex(encodedHistoryCertificate),
                                serviceIdentityTableHistory);
                        addItemRow("SHA256 Thumbprint", DigestUtils.sha256Hex(encodedHistoryCertificate),
                                serviceIdentityTableHistory);
                        document.add(serviceIdentityTableHistory);

                        ExtensionsListType previousExtensions = serviceHistoryInstanceType
                                .getServiceInformationExtensions();
                        if (null != previousExtensions) {
                            for (ExtensionType extension : previousExtensions.getExtension()) {
                                printExtension(extension, document);
                            }
                        }

                        addLongMonoItem("The decoded certificate:", previousCertificate.toString(), document);
                        addLongMonoItem("The certificate in PEM format:", toPem(previousCertificate), document);
                    }
                }
            }
        }

        X509Certificate signerCertificate = tsl.verifySignature();
        if (null != signerCertificate) {
            Paragraph tslSignerTitle = new Paragraph("Trusted List Signer", title1Font);
            tslSignerTitle.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(tslSignerTitle);

            final PdfPTable signerTable = createInfoTable();
            addItemRow("Subject", signerCertificate.getSubjectX500Principal().toString(), signerTable);
            addItemRow("Issuer", signerCertificate.getIssuerX500Principal().toString(), signerTable);
            addItemRow("Not before", signerCertificate.getNotBefore().toString(), signerTable);
            addItemRow("Not after", signerCertificate.getNotAfter().toString(), signerTable);
            addItemRow("Serial number", signerCertificate.getSerialNumber().toString(), signerTable);
            addItemRow("Version", Integer.toString(signerCertificate.getVersion()), signerTable);
            byte[] encodedPublicKey = signerCertificate.getPublicKey().getEncoded();
            addItemRow("Public key SHA1 Thumbprint", DigestUtils.shaHex(encodedPublicKey), signerTable);
            addItemRow("Public key SHA256 Thumbprint", DigestUtils.sha256Hex(encodedPublicKey), signerTable);
            document.add(signerTable);

            addLongMonoItem("The decoded certificate:", signerCertificate.toString(), document);
            addLongMonoItem("The certificate in PEM format:", toPem(signerCertificate), document);
            addLongMonoItem("The public key in PEM format:", toPem(signerCertificate.getPublicKey()), document);
        }

        document.close();
    } catch (DocumentException e) {
        throw new RuntimeException("PDF document error: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new RuntimeException("Exception: " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java

License:Open Source License

protected void addTitle(final String titleText, final Font titleFont, final int align,
        final float spacingBefore, final float spacingAfter, final Document doc) throws DocumentException {
    final Paragraph titlePara = new Paragraph(titleText, titleFont);
    titlePara.setAlignment(align);
    titlePara.setSpacingBefore(spacingBefore);
    titlePara.setSpacingAfter(spacingAfter);
    doc.add(titlePara);//w w  w  .  java  2  s. co  m
}

From source file:beans.ManagedBeanProducto.java

License:Open Source License

public String CreatePdf() throws IOException, DocumentException {
    ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
    //System.out.println(" test: "+extContext);
    //System.out.println(" esta es la ruta" + extContext.getRealPath("//pdfs//"));
    // step 1/*from   ww w  .  j  a v a2  s  . c o  m*/
    String ruta_pdfs = extContext.getRealPath("//pdfs//");
    Document document = new Document(PageSize.A4);
    document.setMargins(5, 5, 25, 25);
    document.setMarginMirroring(true);

    // step 2
    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(ruta_pdfs + "//CB" + Producto.getIdProducto() + ".pdf"));
    // step 3
    document.open();
    // step 4
    PdfContentByte cb = writer.getDirectContent();

    Paragraph Titulo = new Paragraph(
            "PRODUCTO : " + Producto.getNombreProducto().substring(14).toUpperCase() + "\n\n");
    Titulo.setAlignment(Paragraph.ALIGN_CENTER);
    document.add(Titulo);

    // EAN 13
    // document.add(new Paragraph("Barcode EAN.UCC-13"));
    BarcodeEAN codeEAN = new BarcodeEAN();

    codeEAN.setCode(CodigoBarrasFinal());
    String nombre_producto = "";
    if (Producto.getNombreProducto().length() >= 41) {
        nombre_producto = Producto.getNombreProducto().substring(14, 41);
    } else {
        nombre_producto = Producto.getNombreProducto().substring(14);
    }
    // document.add(new Paragraph(nombre_producto,new Font(Font.COURIER, 5, Font.NORMAL)));
    // document.add(codeEAN.createImageWithBarcode(cb,Color.BLUE , Color.BLUE));
    // codeEAN.setGuardBars(false);

    // document.add(new Paragraph(nombre_producto,new Font(Font.COURIER, 5, Font.NORMAL)));
    // codeEAN.setGuardBars(false);
    Image imagen = codeEAN.createImageWithBarcode(cb, null, null);
    imagen.scaleAbsolute(87, 45);
    //document.add(imagen);

    PdfPTable table = new PdfPTable(5);
    table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
    // table.setTotalWidth(1800);
    PdfPCell cell;
    Phrase nombre = new Phrase(nombre_producto.toUpperCase(),
            new Font(Font.COURIER, 5, Font.BOLD, Color.BLACK));

    cell = new PdfPCell();
    cell.addElement(nombre);
    //cell.addElement(new Chunk("\n"));
    cell.addElement(imagen);
    //cell.addElement(new Chunk("\n"));

    table.addCell(cell);
    //table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);

    table.addCell(cell);
    //table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);

    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    document.add(table);

    // EAN 8 "6987";
    // String inicio ="345";
    //  int intermedio =1000+Producto.getIdProducto();
    //  String fin ="0";
    // document.add(new Paragraph(Producto.getNombreProducto(),new Font(Font.COURIER, 4, Font.NORMAL)));
    // codeEAN.setCodeType(Barcode.EAN8);
    // codeEAN.setBarHeight(codeEAN.getSize() * 1.5f);
    // codeEAN.setCode(inicio.concat(intermedio+fin));
    // document.add(codeEAN.createImageWithBarcode(cb, null, null));
    document.close();

    return "codigo_barras_productos";
}

From source file:biblivre3.administration.reports.AllUsersReport.java

License:Open Source License

@Override
protected void generateReportBody(Document document, BaseReportDto reportData) throws Exception {
    AllUsersReportDto dto = (AllUsersReportDto) reportData;
    Paragraph p1 = new Paragraph(this.getText("REPORTS_ALL_USERS"));
    p1.setAlignment(Paragraph.ALIGN_CENTER);
    document.add(p1);//from   w ww . j  a va2 s.  c o  m
    document.add(new Phrase("\n"));
    Paragraph p2 = new Paragraph(this.getHeaderChunk(this.getText("REPORTS_ALL_USERS_TYPE_TOTALS")));
    p2.setAlignment(Paragraph.ALIGN_LEFT);
    document.add(p2);
    document.add(new Phrase("\n"));
    PdfPTable summaryTable = createSummaryTable(dto.getTypesMap());
    document.add(summaryTable);
    document.add(new Phrase("\n"));

    ArrayList<PdfPTable> listTable = createListTable(dto.getData());
    if (listTable != null) {
        Paragraph p3 = new Paragraph(this.getHeaderChunk(this.getText("REPORTS_ALL_USERS_TYPE_LIST")));
        p3.setAlignment(Paragraph.ALIGN_LEFT);
        document.add(p3);
        document.add(new Phrase("\n"));
        for (PdfPTable tabela : listTable) {
            document.add(tabela);
            document.add(new Phrase("\n"));
        }
    }
}