Example usage for com.lowagie.text Document add

List of usage examples for com.lowagie.text Document add

Introduction

In this page you can find the example usage for com.lowagie.text Document add.

Prototype


public boolean add(Element element) throws DocumentException 

Source Link

Document

Adds an Element to the Document.

Usage

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();// ww w . j a  va 2  s  . co 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  ww  w .  j  av a  2s  .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

private void printExtension(ExtensionType extension, Document document) throws DocumentException {

    List<Object> contentList = extension.getContent();
    for (Object content : contentList) {
        LOG.debug("extension content: " + content.getClass().getName());
        if (content instanceof JAXBElement<?>) {
            JAXBElement<?> element = (JAXBElement<?>) content;
            LOG.debug("QName: " + element.getName());
            if (true == ADDITIONAL_SERVICE_INFORMATION_QNAME.equals(element.getName())) {
                addTitle("Extension (critical: " + extension.isCritical() + ")", title3Font,
                        Paragraph.ALIGN_LEFT, 0, 0, document);
                addTitle("Additional service information", title4Font, Paragraph.ALIGN_LEFT, 0, 0, document);
                AdditionalServiceInformationType additionalServiceInformation = (AdditionalServiceInformationType) element
                        .getValue();//w  w  w.j  a v a 2 s  .  c o m
                LOG.debug("information value: " + additionalServiceInformation.getInformationValue());
                NonEmptyMultiLangURIType multiLangUri = additionalServiceInformation.getURI();
                LOG.debug("URI : " + multiLangUri.getValue() + " (language: " + multiLangUri.getLang() + ")");
                document.add(new Paragraph(
                        multiLangUri.getValue().substring(
                                multiLangUri.getValue().indexOf("SvcInfoExt/") + "SvcInfoExt/".length()),
                        this.valueFont));
            } else {
                addTitle("Extension (critical: " + extension.isCritical() + ")", title3Font,
                        Paragraph.ALIGN_LEFT, 0, 0, document);
                addTitle("Qualifications", title4Font, Paragraph.ALIGN_LEFT, 0, 0, document);

                LOG.debug("element namespace: " + element.getName());
                LOG.debug("element name: " + element.getScope());
                if ("http://uri.etsi.org/TrstSvc/SvcInfoExt/eSigDir-1999-93-EC-TrustedList/#"
                        .equals(element.getName().getNamespaceURI())
                        && "Qualifications".equals(element.getName().getLocalPart())) {
                    QualificationsType qualifications = (QualificationsType) element.getValue();
                    List<QualificationElementType> qualificationElements = qualifications
                            .getQualificationElement();
                    for (QualificationElementType qualificationElement : qualificationElements) {
                        QualifiersType qualifiers = qualificationElement.getQualifiers();
                        List<QualifierType> qualifierList = qualifiers.getQualifier();
                        for (QualifierType qualifier : qualifierList) {
                            document.add(new Paragraph(
                                    "Qualifier: " + qualifier.getUri().substring(
                                            qualifier.getUri().indexOf("SvcInfoExt/") + "SvcInfoExt/".length()),
                                    this.valueFont));
                        }

                        CriteriaListType criteriaList = qualificationElement.getCriteriaList();
                        String description = criteriaList.getDescription();
                        if (null != description) {
                            document.add(new Paragraph("Criterial List Description", this.labelFont));
                            document.add(new Paragraph(description, this.valueFont));
                        }
                        document.add(new Paragraph("Assert: " + criteriaList.getAssert(), this.valueFont));
                        List<PoliciesListType> policySet = criteriaList.getPolicySet();
                        for (PoliciesListType policiesList : policySet) {
                            List<ObjectIdentifierType> oids = policiesList.getPolicyIdentifier();
                            for (ObjectIdentifierType oid : oids) {
                                document.add(new Paragraph("Policy OID: " + oid.getIdentifier().getValue(),
                                        this.valueFont));
                            }
                        }
                    }
                }

            }

        } else if (content instanceof Element) {
            addTitle("Qualifications", title4Font, Paragraph.ALIGN_LEFT, 0, 0, document);
            Element element = (Element) content;
            LOG.debug("element namespace: " + element.getNamespaceURI());
            LOG.debug("element name: " + element.getLocalName());
            if ("http://uri.etsi.org/TrstSvc/SvcInfoExt/eSigDir-1999-93-EC-TrustedList/#"
                    .equals(element.getNamespaceURI()) && "Qualifications".equals(element.getLocalName())) {
                try {
                    QualificationsType qualifications = unmarshallQualifications(element);
                    List<QualificationElementType> qualificationElements = qualifications
                            .getQualificationElement();
                    for (QualificationElementType qualificationElement : qualificationElements) {
                        QualifiersType qualifiers = qualificationElement.getQualifiers();
                        List<QualifierType> qualifierList = qualifiers.getQualifier();
                        for (QualifierType qualifier : qualifierList) {
                            document.add(new Paragraph(
                                    "Qualifier: " + qualifier.getUri().substring(
                                            qualifier.getUri().indexOf("SvcInfoExt/") + "SvcInfoExt/".length()),
                                    this.valueFont));
                        }

                        CriteriaListType criteriaList = qualificationElement.getCriteriaList();
                        String description = criteriaList.getDescription();
                        if (null != description) {
                            document.add(new Paragraph("Criterial List Description", this.labelFont));
                            document.add(new Paragraph(description, this.valueFont));
                        }
                        document.add(new Paragraph("Assert: " + criteriaList.getAssert(), this.valueFont));
                        List<PoliciesListType> policySet = criteriaList.getPolicySet();
                        for (PoliciesListType policiesList : policySet) {
                            List<ObjectIdentifierType> oids = policiesList.getPolicyIdentifier();
                            for (ObjectIdentifierType oid : oids) {
                                document.add(new Paragraph("Policy OID: " + oid.getIdentifier().getValue(),
                                        this.valueFont));
                            }
                        }
                    }
                } catch (JAXBException e) {
                    LOG.error("JAXB error: " + e.getMessage(), e);
                }
            }
        }
    }
}

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

License:Open Source License

protected void addLongItem(final String label, final String value, final Document doc)
        throws DocumentException {
    doc.add(new Paragraph(label, labelFont));
    doc.add(new Paragraph(value, valueFont));
}

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

License:Open Source License

protected void addLongMonoItem(final String label, final String value, final Document doc)
        throws DocumentException {
    doc.add(new Paragraph(label, labelFont));
    doc.add(new Paragraph(value, monoFont));
}

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);//  w  w  w.ja v  a 2 s  . c o m
    titlePara.setSpacingBefore(spacingBefore);
    titlePara.setSpacingAfter(spacingAfter);
    doc.add(titlePara);
}

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   w  ww.  j  ava 2s.  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:beans.ReportsMB.java

public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {
    if (null == selectedReport) {
        return;/*from w w w  .  j av  a 2 s .co m*/
    }

    Document pdf = (Document) document;
    String documentTitle = getPDFraportTitle(selectedReport);
    pdf.addTitle(documentTitle);
    pdf.open();
    pdf.setPageSize(PageSize.A4);
    pdf.add(new Phrase(documentTitle));

}

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);
    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);//  ww  w .j  av  a  2  s. c om
    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"));
        }
    }
}

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

License:Open Source License

@Override
protected void generateReportBody(Document document, BaseReportDto reportData) throws Exception {
    AssetHoldingByDateDto dto = (AssetHoldingByDateDto) reportData;
    Paragraph p1 = new Paragraph(this.getText("REPORTS_ASSET_HOLDING_BY_DATE_TITLE"));
    p1.setAlignment(Paragraph.ALIGN_CENTER);
    document.add(p1);
    document.add(new Phrase("\n"));
    PdfPTable table = new PdfPTable(8);
    table.setWidthPercentage(100f);/*from  w  ww.  j a va2  s.  co  m*/
    createHeader(table);
    PdfPCell cell;
    List<String[]> dataList = dto.getData();
    for (String[] data : dataList) {
        cell = new PdfPCell(new Paragraph(this.getSmallFontChunk(data[0])));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(this.getSmallFontChunk(data[1])));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(this.getSmallFontChunk(data[2])));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(this.getSmallFontChunk(data[3])));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(this.getSmallFontChunk(data[4])));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(this.getSmallFontChunk(data[5])));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        table.addCell(cell);
    }
    document.add(table);
}