Example usage for com.lowagie.text Document open

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

Introduction

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

Prototype

boolean open

To view the source code for com.lowagie.text Document open.

Click Source Link

Document

Is the document open or not?

Usage

From source file:at.tugraz.sss.serv.util.SSFileU.java

License:Apache License

public static void writePDFFromDoc(final String docFilePath, final String pdfFilePath) throws SSErr {

    try {//www  .  jav  a  2 s . c o  m
        final Document document = new Document();
        final POIFSFileSystem fs = new POIFSFileSystem(openFileForRead(docFilePath));
        final HWPFDocument word = new HWPFDocument(fs);
        final WordExtractor we = new WordExtractor(word);
        final OutputStream out = openOrCreateFileWithPathForWrite(pdfFilePath);
        final PdfWriter writer = PdfWriter.getInstance(document, out);
        final Range range = word.getRange();

        document.open();
        writer.setPageEmpty(true);
        document.newPage();
        writer.setPageEmpty(true);

        String[] paragraphs = we.getParagraphText();

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

            org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
            // CharacterRun run = pr.getCharacterRun(i);
            // run.setBold(true);
            // run.setCapitalized(true);
            // run.setItalic(true);
            paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");
            System.out.println("Length:" + paragraphs[i].length());
            System.out.println("Paragraph" + i + ": " + paragraphs[i].toString());

            // add the paragraph to the document
            document.add(new Paragraph(paragraphs[i]));
        }

        document.close();
    } catch (Exception error) {
        SSServErrReg.regErrThrow(error);
    }
}

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();

    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);/* www  . ja va2s.  c om*/
    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 w w . ja  va2  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: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  w  w  .  j  av  a  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 a  v  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.BaseBiblivreReport.java

License:Open Source License

protected MemoryFileDTO generateReportFile(BaseReportDto reportData, String fileName) {
    Document document = new Document(PageSize.A4);
    MemoryFileDTO report = new MemoryFileDTO();
    report.setFileName(fileName);//w w w  .jav a  2s.co m
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(this);
        writer.setFullCompression();
        document.open();
        generateReportBody(document, reportData);
        writer.flush();
        document.close();
        report.setFileData(baos.toByteArray());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return null;
    }
    return report;
}

From source file:biblivre3.cataloging.bibliographic.BiblioBO.java

License:Open Source License

public MemoryFileDTO createFileLabelsPDF(ArrayList<LabelDTO> labels, LabelConfigDTO labelConfig) {
    Document document = new Document();
    final MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName("biblivre_etiquetas_" + new Date().getTime() + ".pdf");
    try {/*from   ww w  . j  a  v  a2s  . co m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.setPageSize(PageSize.A4);
        float verticalMargin = (297.0f - (labelConfig.getHeight() * labelConfig.getRows())) / 2;
        document.setMargins(7.15f * ApplicationConstants.MM_UNIT, 7.15f * ApplicationConstants.MM_UNIT,
                verticalMargin * ApplicationConstants.MM_UNIT, verticalMargin * ApplicationConstants.MM_UNIT);
        document.open();

        PdfPTable table = new PdfPTable(labelConfig.getColumns());
        table.setWidthPercentage(100f);
        PdfPCell cell;

        int i = 0;
        for (i = 0; i < labelConfig.getOffset(); i++) {
            cell = new PdfPCell();
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            table.addCell(cell);
        }

        for (LabelDTO ldto : labels) {
            PdfContentByte cb = writer.getDirectContent();

            String holdingSerial = String.valueOf(ldto.getHoldingSerial());
            while (holdingSerial.length() < 10) {
                holdingSerial = "0" + holdingSerial;
            }
            Barcode39 code39 = new Barcode39();
            code39.setExtended(true);
            code39.setCode(holdingSerial);
            code39.setStartStopText(false);

            Image image39 = code39.createImageWithBarcode(cb, null, null);
            if (labelConfig.getHeight() > 30.0f) {
                image39.scalePercent(110f);
            } else {
                image39.scalePercent(90f);
            }

            Paragraph para = new Paragraph();
            Phrase p1 = new Phrase(StringUtils.left(ldto.getAuthor(), 28) + "\n");
            Phrase p2 = new Phrase(StringUtils.left(ldto.getTitle(), 28) + "\n\n");
            Phrase p3 = new Phrase(new Chunk(image39, 0, 0));
            para.add(p1);
            para.add(p2);
            para.add(p3);

            cell = new PdfPCell(para);
            i++;
            cell.setNoWrap(true);
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);

            Paragraph para2 = new Paragraph();
            Phrase p5 = new Phrase(ldto.getLocationA() + "\n");
            Phrase p6 = new Phrase(ldto.getLocationB() + "\n");
            Phrase p7 = new Phrase(ldto.getLocationC() + "\n");
            Phrase p8 = new Phrase(ldto.getLocationD() + "\n");
            Phrase p4 = new Phrase(ldto.getAssetHolding() + "\n");
            para2.add(p5);
            para2.add(p6);
            para2.add(p7);
            para2.add(p8);
            para2.add(p4);

            cell = new PdfPCell(para2);
            i++;
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }
        if ((i % labelConfig.getColumns()) != 0) {
            while ((i % labelConfig.getColumns()) != 0) {
                i++;
                cell = new PdfPCell();
                cell.setBorder(Rectangle.NO_BORDER);
                table.addCell(cell);
            }
        }
        document.add(table);
        writer.flush();
        document.close();
        file.setFileData(baos.toByteArray());
    } catch (Exception de) {
        System.out.println(de.getMessage());
    }
    return file;
}

From source file:biblivre3.circulation.CirculationBO.java

License:Open Source License

public MemoryFileDTO createFileUserCardsPDF(ArrayList<UserCardDTO> cards, int startOffset, Properties i18n) {
    Document document = new Document();
    MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName("user_cards_" + new Date().getTime() + ".pdf");
    try {//from   w w w  . ja v  a 2 s . c  o m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.setPageSize(PageSize.A4);
        document.setMargins(7.15f * ApplicationConstants.MM_UNIT, 7.15f * ApplicationConstants.MM_UNIT,
                9.09f * ApplicationConstants.MM_UNIT, 9.09f * ApplicationConstants.MM_UNIT);
        document.open();
        PdfPTable table = new PdfPTable(3);
        table.setWidthPercentage(100f);
        PdfPCell cell;
        int i = 0;
        for (i = 0; i < startOffset; i++) {
            cell = new PdfPCell();
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setFixedHeight(46.47f * ApplicationConstants.MM_UNIT);
            table.addCell(cell);
        }
        for (UserCardDTO card : cards) {
            String userEnrollNumber = String.valueOf(card.getUserId());
            PdfContentByte cb = writer.getDirectContent();
            Barcode39 code39 = new Barcode39();
            code39.setExtended(true);
            while (userEnrollNumber.length() < 10) {
                userEnrollNumber = "0" + userEnrollNumber;
            }
            code39.setCode(userEnrollNumber);
            code39.setStartStopText(false);
            Image image39 = code39.createImageWithBarcode(cb, null, null);
            image39.scalePercent(110f);
            Paragraph para = new Paragraph();
            String name = card.getUserName();
            name = name.length() >= 30 ? name.substring(0, 30) : name;
            Phrase p1 = new Phrase(name + "\n");
            Phrase p2 = new Phrase(new Chunk(image39, 0, 0));
            Phrase p3 = new Phrase(
                    I18nUtils.getText(i18n, "LABEL_USER_SERIAL") + ": " + card.getUserId() + "\n");
            Phrase p4 = new Phrase(
                    I18nUtils.getText(i18n, "LABEL_USER_TYPE") + ": " + card.getUserType() + "\n\n");
            para.add(p1);
            para.add(p3);
            para.add(p4);
            para.add(p2);
            cell = new PdfPCell(para);
            i++;
            cell.setFixedHeight(46.47f * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }
        if ((i % 3) != 0) {
            while ((i % 3) != 0) {
                i++;
                cell = new PdfPCell();
                cell.setBorder(Rectangle.NO_BORDER);
                table.addCell(cell);
            }
        }
        document.add(table);
        writer.flush();
        document.close();
        writer.close();
        file.setFileData(baos.toByteArray());
    } catch (DocumentException de) {
        System.out.println(de.getMessage());
    }
    return file;
}

From source file:binky.reportrunner.engine.renderers.exporters.HTMLExporter.java

License:Open Source License

@Override
public void export(ResultSet resultSet, String label, OutputStream outputStream) throws ExportException {
    try {//from ww w  .j  a  v a  2  s  .c om
        Document document = new Document();
        HtmlWriter.getInstance(document, outputStream);

        // open the document object
        document.open();

        ResultSetMetaData metaData = resultSet.getMetaData();
        Table table = new Table(metaData.getColumnCount());
        for (int i = 1; i <= metaData.getColumnCount(); i++) {
            Paragraph para = new Paragraph(metaData.getColumnName(i), new Font(Font.HELVETICA, 10, Font.BOLD));
            Cell cell = new Cell(para);
            table.addCell(cell);
        }

        while (resultSet.next()) {
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                Paragraph para = new Paragraph("" + resultSet.getObject(i),
                        new Font(Font.HELVETICA, 10, Font.NORMAL));
                Cell cell = new Cell(para);
                table.addCell(cell);
            }

        }
        document.add(table);
        document.close();
    } catch (DocumentException e) {
        throw new ExportException(e.getMessage(), e);
    } catch (SQLException e) {
        throw new ExportException(e.getMessage(), e);
    }
}

From source file:binky.reportrunner.engine.renderers.exporters.PDFExporter.java

License:Open Source License

@Override
public void export(ResultSet resultSet, String label, OutputStream outputStream) throws ExportException {
    try {/*from  w  w  w  . j  av a2 s . com*/
        Document document = new Document();
        PdfWriter.getInstance(document, outputStream);

        // open the document object
        document.open();

        ResultSetMetaData metaData = resultSet.getMetaData();
        PdfPTable table = new PdfPTable(metaData.getColumnCount());
        for (int i = 1; i <= metaData.getColumnCount(); i++) {
            Paragraph para = new Paragraph(metaData.getColumnName(i), new Font(Font.HELVETICA, 10, Font.BOLD));
            PdfPCell cell = new PdfPCell(para);
            table.addCell(cell);
        }

        while (resultSet.next()) {
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                Paragraph para = new Paragraph("" + resultSet.getObject(i),
                        new Font(Font.HELVETICA, 10, Font.NORMAL));
                PdfPCell cell = new PdfPCell(para);
                table.addCell(cell);
            }

        }
        document.add(table);
        document.close();
    } catch (DocumentException e) {
        throw new ExportException(e.getMessage(), e);
    } catch (SQLException e) {
        throw new ExportException(e.getMessage(), e);
    }
}