Example usage for com.lowagie.text Document setHeader

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

Introduction

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

Prototype


public void setHeader(HeaderFooter header) 

Source Link

Document

Changes the header of this document.

Usage

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.
 * //  ww  w  . j a  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:ch.gpb.elexis.cst.view.CstResultPart.java

License:Open Source License

private void makeActions(final Control viewer) {

    actionScreenshot = new Action() {
        public void run() {
            if (profile == null) {
                SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden");
                return;
            }//from w  ww. j  a  v a  2 s  .  c o  m

            GC gc = null;
            Image image = null;
            try {

                String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null);
                if (latestPath == null) {
                    latestPath = System.getProperty("user.home");
                }

                FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE);
                fd.setText("Save");
                fd.setFilterPath(latestPath);
                String[] filterExt = { "*.png", "*.*" };
                fd.setFilterExtensions(filterExt);
                fd.setFileName(CstService.generateFilename(patient));
                String selected = fd.open();

                if (selected == null) {
                    return;
                }

                File selFile = new File(selected);

                CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH,
                        selFile.getParentFile().getAbsolutePath());

                //if (profile.getAnzeigeTyp().toLowerCase().equals("effektiv")) {
                if (profile.getAnzeigeTyp().toLowerCase().equals(CstProfile.ANZEIGETYP_EFFEKTIV)) {

                    if (profile.getAusgabeRichtung()) {
                        image = new Image(viewer.getDisplay(), 1123, viewer.getBounds().height);

                    } else {
                        image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height);

                    }
                } else {
                    image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height);

                }

                ImageLoader loader = new ImageLoader();

                gc = new GC(image);
                viewer.print(gc);

                gc.dispose();

                loader.data = new ImageData[] { image.getImageData() };
                loader.save(selected, SWT.IMAGE_PNG);

            } catch (Exception e) {
                log.error("Error saving png: " + e.toString());
                showMessage("Error while saving PNG", e.getMessage());
            } finally {
                if (image != null) {
                    image.dispose();
                }
                if (gc != null) {
                    gc.dispose();
                }
            }

        }
    };
    actionScreenshot.setText(Messages.Cst_Text_Save_as_png);
    actionScreenshot.setToolTipText(Messages.Cst_Text_Save_as_png);
    actionScreenshot.setImageDescriptor(
            PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ELEMENT));
    actionScreenshot.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PNG_PATH));

    // TODO: die pdf ausgabe ist eine ziemliche Baustelle - berarbeiten
    actionPdf = new Action() {
        public void run() {

            //////////////////////////
            if (profile == null) {
                SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden");
                return;
            }

            GC gc = null;
            Image image = null;
            try {
                String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null);
                if (latestPath == null) {
                    latestPath = System.getProperty("user.home");
                }

                FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE);
                fd.setText("Save");
                fd.setFilterPath(latestPath);
                String[] filterExt = { "*.pdf", "*.*" };
                fd.setFilterExtensions(filterExt);
                fd.setFileName(CstService.generateFilename(patient));
                String selected = fd.open();

                if (selected == null) {
                    return;
                }
                File selFile = new File(selected);

                CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH,
                        selFile.getParentFile().getAbsolutePath());

                int printHeigth = 1123;
                int printWidth = 794;
                if (profile.getAusgabeRichtung()) {
                    printHeigth = 794;
                    printWidth = 1123;

                }

                // get the image from the viewport
                image = new Image(viewer.getDisplay(), printWidth, viewer.getBounds().height);
                ImageLoader loader = new ImageLoader();

                gc = new GC(image);
                viewer.print(gc);
                gc.dispose();

                // prepare title data
                //Date date = new Date();
                //SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy  HH:mm");

                Patient patient = Patient.load(profile.getKontaktId());
                //String sTitle = "Gemeinschaftspraxis Brunnmatt Dr. Beat Knzi ";
                String sTitle;
                sTitle = profile.getOutputHeader() == null ? "No header configured!"
                        : profile.getOutputHeader();

                if (sTitle == null || sTitle.length() == 0) {
                    sTitle = "No header configured!";
                }
                sTitle = sTitle + " Datum: " + CstService.getReadableDateAndTime();

                // get option (paging to A4/ in one piece)
                int pdfOutputOption = 0;
                boolean onePage = true;

                PdfOptionsDialog dialog = new PdfOptionsDialog(baseComposite.getShell());
                dialog.create();

                if (dialog.open() == Window.OK) {
                    pdfOutputOption = dialog.getPdfOutputOption();
                    if (pdfOutputOption == PdfOptionsDialog.OPTION_ONE_PAGE) {
                        onePage = true;
                    } else {

                        onePage = false;
                    }
                }

                float docHeight = viewer.getBounds().height;
                docHeight = docHeight / 7.5f;

                float fontSize = 12f;

                if (docHeight < 360f) {
                    docHeight = 360f;
                }

                BufferedImage bimage = ImageUtils.convertToAWT(image.getImageData());

                // create an Itextt Image from AWT BufferedImage
                com.lowagie.text.Image itextImage = null;
                java.awt.Image awtImage = null;

                try {
                    awtImage = Toolkit.getDefaultToolkit().createImage(bimage.getSource());
                    itextImage = com.lowagie.text.Image.getInstance(awtImage, null);

                } catch (Exception e) {
                    log.error("Error on image loading: " + e.toString());
                    e.printStackTrace();
                }

                // only for debugging

                //loader.data = new ImageData[] { image.getImageData() };
                //loader.save("C:\\Users\\daniel\\tmp\\debug.png", SWT.IMAGE_PNG);

                Rectangle pagesize = new Rectangle(595f, itextImage.getHeight() * 0.75f);

                // is it a4 quer?
                if (profile.getAusgabeRichtung()) {
                    pagesize = new Rectangle(842f, itextImage.getHeight() * 0.75f);

                }

                //System.out.println("pagesize: " + pagesize.toString());

                Document document;
                if (onePage) {
                    document = new Document(pagesize);

                } else {
                    document = new Document(PageSize.A4);
                    if (profile.getAusgabeRichtung()) {
                        document = new Document(PageSize.A4.rotate());
                    }

                }

                document.addCreationDate();

                try {
                    // creation of the different writers
                    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(selected));

                    // various fonts
                    BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", true);
                    BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", true);
                    BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", true);

                    com.lowagie.text.Font fontHelv12 = new com.lowagie.text.Font(bf_helv, fontSize);

                    com.lowagie.text.Font fontTimes = new com.lowagie.text.Font(bf_times, fontSize);

                    fontTimes.setSize(fontSize);
                    fontTimes.setStyle(com.lowagie.text.Font.ITALIC);

                    Chunk chunkHeader = new Chunk(sTitle, FontFactory.getFont(FontFactory.HELVETICA, fontSize,
                            com.lowagie.text.Font.NORMAL, new java.awt.Color(255, 0, 0)));

                    com.lowagie.text.Phrase phraseHeader = new com.lowagie.text.Phrase(chunkHeader);

                    // headers and footers must be added before the document
                    // is opened

                    Chunk chunkFooter = new Chunk("Seite: ", FontFactory.getFont(FontFactory.HELVETICA,
                            fontSize, com.lowagie.text.Font.BOLD, new java.awt.Color(0, 0, 0)));

                    Phrase phraseFooter = new Phrase(chunkFooter);
                    phraseFooter.setFont(fontHelv12);

                    HeaderFooter footer = new HeaderFooter(phraseFooter, true);
                    footer.setBorder(Rectangle.NO_BORDER);
                    footer.setAlignment(Element.ALIGN_CENTER);

                    document.setFooter(footer);

                    Phrase headerPhrase = new Phrase(sTitle);
                    headerPhrase.setFont(fontTimes);

                    HeaderFooter header = new HeaderFooter(phraseHeader, false);
                    header.setBorder(Rectangle.BOTTOM);
                    header.setBorderWidth(0.5f);
                    header.setAlignment(Element.ALIGN_LEFT);
                    document.setHeader(header);

                    document.open();

                    //System.out.println("itext image w: " + itextImage.getWidth() + " h:" + itextImage.getHeight());

                    if (onePage) {

                        int scale = 66;
                        itextImage.scalePercent(scale);

                        document.add(itextImage);

                    } else {

                        BufferedImage[] imageChunks = ImageUtils.splitImageByHeigth(bimage, printHeigth);

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

                            com.lowagie.text.Image itextImage2 = com.lowagie.text.Image.getInstance(
                                    Toolkit.getDefaultToolkit().createImage(imageChunks[i].getSource()), null);

                            // width becomes typically 523 (595 - 72) for a4Hoch or 770 (842 - 72) for A4Quer
                            float imgWidth = document.getPageSize().getWidth() - document.leftMargin()
                                    - document.rightMargin();
                            float imgHeigth = itextImage.getHeight() * 0.75f;

                            itextImage2.setAbsolutePosition(30, 20);
                            int scale = 66;
                            itextImage2.scalePercent(scale);

                            document.add(itextImage2);
                            document.newPage();

                        }

                    }

                    // we're done!
                    document.close();

                    ///////////////////////////////

                } catch (Exception ex) {
                    log.error(ex.getMessage());
                    showMessage("Error while generating PDF", ex.getMessage());
                }

            } finally {
                if (image != null) {
                    image.dispose();
                }
                if (gc != null) {
                    gc.dispose();
                }
                /*
                image.dispose();
                gc.dispose();
                */
            }

        }
    };

    actionPdf.setText(Messages.Cst_Text_Save_as_pdf);
    actionPdf.setToolTipText(Messages.Cst_Text_Save_as_pdf);
    /*
     * actionPdf.setImageDescriptor(PlatformUI.getWorkbench() .getSharedImages()
     * .getImageDescriptor(ISharedImages.IMG_OBJ_FILE));
     */
    actionPdf.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PDF_PATH));

}

From source file:ch.gpb.elexis.kgexporter.pdf.PdfHandler.java

License:Open Source License

public static void createPdf(Patient patient, String filename, LinkedList<String[]> laborBlatt)
        throws IOException, DocumentException {

    BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", true);
    fontTimes = new com.lowagie.text.Font(bf_helv, 6);

    // step 1//from  www. ja va2 s  .  c  o  m
    Document document = new Document(PageSize.A4.rotate());

    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3

    document.setHeader(getHeader(
            patient.getVorname() + " " + patient.getName() + "   Geburtsdatum: " + patient.getGeburtsdatum()));

    document.open();

    document.add(new Chunk("")); // << this will do the trick. 

    // step 4
    document.add(createTable2(laborBlatt));
    // step 5
    document.close();
}

From source file:com.googlecode.openmpis.action.CaseAction.java

License:Open Source License

/**
 * Writes the cases to a PDF file./*from  w  w w.  j av a 2 s . co  m*/
 *
 * @param mapping       the ActionMapping used to select this instance
 * @param form          the optional ActionForm bean for this request
 * @param request       the HTTP Request we are processing
 * @param response      the HTTP Response we are processing
 * @return              the forwarding instance
 * @throws java.lang.Exception
 */
public ActionForward printCases(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    User currentUser = null;

    // Check if there exists a session
    if (request.getSession().getAttribute("currentuser") != null) {
        currentUser = (User) request.getSession().getAttribute("currentuser");
    }

    // Set the paper size and margins
    Document document = new Document(PageSize.LETTER.rotate(), 50, 50, 50, 50);

    // Create the PDF writer
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);

    // Add some meta information to the document
    document.addTitle("Case Statistics");
    document.addAuthor("OpenMPIS");
    document.addSubject("Statistics for All Cases");
    document.addKeywords("OpenMPIS, missing, found, unidentified");
    document.addProducer();
    document.addCreationDate();
    document.addCreator("OpenMPIS version " + Constants.VERSION);

    // Set the header
    String date = simpleDateFormat.format(System.currentTimeMillis());
    document.setHeader(new HeaderFooter(new Phrase("Statistics for cases as of " + date), false));

    // Set the footer
    HeaderFooter footer = new HeaderFooter(new Phrase("Page : "), true);
    footer.setAlignment(Element.ALIGN_CENTER);
    document.setFooter(footer);

    // Open the document for writing
    document.open();
    Table table = new Table(2);
    table.setBorderWidth(1);
    table.setBorderColor(new Color(0, 0, 0));
    table.setPadding(2);
    table.setSpacing(0);
    Paragraph paragraph = new Paragraph("Cases",
            FontFactory.getFont(FontFactory.HELVETICA, 24, Font.BOLD, new Color(0, 0, 0)));
    paragraph.setAlignment(Paragraph.ALIGN_CENTER);
    Cell cell = new Cell(paragraph);
    cell.setHeader(true);
    cell.setColspan(2);
    table.addCell(cell);
    table.endHeaders();
    table.addCell("Total On-going Cases");
    table.addCell("" + personService.countOngoing());
    table.addCell("\t\t\t\t\tMissing Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countMissing());
    table.addCell("\t\t\t\t\tFamily Abductions");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countFamilyAbduction());
    table.addCell("\t\t\t\t\tNon-Family Abductions");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countNonFamilyAbduction());
    table.addCell("\t\t\t\t\tRunaway Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countRunaway());
    table.addCell("\t\t\t\t\tUnknown");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countUnknown());
    table.addCell("\t\t\t\t\tFound Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + personService.countFound());
    table.addCell("\t\t\t\t\tAbandoned Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + personService.countAbandoned());
    table.addCell("\t\t\t\t\tThrowaway Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + personService.countThrowaway());
    table.addCell("\t\t\t\t\tUnidentified");
    table.addCell(
            "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + personService.countUnidentified());
    table.addCell("Total Solved Cases");
    table.addCell("" + personService.countSolved());
    table.addCell("\t\t\t\t\tMissing Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countSolvedMissing());
    table.addCell("\t\t\t\t\tFamily Abductions");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countSolvedFamilyAbduction());
    table.addCell("\t\t\t\t\tNon-Family Abductions");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countSolvedNonFamilyAbduction());
    table.addCell("\t\t\t\t\tRunaway Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countSolvedRunaway());
    table.addCell("\t\t\t\t\tUnknown");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countSolvedUnknown());
    table.addCell("\t\t\t\t\tFound Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + personService.countSolvedFound());
    table.addCell("\t\t\t\t\tAbandoned Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + personService.countSolvedAbandoned());
    table.addCell("\t\t\t\t\tThrowaway Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + personService.countSolvedThrowaway());
    table.addCell("\t\t\t\t\tUnidentified");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
            + personService.countSolvedUnidentified());
    table.addCell("Total Unsolved Cases");
    table.addCell("" + personService.countUnsolved());
    table.addCell("\t\t\t\t\tMissing Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countUnsolvedMissing());
    table.addCell("\t\t\t\t\tFamily Abductions");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countUnsolvedFamilyAbduction());
    table.addCell("\t\t\t\t\tNon-Family Abductions");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countUnsolvedNonFamilyAbduction());
    table.addCell("\t\t\t\t\tRunaway Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countUnsolvedRunaway());
    table.addCell("\t\t\t\t\tUnknown");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countUnsolvedUnknown());
    table.addCell("\t\t\t\t\tFound Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + personService.countUnsolvedFound());
    table.addCell("\t\t\t\t\tAbandoned Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + personService.countUnsolvedAbandoned());
    table.addCell("\t\t\t\t\tThrowaway Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + personService.countUnsolvedThrowaway());
    table.addCell("\t\t\t\t\tUnidentified");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
            + personService.countUnsolvedUnidentified());
    table.addCell("Total Cases");
    table.addCell("" + personService.countAllPersons());
    table.addCell("\t\t\t\t\tTotal Missing Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + personService.countAllMissing());
    table.addCell("\t\t\t\t\tTotal Found Persons");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + personService.countAllFound());
    table.addCell("\t\t\t\t\tTotal Unidentified Persons");
    table.addCell(
            "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + personService.countUnidentified());
    table.addCell("Total Relatives");
    table.addCell("" + relativeService.countAllRelatives());
    table.addCell("Total Abductors");
    table.addCell("" + abductorService.countAllAbductors());
    document.add(table);
    if (currentUser != null) {
        // List ongoing cases
        document.setHeader(new HeaderFooter(new Phrase("List of ongoing cases as of " + date), false));
        document.newPage();
        float[] widths = { 0.05f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.05f, 0.15f, 0.1f, 0.1f, 0.05f };
        PdfPTable pdfptable = new PdfPTable(widths);
        pdfptable.setWidthPercentage(100);
        pdfptable.addCell(new Phrase("ID", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Last Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("First Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Nickname", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Middle Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Case Type", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Status", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Photo", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Relative", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Abductor", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Investigator", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        List<Person> personList = personService.listOngoing();
        if (personList != null) {
            for (Person person : personList) {
                // Process the photo
                String tokens[] = person.getPhoto().split("\\/");
                String defaultPhotoBasename = "";
                for (int i = 0; i < tokens.length - 1; i++) {
                    defaultPhotoBasename += tokens[i] + File.separator;
                }
                defaultPhotoBasename += tokens[tokens.length - 1];
                String absoluteDefaultPhotoFilename = getServlet().getServletContext().getRealPath("/")
                        + defaultPhotoBasename;
                Image image = Image.getInstance(absoluteDefaultPhotoFilename);
                image.scaleAbsolute(50, 75);
                image.setAlignment(Image.ALIGN_CENTER);

                pdfptable.addCell(
                        new Phrase("" + person.getId(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(person.getLastName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(person.getFirstName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(person.getNickname(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(person.getMiddleName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("type." + person.getType()),
                        FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(getResources(request).getMessage("status.case." + person.getStatus()),
                                FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(image);
                String relativeName = "";
                if (person.getRelativeId() != null) {
                    Relative relative = relativeService.getRelativeById(person.getRelativeId());
                    relativeName = relative.getFirstName() + " " + relative.getLastName();
                }
                pdfptable.addCell(new Phrase(relativeName, FontFactory.getFont(FontFactory.HELVETICA, 8)));
                String abductorName = "";
                if (person.getAbductorId() != null) {
                    Abductor abductor = abductorService.getAbductorById(person.getAbductorId());
                    abductorName = abductor.getFirstName() + " " + abductor.getLastName();
                }
                pdfptable.addCell(new Phrase(abductorName, FontFactory.getFont(FontFactory.HELVETICA, 8)));
                String investigatorUsername = "";
                if (person.getInvestigatorId() != null) {
                    User investigator = userService.getUserById(person.getInvestigatorId());
                    investigatorUsername = investigator.getUsername();
                }
                pdfptable.addCell(
                        new Phrase(investigatorUsername, FontFactory.getFont(FontFactory.HELVETICA, 8)));
            }
        }
        document.add(pdfptable);

        // List solved cases
        document.setHeader(new HeaderFooter(new Phrase("List of solved cases as of " + date), false));
        document.newPage();
        pdfptable = new PdfPTable(widths);
        pdfptable.setWidthPercentage(100);
        pdfptable.addCell(new Phrase("ID", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Last Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("First Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Nickname", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Middle Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Case Type", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Status", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Photo", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Relative", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Abductor", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Investigator", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        personList = personService.listSolved();
        if (personList != null) {
            for (Person person : personList) {
                // Process the photo
                String tokens[] = person.getPhoto().split("\\/");
                String defaultPhotoBasename = "";
                for (int i = 0; i < tokens.length - 1; i++) {
                    defaultPhotoBasename += tokens[i] + File.separator;
                }
                defaultPhotoBasename += tokens[tokens.length - 1];
                String absoluteDefaultPhotoFilename = getServlet().getServletContext().getRealPath("/")
                        + defaultPhotoBasename;
                Image image = Image.getInstance(absoluteDefaultPhotoFilename);
                image.scaleAbsolute(50, 75);
                image.setAlignment(Image.ALIGN_CENTER);

                pdfptable.addCell(
                        new Phrase("" + person.getId(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(person.getLastName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(person.getFirstName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(person.getNickname(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(person.getMiddleName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("type." + person.getType()),
                        FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(getResources(request).getMessage("status.case." + person.getStatus()),
                                FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(image);
                String relativeName = "";
                if (person.getRelativeId() != null) {
                    Relative relative = relativeService.getRelativeById(person.getRelativeId());
                    relativeName = relative.getFirstName() + " " + relative.getLastName();
                }
                pdfptable.addCell(new Phrase(relativeName, FontFactory.getFont(FontFactory.HELVETICA, 8)));
                String abductorName = "";
                if (person.getAbductorId() != null) {
                    Abductor abductor = abductorService.getAbductorById(person.getAbductorId());
                    abductorName = abductor.getFirstName() + " " + abductor.getLastName();
                }
                pdfptable.addCell(new Phrase(abductorName, FontFactory.getFont(FontFactory.HELVETICA, 8)));
                String investigatorUsername = "";
                if (person.getInvestigatorId() != null) {
                    User investigator = userService.getUserById(person.getInvestigatorId());
                    investigatorUsername = investigator.getUsername();
                }
                pdfptable.addCell(
                        new Phrase(investigatorUsername, FontFactory.getFont(FontFactory.HELVETICA, 8)));
            }
        }
        document.add(pdfptable);

        // List unsolved cases
        document.setHeader(new HeaderFooter(new Phrase("List of unsolved cases as of " + date), false));
        document.newPage();
        pdfptable = new PdfPTable(widths);
        pdfptable.setWidthPercentage(100);
        pdfptable.addCell(new Phrase("ID", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Last Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("First Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Nickname", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Middle Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Case Type", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Status", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Photo", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Relative", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Abductor", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        pdfptable.addCell(new Phrase("Investigator", FontFactory.getFont(FontFactory.HELVETICA, 12)));
        personList = personService.listUnsolved();
        if (personList != null) {
            for (Person person : personList) {
                // Process the photo
                String tokens[] = person.getPhoto().split("\\/");
                String defaultPhotoBasename = "";
                for (int i = 0; i < tokens.length - 1; i++) {
                    defaultPhotoBasename += tokens[i] + File.separator;
                }
                defaultPhotoBasename += tokens[tokens.length - 1];
                String absoluteDefaultPhotoFilename = getServlet().getServletContext().getRealPath("/")
                        + defaultPhotoBasename;
                Image image = Image.getInstance(absoluteDefaultPhotoFilename);
                image.scaleAbsolute(50, 75);
                image.setAlignment(Image.ALIGN_CENTER);

                pdfptable.addCell(
                        new Phrase("" + person.getId(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(person.getLastName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(person.getFirstName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(person.getNickname(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(person.getMiddleName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("type." + person.getType()),
                        FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(getResources(request).getMessage("status.case." + person.getStatus()),
                                FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(image);
                String relativeName = "";
                if (person.getRelativeId() != null) {
                    Relative relative = relativeService.getRelativeById(person.getRelativeId());
                    relativeName = relative.getFirstName() + " " + relative.getLastName();
                }
                pdfptable.addCell(new Phrase(relativeName, FontFactory.getFont(FontFactory.HELVETICA, 8)));
                String abductorName = "";
                if (person.getAbductorId() != null) {
                    Abductor abductor = abductorService.getAbductorById(person.getAbductorId());
                    abductorName = abductor.getFirstName() + " " + abductor.getLastName();
                }
                pdfptable.addCell(new Phrase(abductorName, FontFactory.getFont(FontFactory.HELVETICA, 8)));
                String investigatorUsername = "";
                if (person.getInvestigatorId() != null) {
                    User investigator = userService.getUserById(person.getInvestigatorId());
                    investigatorUsername = investigator.getUsername();
                }
                pdfptable.addCell(
                        new Phrase(investigatorUsername, FontFactory.getFont(FontFactory.HELVETICA, 8)));
            }
        }
        document.add(pdfptable);
    }
    document.close();

    // Set the response to return the poster (PDF file)
    response.setContentType("application/pdf");
    response.setContentLength(baos.size());
    response.setHeader("Content-disposition", "attachment; filename=Case_Statistics.pdf");

    // Close the output stream
    baos.writeTo(response.getOutputStream());
    response.getOutputStream().flush();

    return null;
}

From source file:com.googlecode.openmpis.action.ReportAction.java

License:Open Source License

/**
 * Prints the reports.//from ww w . ja v  a2  s  .c o  m
 * This is the print report action called from the Struts framework.
 *
 * @param mapping       the ActionMapping used to select this instance
 * @param form          the optional ActionForm bean for this request
 * @param request       the HTTP Request we are processing
 * @param response      the HTTP Response we are processing
 * @return              the forwarding instance
 * @throws java.lang.Exception
 */
public ActionForward printReport(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    User currentUser = null;

    // Check if there exists a session
    if (request.getSession().getAttribute("currentuser") == null) {
        return mapping.findForward(Constants.EXPIRED);
    } else {
        currentUser = (User) request.getSession().getAttribute("currentuser");
    }

    // Check if current user is authorized
    if ((currentUser.getGroupId() == 1) || (currentUser.getGroupId() == 2)) {
        // Retrieve person ID
        try {
            int personId = Integer.parseInt(request.getParameter("personid"));
            Person person = personService.getPersonById(personId);

            // Process the photo
            String tokens[] = person.getPhoto().split("\\/");
            String defaultPhotoBasename = "";
            for (int i = 0; i < tokens.length - 1; i++) {
                defaultPhotoBasename += tokens[i] + File.separator;
            }
            defaultPhotoBasename += tokens[tokens.length - 1];
            String absoluteDefaultPhotoFilename = getServlet().getServletContext().getRealPath("/")
                    + defaultPhotoBasename;

            // Set the paper size and margins
            Document document = new Document(PageSize.LETTER, 50, 50, 50, 50);

            // Create the PDF writer
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);

            // Add some meta information to the document
            document.addTitle("Progress Report");
            document.addAuthor("OpenMPIS");
            document.addSubject("Progress Report");
            document.addKeywords("OpenMPIS, missing, found, unidentified");
            document.addProducer();
            document.addCreationDate();
            document.addCreator("OpenMPIS version " + Constants.VERSION);

            // Set the header
            String date = simpleDateFormat.format(System.currentTimeMillis());
            document.setHeader(new HeaderFooter(new Phrase("Report for " + person.getFirstName() + " \""
                    + person.getNickname() + "\" " + person.getLastName() + " as of " + date), false));

            // Set the footer
            HeaderFooter footer = new HeaderFooter(new Phrase("Page : "), true);
            footer.setAlignment(Element.ALIGN_CENTER);
            document.setFooter(footer);

            // Open the document for writing
            document.open();
            // Print the information on person
            // Add the banner
            if (person.getType() > 4) {
                Paragraph foundParagraph = new Paragraph("F O U N D",
                        FontFactory.getFont(FontFactory.HELVETICA_BOLD, 36, Font.BOLD, new Color(255, 0, 0)));
                foundParagraph.setAlignment(Paragraph.ALIGN_CENTER);
                document.add(foundParagraph);
            } else {
                Paragraph missingParagraph = new Paragraph("M I S S I N G",
                        FontFactory.getFont(FontFactory.HELVETICA_BOLD, 36, Font.BOLD, new Color(255, 0, 0)));
                missingParagraph.setAlignment(Paragraph.ALIGN_CENTER);
                document.add(missingParagraph);
            }
            // Add date missing or found
            Paragraph blackParagraph = new Paragraph(
                    getResources(request).getMessage("month." + person.getMonthMissingOrFound()) + " "
                            + person.getDayMissingOrFound() + ", " + person.getYearMissingOrFound(),
                    FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD, new Color(0, 0, 0)));
            blackParagraph.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(blackParagraph);
            // Add missing from location
            if (person.getType() < 5) {
                blackParagraph = new Paragraph(
                        person.getMissingFromCity() + ", " + person.getMissingFromProvince(),
                        FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD, new Color(0, 0, 0)));
                blackParagraph.setAlignment(Paragraph.ALIGN_CENTER);
                document.add(blackParagraph);
            }
            // Add name
            Paragraph redParagraph;
            if (!person.getNickname().isEmpty()) {
                redParagraph = new Paragraph(
                        person.getFirstName() + " \"" + person.getNickname() + "\" " + person.getLastName(),
                        FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(255, 0, 0)));
            } else {
                redParagraph = new Paragraph(person.getFirstName() + " " + person.getLastName(),
                        FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(255, 0, 0)));
            }
            redParagraph.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(redParagraph);
            // Add the photo
            Image image = Image.getInstance(absoluteDefaultPhotoFilename);
            image.scaleAbsolute(200, 300);
            image.setAlignment(Image.ALIGN_CENTER);
            document.add(image);
            // Add description
            redParagraph = new Paragraph("Description",
                    FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(255, 0, 0)));
            redParagraph.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(redParagraph);
            float[] widths = { 0.5f, 0.5f };
            PdfPTable pdfptable = new PdfPTable(widths);
            pdfptable.setWidthPercentage(100);
            if (person.getType() < 5) {
                pdfptable
                        .addCell(
                                new Phrase(
                                        getResources(request).getMessage("label.date.birth") + ": "
                                                + getResources(request)
                                                        .getMessage("month." + person.getBirthMonth())
                                                + " " + person.getBirthDay() + ", " + person.getBirthYear(),
                                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
                pdfptable.addCell(new Phrase(
                        getResources(request).getMessage("label.address.city") + ": " + person.getCity(),
                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
            }
            pdfptable.addCell(new Phrase(
                    getResources(request).getMessage("label.sex") + ": "
                            + getResources(request).getMessage("sex." + person.getSex()),
                    FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable
                    .addCell(
                            new Phrase(
                                    getResources(request).getMessage("label.color.hair") + ": "
                                            + getResources(request)
                                                    .getMessage("color.hair." + person.getHairColor()),
                                    FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable
                    .addCell(new Phrase(
                            getResources(request).getMessage("label.height") + ": " + person.getFeet() + "' "
                                    + person.getInches() + "\"",
                            FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable
                    .addCell(
                            new Phrase(
                                    getResources(request).getMessage("label.color.eye") + ": "
                                            + getResources(request)
                                                    .getMessage("color.eye." + person.getEyeColor()),
                                    FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase(
                    getResources(request).getMessage("label.weight") + ": " + person.getWeight() + " "
                            + getResources(request).getMessage("label.weight.lbs"),
                    FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase(
                    getResources(request).getMessage("label.race") + ": "
                            + getResources(request).getMessage("race." + person.getRace()),
                    FontFactory.getFont(FontFactory.HELVETICA, 12)));
            document.add(pdfptable);

            // Print information on relative
            Relative relative = relativeService.getRelativeById(person.getRelativeId());

            document.newPage();
            document.add(new Paragraph(getResources(request).getMessage("label.relative.name") + ": "
                    + relative.getFirstName() + " " + relative.getLastName()));
            document.add(new Paragraph(getResources(request).getMessage("label.relation") + ": "
                    + getResources(request).getMessage("relation." + person.getRelationToRelative())));
            document.add(new Paragraph(getResources(request).getMessage("label.address") + ": "
                    + relative.getStreet() + ", " + relative.getCity() + ", " + relative.getProvince()));
            document.add(new Paragraph(
                    getResources(request).getMessage("label.number") + ": " + relative.getNumber()));
            document.add(new Paragraph(
                    getResources(request).getMessage("label.email") + ": " + relative.getEmail()));

            // Print information on abductor
            if (person.getAbductorId() != null) {
                Abductor abductor = abductorService.getAbductorById(person.getAbductorId());

                document.newPage();
                document.add(new Paragraph(getResources(request).getMessage("label.abductor.name") + ": "
                        + abductor.getFirstName() + " " + abductor.getLastName()));
            }

            // Print sightings
            if ((currentUser.getGroupId() == 1) || (currentUser.getGroupId() == 2)) {
                document.setHeader(new HeaderFooter(new Phrase("List of sightings as of " + date), false));
                document.newPage();
                float sightingsWidths[] = { 0.1f, 0.1f, 0.1f, 0.3f, 0.1f, 0.1f, 0.1f, 0.1f };
                pdfptable = new PdfPTable(sightingsWidths);
                pdfptable.setWidthPercentage(100);
                pdfptable.addCell(new Phrase(getResources(request).getMessage("label.id"),
                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("label.date.sent"),
                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("label.subject"),
                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("label.message"),
                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("label.lastname"),
                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("label.firstname"),
                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("label.email"),
                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("label.ipaddress"),
                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
                List<Message> sightingList = messageService.listAllSightingsForPerson(personId);
                for (Message sighting : sightingList) {
                    pdfptable.addCell(
                            new Phrase("" + sighting.getId(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                    pdfptable.addCell(
                            new Phrase(sighting.getDate(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                    pdfptable.addCell(
                            new Phrase(sighting.getSubject(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                    pdfptable.addCell(
                            new Phrase(sighting.getMessage(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                    pdfptable.addCell(
                            new Phrase(sighting.getLastName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                    pdfptable.addCell(
                            new Phrase(sighting.getFirstName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                    pdfptable.addCell(
                            new Phrase(sighting.getEmail(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                    pdfptable.addCell(
                            new Phrase(sighting.getIpAddress(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                }
                document.add(pdfptable);
            }

            // Print progress reports
            if ((currentUser.getGroupId() == 1) || (currentUser.getGroupId() == 2)) {
                document.setHeader(
                        new HeaderFooter(new Phrase("List of progress reports as of " + date), false));
                document.newPage();
                float reportsWidths[] = { 0.1f, 0.1f, 0.3f };
                pdfptable = new PdfPTable(reportsWidths);
                pdfptable.setWidthPercentage(100);
                pdfptable.addCell(new Phrase(getResources(request).getMessage("label.id"),
                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("label.date.reported"),
                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("label.report"),
                        FontFactory.getFont(FontFactory.HELVETICA, 12)));
                List<Report> reportList = reportService.listAllReportsForPerson(personId);
                for (Report report : reportList) {
                    pdfptable.addCell(
                            new Phrase("" + report.getId(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                    pdfptable.addCell(
                            new Phrase(report.getDate(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                    pdfptable.addCell(
                            new Phrase(report.getReport(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                }
                document.add(pdfptable);
            }
            document.close();

            // Set the response to return the poster (PDF file)
            response.setContentType("application/pdf");
            response.setContentLength(baos.size());
            response.setHeader("Content-disposition", "attachment; filename=Report.pdf");

            // Close the output stream
            baos.writeTo(response.getOutputStream());
            response.getOutputStream().flush();

            return null;
        } catch (NumberFormatException nfe) {
            return mapping.findForward(Constants.LIST_PERSON);
        } catch (NullPointerException npe) {
            return mapping.findForward(Constants.LIST_PERSON);
        }
    } else {
        return mapping.findForward(Constants.UNAUTHORIZED);
    }
}

From source file:com.googlecode.openmpis.action.UserAction.java

License:Open Source License

/**
 * Writes the users to a PDF file./*from  w  ww .  j a  v  a  2  s.  c  o  m*/
 *
 * @param mapping       the ActionMapping used to select this instance
 * @param form          the optional ActionForm bean for this request
 * @param request       the HTTP Request we are processing
 * @param response      the HTTP Response we are processing
 * @return              the forwarding instance
 * @throws java.lang.Exception
 */
public ActionForward printUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    User currentUser = null;

    // Check if there exists a session
    if (request.getSession().getAttribute("currentuser") != null) {
        currentUser = (User) request.getSession().getAttribute("currentuser");
    }

    // Set the paper size and margins
    Document document = new Document(PageSize.LETTER.rotate(), 50, 50, 50, 50);

    // Create the PDF writer
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);

    // Add some meta information to the document
    document.addTitle("Case Statistics");
    document.addAuthor("OpenMPIS");
    document.addSubject("Statistics for All Cases");
    document.addKeywords("OpenMPIS, missing, found, unidentified");
    document.addProducer();
    document.addCreationDate();
    document.addCreator("OpenMPIS version " + Constants.VERSION);

    // Set the header
    String date = simpleDateFormat.format(System.currentTimeMillis());
    document.setHeader(new HeaderFooter(new Phrase("List of users as of " + date), false));

    // Set the footer
    HeaderFooter footer = new HeaderFooter(new Phrase("Page : "), true);
    footer.setAlignment(Element.ALIGN_CENTER);
    document.setFooter(footer);

    // Open the document for writing
    document.open();
    Table table = new Table(2);
    table.setBorderWidth(1);
    table.setPadding(2);
    table.setSpacing(0);
    Paragraph paragraph = new Paragraph("Users", FontFactory.getFont(FontFactory.HELVETICA, 24, Font.BOLD));
    paragraph.setAlignment(Paragraph.ALIGN_CENTER);
    Cell cell = new Cell(paragraph);
    cell.setHeader(true);
    cell.setColspan(2);
    table.addCell(cell);
    table.endHeaders();
    table.addCell("Total Administrators");
    table.addCell("" + userService.countAdministrators());
    table.addCell("\t\t\t\t\tActive Administrators");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + userService.countActiveAdministrators());
    table.addCell("\t\t\t\t\tSuspended Administrators");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + userService.countSuspendedAdministrators());
    table.addCell("Total Encoders");
    table.addCell("" + userService.countEncoders());
    table.addCell("\t\t\t\t\tActive Encoders");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + userService.countActiveEncoders());
    table.addCell("\t\t\t\t\tSuspended Encoders");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + userService.countSuspendedEncoders());
    table.addCell("Total Investigators");
    table.addCell("" + userService.countInvestigators());
    table.addCell("\t\t\t\t\tActive Investigators");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + userService.countActiveInvestigators());
    table.addCell("\t\t\t\t\tSuspended Investigators");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + userService.countSuspendedInvestigators());
    table.addCell("Total Users");
    table.addCell("" + userService.countAllUsers());
    table.addCell("\t\t\t\t\tTotal Active Users");
    table.addCell("\t\t\t\t\t\t\t\t\t\t" + userService.countActiveUsers());
    table.addCell("\t\t\t\t\tTotal Suspended Users");
    table.addCell("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + userService.countSuspendedUsers());
    document.add(table);
    if (currentUser != null) {
        if ((currentUser.getGroupId() == 0) || (currentUser.getGroupId() == 1)) {
            // List administrators
            document.setHeader(new HeaderFooter(new Phrase("List of administrators as of " + date), false));
            document.newPage();
            float[] widths = { 0.03f, 0.07f, 0.1f, 0.1f, 0.1f, 0.1f, 0.2f, 0.05f };
            PdfPTable pdfptable = new PdfPTable(widths);
            pdfptable.setWidthPercentage(100);
            pdfptable.addCell(new Phrase("ID", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Group", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Last Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("First Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Agency", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Designation", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("E-mail Address", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Status", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            List<User> administratorList = userService.listAdministrators();
            for (User administrator : administratorList) {
                pdfptable.addCell(
                        new Phrase("" + administrator.getId(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(getResources(request).getMessage("group." + administrator.getGroupId()),
                                FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(administrator.getLastName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(new Phrase(administrator.getFirstName(),
                        FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(administrator.getAgency(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(new Phrase(administrator.getDesignation(),
                        FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(administrator.getEmail(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(getResources(request).getMessage("status.user." + administrator.getStatus()),
                                FontFactory.getFont(FontFactory.HELVETICA, 8)));
            }
            document.add(pdfptable);

            // List encoders
            document.setHeader(new HeaderFooter(new Phrase("List of encoders as of " + date), false));
            document.newPage();
            pdfptable = new PdfPTable(widths);
            pdfptable.setWidthPercentage(100);
            pdfptable.addCell(new Phrase("ID", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Group", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Last Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("First Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Agency", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Designation", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("E-mail Address", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Status", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            List<User> encoderList = userService.listEncoders();
            for (User encoder : encoderList) {
                pdfptable.addCell(
                        new Phrase("" + encoder.getId(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(new Phrase(getResources(request).getMessage("group." + encoder.getGroupId()),
                        FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(encoder.getLastName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(encoder.getFirstName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(encoder.getAgency(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(encoder.getDesignation(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable
                        .addCell(new Phrase(encoder.getEmail(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(getResources(request).getMessage("status.user." + encoder.getStatus()),
                                FontFactory.getFont(FontFactory.HELVETICA, 8)));
            }
            document.add(pdfptable);

            // List investigators
            document.setHeader(new HeaderFooter(new Phrase("List of investigators as of " + date), false));
            document.newPage();
            pdfptable = new PdfPTable(widths);
            pdfptable.setWidthPercentage(100);
            pdfptable.addCell(new Phrase("ID", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Group", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Last Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("First Name", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Agency", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Designation", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("E-mail Address", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            pdfptable.addCell(new Phrase("Status", FontFactory.getFont(FontFactory.HELVETICA, 12)));
            List<User> investigatorList = userService.listInvestigators();
            for (User investigator : investigatorList) {
                pdfptable.addCell(
                        new Phrase("" + investigator.getId(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(getResources(request).getMessage("group." + investigator.getGroupId()),
                                FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(investigator.getLastName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(investigator.getFirstName(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(investigator.getAgency(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(new Phrase(investigator.getDesignation(),
                        FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(investigator.getEmail(), FontFactory.getFont(FontFactory.HELVETICA, 8)));
                pdfptable.addCell(
                        new Phrase(getResources(request).getMessage("status.user." + investigator.getStatus()),
                                FontFactory.getFont(FontFactory.HELVETICA, 8)));
            }
            document.add(pdfptable);
        }
    }
    document.close();

    // Set the response to return the poster (PDF file)
    response.setContentType("application/pdf");
    response.setContentLength(baos.size());
    response.setHeader("Content-disposition", "attachment; filename=User_Statistics.pdf");

    // Close the output stream
    baos.writeTo(response.getOutputStream());
    response.getOutputStream().flush();

    return null;
}

From source file:com.krawler.esp.servlets.ExportMPXServlet.java

License:Open Source License

public static void setHeaderFooter(Document doc, String headerText) {
    HeaderFooter footer = new HeaderFooter(
            new Phrase(" ", FontFactory.getFont("Helvetica", 8, Font.NORMAL, Color.BLACK)), true);
    footer.setBorderWidth(0);//from   w  ww.  j a  v a  2  s  .c  o  m
    footer.setBorderWidthTop(1);
    footer.setAlignment(HeaderFooter.ALIGN_RIGHT);
    doc.setFooter(footer);
    HeaderFooter header = new HeaderFooter(
            new Phrase(headerText, FontFactory.getFont("Helvetica", 14, Font.BOLD, Color.BLACK)), false);
    doc.setHeader(header);
}

From source file:com.krawler.esp.servlets.ExportServlet.java

License:Open Source License

public static void setHeaderFooter(Document doc, String headerText) {
    HeaderFooter footer = new HeaderFooter(
            new Phrase("  ", FontFactory.getFont("Helvetica", 8, Font.NORMAL, Color.BLACK)), true);
    footer.setBorderWidth(0);/*w  ww. j a v a2s. c o m*/
    footer.setBorderWidthTop(1);
    footer.setAlignment(HeaderFooter.ALIGN_RIGHT);
    doc.setFooter(footer);
    HeaderFooter header = new HeaderFooter(
            new Phrase(headerText, FontFactory.getFont("Helvetica", 14, Font.BOLD, Color.BLACK)), false);
    doc.setHeader(header);
}

From source file:com.krawler.spring.exportFunctionality.exportDAOImpl.java

License:Open Source License

public void setHeaderFooter(Document doc, String headerText) {
    HeaderFooter footer = new HeaderFooter(
            new Phrase("  ", FontFactory.getFont("Helvetica", 8, Font.NORMAL, Color.BLACK)), true);
    footer.setBorderWidth(0);/*from w  w  w .ja v a2s  .c om*/
    footer.setBorderWidthTop(1);
    footer.setAlignment(HeaderFooter.ALIGN_RIGHT);
    doc.setFooter(footer);
    HeaderFooter header = new HeaderFooter(
            new Phrase(headerText, FontFactory.getFont("Helvetica", 14, Font.BOLD, Color.BLACK)), false);
    doc.setHeader(header);
}

From source file:com.orange.atk.compModel.PDFGenerator.java

License:Apache License

/**
 * @see com.orange.atk.results.logger.documentGenerator.DocumentGenerator#dumpInStream(boolean, interpreter.logger.DocumentLogger)
 *//*from  w w w  .j a v  a  2  s. c  om*/

public void dumpInStream(boolean isParseErrorHappened, /*DocumentLogger dl,*/ org.w3c.dom.Document xmlDoc,
        Model model3) {
    long endTime = new Date().getTime();
    // step 1: creation of a document-object
    Document document = new Document();
    PdfWriter writer = null;

    // step 2:
    // we create a writer that listens to the document
    // and directs a PDF-stream to the outputStream
    try {
        writer = PdfWriter.getInstance(document, outputStream);
    } catch (DocumentException e1) {
        e1.printStackTrace();
        return;
    }
    writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
    // step 3: we open the document
    document.open();
    document.addTitle("REPORT");
    document.addCreationDate();

    HeaderFooter headerPage = new HeaderFooter(new Phrase("ScreenShot report"), false);
    HeaderFooter footerPage = new HeaderFooter(new Phrase(" - "), new Phrase(" - "));
    headerPage.setAlignment(Element.ALIGN_CENTER);
    footerPage.setAlignment(Element.ALIGN_CENTER);
    document.setHeader(headerPage);
    document.setFooter(footerPage);

    // Chapter 1 : Summary
    // Section 1 : Informations

    Chunk c = new Chunk("Summary");
    c.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c.setFont(FONT_PAR_TITLE);

    Paragraph title1 = new Paragraph(c);
    title1.setAlignment("CENTER");
    title1.setLeading(20);
    Chapter chapter1 = new Chapter(title1, 1);
    chapter1.setNumberDepth(0);

    Paragraph title11 = new Paragraph("Informations");
    Section section1 = chapter1.addSection(title11);
    Paragraph pSum = new Paragraph();
    pSum.add("Author : " + author);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Group : " + group);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Script : " + script);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Reference directory: " + model3.getRefDirectory());
    pSum.add(Chunk.NEWLINE);
    pSum.add("Test directory: " + model3.getTestDirectory());
    pSum.add(Chunk.NEWLINE);
    SimpleDateFormat formatter = new SimpleDateFormat("MMMMM dd, yyyy - hh:mm aaa");
    String dateString = formatter.format(endTime);
    pSum.add("Date : " + dateString);
    pSum.add(Chunk.NEWLINE);
    pSum.add(Chunk.NEWLINE);
    if (model3.getNbFail() > 0) {
        pSum.add(model3.getNbFail() + "/" + model3.getNbImages() + " images didn't succeed the test.");
    } else {
        pSum.add("All images (" + model3.getNbImages() + ") have succeed this comparaison.");
    }
    pSum.add(Chunk.NEWLINE);
    pSum.setIndentationLeft(20);
    section1.add(pSum);
    section1.add(new Paragraph(Chunk.NEXTPAGE));

    try {
        document.add(chapter1);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.newPage();

    if (isParseErrorHappened) {
        document.close();
        return;
    }

    // Add generated pictures
    Chunk c3 = new Chunk("ScreenShots");
    c3.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c3.setFont(FONT_PAR_TITLE);
    Paragraph p3 = new Paragraph(c3);
    p3.setAlignment("CENTER");
    p3.setLeading(20);
    Chapter chapter3 = new Chapter(p3, 1);
    chapter3.setNumberDepth(0);

    NodeList imgs = xmlDoc.getElementsByTagName("img");
    for (int i = 0; i < imgs.getLength(); i++) {
        org.w3c.dom.Element eImg = (org.w3c.dom.Element) imgs.item(i);
        if (eImg.getElementsByTagName("Pass").item(0).getTextContent().equals(Model.FAIL)) {

            org.w3c.dom.Element eRef = (org.w3c.dom.Element) eImg.getElementsByTagName("Ref").item(0);
            org.w3c.dom.Element eTest = (org.w3c.dom.Element) eImg.getElementsByTagName("Test").item(0);
            Paragraph pScreen = new Paragraph(eTest.getAttributes().getNamedItem("name").getNodeValue() + " "
                    + eImg.getElementsByTagName("Pass").item(0).getTextContent());
            Section section31 = chapter3.addSection(pScreen);
            PdfPTable scTable = null;
            scTable = new PdfPTable(2);
            scTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            scTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            scTable.getDefaultCell().setPadding(5);
            if (new File(eRef.getTextContent()).exists()) {
                Image refImg;
                try {
                    refImg = Image.getInstance(eRef.getTextContent());
                    refImg.scaleToFit(310, 260);
                    refImg.setAlignment(Element.ALIGN_BASELINE);
                    scTable.addCell(refImg);
                } catch (BadElementException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (DOMException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (new File(eTest.getTextContent()).exists()) {
                Image testImg;
                try {
                    BufferedImage bi = ImageIO.read(new File(eTest.getTextContent()));
                    Graphics2D g2d = (Graphics2D) bi.getGraphics();
                    g2d.setStroke(new BasicStroke(1.5f));
                    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));

                    Boolean2D dif = model3.getCouplesComparaison().get(i).getDifWithMask();
                    //               if (squarable){
                    g2d.setColor(Color.red);
                    int w = bi.getWidth();
                    int h = bi.getHeight();
                    //TODO: Gurvan, Maybe we need to have the list of masks in the report?
                    Mask mask = model3.getCouplesComparaison().get(i).getMaskSum();
                    //g2d.drawRect(0, 0, mask.getWidth()*2*sampleWidth, mask.getHeight()*2*sampleHeight);
                    for (int x = 0; x < mask.getWidth(); x++) {

                        for (int y = 0; y < mask.getHeight(); y++) {

                            if (mask.getCell(x, y)) {
                                g2d.setColor(Color.blue);
                                ////Logger.getLogger(this.getClass() ).debug("grise");
                                g2d.fillRect(x * 2 * Mask.getCELL_HALF_SIZE(), y * 2 * Mask.getCELL_HALF_SIZE(),
                                        2 * Mask.getCELL_HALF_SIZE(), 2 * Mask.getCELL_HALF_SIZE());
                            }

                            if (!dif.get(x, y)) {
                                g2d.setColor(Color.green);
                                g2d.fillRect(x * 2 * Mask.getCELL_HALF_SIZE(), y * 2 * Mask.getCELL_HALF_SIZE(),
                                        2 * Mask.getCELL_HALF_SIZE(), 2 * Mask.getCELL_HALF_SIZE());
                            }
                        }
                    }
                    testImg = Image.getInstance(bi, null);
                    testImg.scaleToFit(310, 260);
                    testImg.setAlignment(Element.ALIGN_BASELINE);
                    scTable.addCell(testImg);
                    section31.add(Chunk.NEWLINE);
                    section31.add(scTable);
                } catch (BadElementException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (DOMException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            section31.add(new Paragraph("Reference screenshot description : "
                    + eImg.getElementsByTagName("RefDescription").item(0).getTextContent()));
            section31.add(Chunk.NEWLINE);

            section31
                    .add(new Paragraph("Mask : " + eImg.getElementsByTagName("Mask").item(0).getTextContent()));
            section31.add(Chunk.NEWLINE);

            section31.add(new Paragraph(
                    "Comment : " + eImg.getElementsByTagName("Comment").item(0).getTextContent()));
            section31.add(new Paragraph(Chunk.NEXTPAGE));

        }
    }
    try {
        document.add(chapter3);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.newPage();

    // step 5: we close the document
    document.close();
}