Example usage for com.itextpdf.text Image getInstance

List of usage examples for com.itextpdf.text Image getInstance

Introduction

In this page you can find the example usage for com.itextpdf.text Image getInstance.

Prototype

public static Image getInstance(final Image image) 

Source Link

Document

gets an instance of an Image

Usage

From source file:org.apache.jmeter.visualizers.CreateReport.java

License:Apache License

/**
 * Creates a table; widths are set with setWidths().
 * @return a PdfPTable// w  w  w . j av  a2  s . com
 * @throws DocumentException
 */

//createGraphs("Average Response Time of samples for each Request","Average(ms)",2);
public Image createGraphs(String chartName, String colName, int colNo) {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (int i = 0; i < model.getRowCount(); i++)
        dataset.setValue((long) model.getValueAt(i, colNo), "Average", model.getValueAt(i, 0).toString());
    ChartFactory.setChartTheme(StandardChartTheme.createDarknessTheme());

    final JFreeChart chart = ChartFactory.createBarChart3D(chartName, // chart title
            "Requests", // domain axis label

            "Average (ms)", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    final CategoryPlot plot = chart.getCategoryPlot();
    final CategoryAxis axis = plot.getDomainAxis();
    axis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 8.0));
    final BarRenderer3D renderer = (BarRenderer3D) plot.getRenderer();
    renderer.setDrawBarOutline(false);
    renderer.setMaximumBarWidth(0.05);

    try {
        //java.io.OutputStream out= new OutputStream(new FileOutputStream(BASEPATH+"//MyFile.jpg"));
        ChartUtilities.saveChartAsJPEG(new File(BASEPATH + "//MyFile.jpg"), chart, 500, 400);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Image img = null;
    try {
        img = Image.getInstance(BASEPATH + "//MyFile.jpg");
    } catch (BadElementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return img;
}

From source file:org.bonitasoft.studio.migration.utils.PDFMigrationReportWriter.java

License:Open Source License

private com.itextpdf.text.Image getImageForStatus(int status)
        throws BadElementException, MalformedURLException, IOException {
    switch (status) {
    case IStatus.OK:
        Image im = Image.getInstance(FileLocator
                .toFileURL(MigrationPlugin.getDefault().getBundle().getResource("/icons/valid.png")));
        im.setCompressionLevel(12);// www  .j a v  a2s .c  o m
        im.scaleToFit(12, 12);
        return im;
    case IStatus.WARNING:
        im = Image.getInstance(FileLocator
                .toFileURL(MigrationPlugin.getDefault().getBundle().getResource("/icons/warning.gif")));
        im.setCompressionLevel(12);
        im.scaleToFit(16, 16);
        return im;
    case IStatus.ERROR:
        im = Image.getInstance(FileLocator
                .toFileURL(MigrationPlugin.getDefault().getBundle().getResource("/icons/error.png")));
        im.setCompressionLevel(12);
        im.scaleToFit(12, 12);
        return im;
    default:
        break;
    }

    return null;
}

From source file:org.dspace.disseminate.CitationDocument.java

/**
 * Attempts to add a Logo to the document from the given resource. Returns
 * true on success and false on failure.
 *
 * @param doc The document to add the logo to. (Added to the top right
 * corner of the first page.//from w ww  .j  a  v a  2s .  c o m
 * @param writer The writer associated with the given Document.
 * @param res The resource/path to the logo file. This file can be any of
 * the following formats:
 *  GIF, PNG, JPEG, PDF
 *
 * @return Succesfully added logo to document.
 */
private boolean addLogoToDocument(Document doc, PdfWriter writer, String res) {
    boolean ret = false;
    try {
        //First we try to get the logo as if it is a Java Resource
        URL logoURL = this.getClass().getResource(res);
        log.debug(res + " -> " + logoURL.toString());
        if (logoURL == null) {
            logoURL = new URL(res);
        }

        if (logoURL != null) {
            String mtype = URLConnection.guessContentTypeFromStream(logoURL.openStream());
            if (mtype == null) {
                mtype = URLConnection.guessContentTypeFromName(res);
            }
            log.debug("Determined MIMETYPE of logo: " + mtype);
            if (PDF_MIMES.contains(mtype)) {
                //Handle pdf logos.
                PdfReader reader = new PdfReader(logoURL);
                PdfImportedPage logoPage = writer.getImportedPage(reader, 1);
                Image logo = Image.getInstance(logoPage);
                float x = doc.getPageSize().getWidth() - doc.rightMargin() - logo.getScaledWidth();
                float y = doc.getPageSize().getHeight() - doc.topMargin() - logo.getScaledHeight();
                logo.setAbsolutePosition(x, y);
                doc.add(logo);
                ret = true;
            } else if (RASTER_MIMES.contains(mtype)) {
                //Use iText's Image class
                Image logo = Image.getInstance(logoURL);

                //Determine the position of the logo (upper-right corner) and
                //place it there.
                float x = doc.getPageSize().getWidth() - doc.rightMargin() - logo.getScaledWidth();
                float y = doc.getPageSize().getHeight() - doc.topMargin() - logo.getScaledHeight();
                logo.setAbsolutePosition(x, y);
                writer.getDirectContent().addImage(logo);
                ret = true;
            } else if (SVG_MIMES.contains(mtype)) {
                //Handle SVG Logos
                log.error("SVG Logos are not supported yet.");
            } else {
                //Cannot use other mimetypes
                log.debug("Logo MIMETYPE is not supported.");
            }
        } else {
            log.debug("Could not create URL to Logo resource: " + res);
        }
    } catch (Exception e) {
        log.error("Could not add logo (" + res + ") to cited document: " + e.getMessage());
        ret = false;
    }
    return ret;
}

From source file:org.durel.mydooble.ImageItem.java

License:Open Source License

@Override
public void toPDF(PDF out, int i) {
    super.toPDF(out, i);

    try {/* ww  w. j  av a 2 s .  c  o  m*/
        Image img = Image.getInstance(image);
        img.setDpi(288, 288);
        img.setInterpolation(true);
        float ih = (float) (img.getHeight());
        float iw = (float) (img.getWidth());
        if (ih > h || iw > w) {
            float xratio = iw / w;
            float yratio = ih / h;
            float ratio = Math.max(xratio, yratio);
            log.info("ih: " + ih + " - iw: " + iw + " - xratio: " + xratio + " - yratio: " + yratio
                    + " - ratio: " + ratio + " --> " + (int) (iw / ratio) + "x" + (int) (ih / ratio));
            img.scalePercent(100 / ratio);
        }

        PdfContentByte cb = out.writer.getDirectContent();
        float x = bx + (c * (w + m)) + m;
        float y = by + (r * (h + m)) + m;
        img.setAbsolutePosition(x, y);
        cb.addImage(img);
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.fao.geonet.api.records.formatters.ImageReplacedElementFactory.java

License:Open Source License

private ReplacedElement loadImage(LayoutContext layoutContext, BlockBox box,
        UserAgentCallback userAgentCallback, int cssWidth, int cssHeight, String url, float scaleFactor) {
    InputStream input = null;// ww  w. j  av  a2 s  .c  om
    try {
        Log.error(Geonet.GEONETWORK, "URL -> " + url.toString());

        input = new URL(url).openStream();
        byte[] bytes = IOUtils.toByteArray(input);
        Image image = Image.getInstance(bytes);

        image.scaleAbsolute(image.getPlainWidth() * scaleFactor, image.getPlainHeight() * scaleFactor);
        FSImage fsImage = new ITextFSImage(image);

        if (cssHeight > -1 && cssWidth > -1) {
            fsImage.scale(cssWidth, cssHeight);
        }
        int maxWidth = (int) (900 * scaleFactor);
        if (fsImage.getWidth() > maxWidth) {
            int ratio = fsImage.getWidth() / maxWidth;
            fsImage.scale(maxWidth, fsImage.getHeight() / ratio);
        }

        return new ITextImageElement(fsImage);
    } catch (Exception e) {
        Log.error(Geonet.GEONETWORK, "Error writing metadata to PDF", e);

        try {
            return superFactory.createReplacedElement(layoutContext, box, userAgentCallback, cssWidth,
                    cssHeight);
        } catch (Throwable e2) {
            return new EmptyReplacedElement(cssWidth, cssHeight);
        }
    } finally {
        if (input != null) {
            IOUtils.closeQuietly(input);
        }
    }
}

From source file:org.fhaes.jsea.JSEAStatsFunctions.java

License:Open Source License

public void savePDFReport(String filename) {

    Document document = new Document();
    try {//from  ww  w  . jav  a 2  s.c om

        // if you want to save a pdf file using bigbuffer do it here
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        document.add(new Paragraph(para1.get(0)));
        printTableAct.get(0).setWidthPercentage(90);
        printTableAct.get(0).setSpacingBefore(20f);
        printTableAct.get(0).setSpacingAfter(20f);
        document.add(printTableAct.get(0));
        // document.newPage();
        document.add(new Paragraph(para2.get(0)));
        printTableSim.get(0).setWidthPercentage(90);
        printTableSim.get(0).setSpacingBefore(20f);
        printTableSim.get(0).setSpacingAfter(20f);
        document.add(printTableSim.get(0));

        // the charts are being saved from an array list to the files
        for (int i = 0; i < chartList.size(); i++) {
            try {

                File f2 = File.createTempFile("chart" + i, ".png");
                ChartUtilities.saveChartAsPNG(f2, chartList.get(i).getChart(), 800, 500);
                Image image = Image.getInstance(f2.getAbsolutePath());
                float fWidth = 0.6f * 800;
                float fHeight = 0.6f * 500;
                image.scaleAbsolute(fWidth, fHeight);
                document.add(image);
                f2.delete();

            } catch (IOException ex) {
                System.err.println(ex.getLocalizedMessage());
            }
        }
    } catch (Exception e) {

    }

    document.close();

}

From source file:org.fossa.rolp.util.PdfStreamSource.java

License:Open Source License

public PdfStreamSource(FossaApplication app, LebData lebData, LebCreator lebCreator)
        throws DocumentException, IOException, PdfFormatierungsException {
    this.lebData = lebData;
    this.lebCreator = lebCreator;
    BaseFont fontNormal = BaseFont.createFont(
            app.getContext().getBaseDirectory() + Config.getRelativeNormalFontPath(), BaseFont.CP1252,
            BaseFont.EMBEDDED);/*w w w.j a v  a  2 s .  c  o m*/
    BaseFont fontBold = BaseFont.createFont(
            app.getContext().getBaseDirectory() + Config.getRelativeBoldFontPath(), BaseFont.CP1252,
            BaseFont.EMBEDDED);
    BaseFont fontThin = BaseFont.createFont(
            app.getContext().getBaseDirectory() + Config.getRelativeThinFontPath(), BaseFont.CP1252,
            BaseFont.EMBEDDED);

    lernentwicklungsberichtUeberschriftFont = new Font(fontThin, 22, Font.NORMAL);
    standardTextFont = new Font(fontNormal, KlassenstufenUtils.getLebFontSize(lebData.getKlassenname()),
            Font.NORMAL);
    standardTextBoldFont = new Font(fontBold, KlassenstufenUtils.getLebFontSize(lebData.getKlassenname()),
            Font.NORMAL);
    headerFont = new Font(fontNormal, 12, Font.NORMAL);
    footerFont = new Font(fontNormal, 10, Font.NORMAL);
    fusszeilenFont = new Font(fontNormal, 8, Font.NORMAL);
    zeilenabstandsfaktor = KlassenstufenUtils.getLebZeilenabstandAsFactor(lebData.getKlassenname());
    document = null;
    try {
        document = new Document(PageSize.A4, 100, 90, topMargin, bottomMargin);
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        LebPageHelper event = new LebPageHelper(lebData,
                Image.getInstance(app.getContext().getBaseDirectory() + Config.getRelativeLogoPath()),
                fusszeilenFont);
        writer.setPageEvent(event);
        document.open();
        addContent(writer);
        addFooter(lebData, writer);
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:org.gbif.ipt.task.Eml2Pdf.java

public void writeEmlIntoPdf(Document doc, Resource resource, PdfWriter pdfWriter, String lng, String cert,
        String url) {//ww  w  . j av  a 2  s  .  c  om
    Locale loc = new Locale(lng);
    String[] dataCert = cert.split("-");
    resourceBundle = ResourceBundle.getBundle("ApplicationResources", loc);
    // this.action = action;
    authoritiesHome = new LinkedHashMap<String, String>();
    authoritiesHome.putAll(cfg.loadAuthorities());
    //roles list, derived from XML vocabulary, and displayed in drop-down where new contacts are created
    roles = new LinkedHashMap<String, String>();
    roles.put("", getText("eml.agent.role.selection"));
    roles.putAll(vocabManager.getI18nVocab(Constants.VOCAB_URI_ROLES, "es", false));
    Eml eml = resource.getEml();
    setInfo(eml);
    setDate(dataCert[0]);
    String keys = "";
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    for (KeywordSet kw : eml.getKeywords()) {
        if (keys.length() == 0) {
            keys = kw.getKeywordsString(", ");
        } else {
            keys += ", " + kw.getKeywordsString(", ");
        }
    }
    doc.addKeywords(keys);
    addMetaData(doc);
    doc.open();

    String htmlText = "<html>";
    htmlText += "<style type='text/css'>";
    htmlText += " .mainTable{width:100%;} "
            + ".nota{color:#e75170;font-family:sans-serif;font-size: 14px;padding: 40px;font-weight:bold;margin-top:90px;margin-botom:400px}"
            + ".centerLine{text-align:center;} " + ".subtitle{color:#ebf7fb;} "
            + ".resumeInfo{width: 418px;padding: 40px;}"
            + "h4{font-family:sans-serif;font-size: 22px;color: #58585b}" + "span{color:#268ac7}"
            + "label{font-family:sans-serif;font-size: 18px;color: #58585b;margin-bottom:5px;font-weight:100}"
            + "a{color:#43afe3}" + "b{font-weight:bold}"
            + "h2{font-family:sans-serif;font-size: 26px;color: #58585b}"
            + "h3{font-family:sans-serif;color: #58585b}"
            + "p{font-family:sans-serif;font-size: 16px;color: #58585b;font-weight:100;text-align:justify;}";
    htmlText += "</style>";
    htmlText += "<body><table class='mainTable'><tr align='center' class='centerLine'><td>";
    htmlText += "<img width='520px' src='" + url + "/styles/certificado_header_crsibA.png' class='imgTitle'/>";
    htmlText += "</td></tr>";
    htmlText += "<tr align='center' class='centerLine'><td>";
    htmlText += "</td></tr>";
    htmlText += "<tr><td class='resumeInfo'>";
    htmlText += "<p id='resumeInfo'>";
    htmlText += "<h4><span>1. </span>" + getText("pdf.info.cert") + "</h4>";
    htmlText += "<br />";
    htmlText += "<label>" + getText("pdf.cert.number") + "<b>" + dataCert[0] + "</b></label><br/>";
    htmlText += "<label>" + getText("pdf.cert.resource.actu") + "<b>"
            + dateFormat.format(resource.getModified()) + "</b></label><br/>";
    htmlText += "<label>" + getText("pdf.cert.resource.url") + "<a href='" + url + "/resource.do?r="
            + resource.getShortname() + "'>" + url + "/resource.do?r=" + resource.getShortname()
            + "</a></label><br/>";

    if (resource.getRecordsPublished() != 0) {
        htmlText += "<label>" + getText("pdf.cert.resource.records") + "<b>" + resource.getRecordsPublished()
                + "</b></label>";
    } else {
        if (resource.getSources().size() > 0) {
            if (resource.getSources().get(0).isExcelSource()) {
                ExcelFileSource excl = new ExcelFileSource();
                excl = (ExcelFileSource) resource.getSources().get(0);
                htmlText += "<label>" + getText("pdf.cert.resource.records") + "<b>" + excl.getRows()
                        + "</b></label>";
            } else if (resource.getSources().get(0).isFileSource()) {
                TextFileSource txtcl = new TextFileSource();
                txtcl = (TextFileSource) resource.getSources().get(0);
                htmlText += "<label>" + getText("pdf.cert.resource.records") + "<b>" + txtcl.getRows()
                        + "</b></label>";
            }
        }
    }

    htmlText += "</p>";
    htmlText += "</td></tr>";

    htmlText += "<tr ><td style='text-align:justify;'>";
    //htmlText +="<br />";
    htmlText += "<h2><span>2. </span>" + getText("pdf.license") + "</h2> ";
    htmlText += "<p><b>" + getText("pdf.license.authority") + "</b><br/>" + aut + "<br/>";
    htmlText += "<b>" + getText("pdf.license.number") + "</b><br/>" + num + "<br/>";
    htmlText += "<b>" + getText("pdf.license.holder") + "</b><br/>" + hol + "<br/>";
    htmlText += "<b>" + getText("pdf.license.nit") + "</b><br/>" + nit + "<br/>";
    htmlText += "<b>" + getText("pdf.license.date") + "</b><br/>" + dte + "</p>";

    htmlText += "<h2><span>3. </span>" + getText("pdf.info.project") + "</h2> ";
    htmlText += "<p>";
    htmlText += "<b>" + getText("pdf.title.proyect") + "</b><br/>";
    htmlText += eml.getTitle().replaceAll("<", "&#60;").replaceAll(">", "&#62;");
    ;
    htmlText += "</p>";
    htmlText += "<p>";
    htmlText += "<b>" + getText("pdf.abstract") + "</b><br/>";
    htmlText += eml.getDescription().replaceAll("<", "&#60;").replaceAll(">", "&#62;");
    ;
    htmlText += "</p>";
    htmlText += "<p>";

    htmlText += "<b>" + getText("pdf.keywords") + "</b><br/>";
    htmlText += keys.replaceAll("<", "&#60;").replaceAll(">", "&#62;");
    htmlText += "</p>";

    int subI = 0;

    subI++;
    htmlText += "<h3><span>3." + subI + " </span>" + getText("pdf.contact.resource") + "</h3> ";
    htmlText += "<p>";
    htmlText += "<b>" + getText("pdf.contact.resource.name") + "</b><br/>";
    htmlText += eml.getContact().getFirstName().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + " "
            + eml.getContact().getLastName().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
    htmlText += "<b>" + getText("pdf.contact.resource.position") + "</b><br/>";
    htmlText += eml.getContact().getPosition().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
    htmlText += "<b>" + getText("pdf.contact.resource.organisation") + "</b><br/>";
    htmlText += eml.getContact().getOrganisation().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
    htmlText += "<b>" + getText("pdf.contact.resource.address.address") + "</b><br/>";
    htmlText += eml.getContact().getAddress().getAddress().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
            + "<br/>";
    htmlText += "<b>" + getText("pdf.contact.resource.address.city") + "</b><br/>";
    htmlText += eml.getContact().getAddress().getCity().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
            + "<br/>";
    if (exists(eml.getContact().getAddress().getPostalCode())) {
        htmlText += "<b>" + getText("pdf.contact.resource.address.postalcode") + "</b><br/>";
        htmlText += eml.getContact().getAddress().getPostalCode().replaceAll("<", "&#60;").replaceAll(">",
                "&#62;") + "<br/>";
    }
    htmlText += "<b>" + getText("pdf.contact.resource.phone") + "</b><br/>";
    htmlText += eml.getContact().getPhone().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
    htmlText += "<b>" + getText("pdf.contact.resource.email") + "</b><br/>";
    htmlText += eml.getContact().getEmail().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
    if (exists(eml.getContact().getHomepage())) {
        htmlText += "<b>" + getText("pdf.contact.resource.homepage") + "</b><br/>"; //***
        htmlText += eml.getContact().getHomepage().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
    }
    htmlText += "</p>";

    subI++;
    htmlText += "<h3><span>3." + subI + " </span>" + getText("pdf.resourceCreator") + "</h3> ";
    htmlText += "<p>";
    htmlText += "<b>" + getText("pdf.resourceCreator.name") + "</b><br/>";
    htmlText += eml.getResourceCreator().getFirstName().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + " "
            + eml.getResourceCreator().getLastName().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
            + "<br/>";
    htmlText += "<b>" + getText("pdf.resourceCreator.position") + "</b><br/>";
    htmlText += eml.getResourceCreator().getPosition().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
            + "<br/>";
    htmlText += "<b>" + getText("pdf.resourceCreator.organisation") + "</b><br/>";
    htmlText += eml.getResourceCreator().getOrganisation().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
            + "<br/>";
    htmlText += "<b>" + getText("pdf.resourceCreator.address.address") + "</b><br/>";
    htmlText += eml.getResourceCreator().getAddress().getAddress().replaceAll("<", "&#60;").replaceAll(">",
            "&#62;") + "<br/>";
    htmlText += "<b>" + getText("pdf.resourceCreator.address.city") + "</b><br/>";
    htmlText += eml.getResourceCreator().getAddress().getCity().replaceAll("<", "&#60;").replaceAll(">",
            "&#62;") + "<br/>";
    if (exists(eml.getResourceCreator().getAddress().getPostalCode())) {
        htmlText += "<b>" + getText("pdf.resourceCreator.address.postalcode") + "</b><br/>";
        htmlText += eml.getResourceCreator().getAddress().getPostalCode().replaceAll("<", "&#60;")
                .replaceAll(">", "&#62;") + "<br/>";
    }
    htmlText += "<b>" + getText("pdf.resourceCreator.phone") + "</b><br/>";
    htmlText += eml.getResourceCreator().getPhone().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
    htmlText += "<b>" + getText("pdf.resourceCreator.email") + "</b><br/>";
    htmlText += eml.getResourceCreator().getEmail().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
    if (exists(eml.getResourceCreator().getHomepage())) {
        htmlText += "<b>" + getText("pdf.resourceCreator.homepage") + "</b><br/>"; //***
        htmlText += eml.getResourceCreator().getHomepage().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
                + "<br/>";
    }
    htmlText += "</p>";

    subI++;
    htmlText += "<h3><span>3." + subI + " </span>" + getText("pdf.metadataProvider") + "</h3> ";
    htmlText += "<p>";
    htmlText += "<b>" + getText("pdf.metadataProvider.name") + "</b><br/>";
    htmlText += eml.getMetadataProvider().getFirstName() + " "
            + eml.getMetadataProvider().getLastName().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
            + "<br/>";
    htmlText += "<b>" + getText("pdf.metadataProvider.position") + "</b><br/>";
    htmlText += eml.getMetadataProvider().getPosition().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
            + "<br/>";
    htmlText += "<b>" + getText("pdf.metadataProvider.organisation") + "</b><br/>";
    htmlText += eml.getMetadataProvider().getOrganisation().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
            + "<br/>";
    htmlText += "<b>" + getText("pdf.metadataProvider.address.address") + "</b><br/>";
    htmlText += eml.getMetadataProvider().getAddress().getAddress().replaceAll("<", "&#60;").replaceAll(">",
            "&#62;") + "<br/>";
    htmlText += "<b>" + getText("pdf.metadataProvider.address.city") + "</b><br/>";
    htmlText += eml.getMetadataProvider().getAddress().getCity().replaceAll("<", "&#60;").replaceAll(">",
            "&#62;") + "<br/>";
    if (exists(eml.getMetadataProvider().getAddress().getPostalCode())) {
        htmlText += "<b>" + getText("pdf.metadataProvider.address.postalcode") + "</b><br/>";
        htmlText += eml.getMetadataProvider().getAddress().getPostalCode().replaceAll("<", "&#60;")
                .replaceAll(">", "&#62;") + "<br/>";
    }
    htmlText += "<b>" + getText("pdf.metadataProvider.phone") + "</b><br/>";
    htmlText += eml.getMetadataProvider().getPhone().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
            + "<br/>";
    htmlText += "<b>" + getText("pdf.metadataProvider.email") + "</b><br/>";
    htmlText += eml.getMetadataProvider().getEmail().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
            + "<br/>";
    if (exists(eml.getMetadataProvider().getHomepage())) {
        htmlText += "<b>" + getText("pdf.metadataProvider.homepage") + "</b><br/>"; //***
        htmlText += eml.getMetadataProvider().getHomepage().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
                + "<br/>";
    }
    htmlText += "</p>";

    subI++;
    htmlText += "<h3><span>3." + subI + " </span>" + getText("pdf.spatialCoverage") + "</h3> ";
    htmlText += "<p>";
    htmlText += getGeoCov(eml).replaceAll("<", "&#60;").replaceAll(">", "&#62;");
    htmlText += "</p>";
    //------

    subI++;
    htmlText += "<h3><span>3." + subI + " </span>" + getText("pdf.taxcoverage") + "</h3> ";
    htmlText += "<p>";
    htmlText += getTaxCov(eml);
    htmlText += "</p>";

    subI++;
    htmlText += "<h3><span>3." + subI + " </span>" + getText("pdf.tempcoverage") + "</h3> ";
    htmlText += "<p>";
    htmlText += getTempCov(eml, loc);
    htmlText += "</p>";

    subI++;
    htmlText += "<h3><span>3." + subI + " </span>" + getText("pdf.methods") + "</h3> ";
    htmlText += "<p>";
    htmlText += eml.getSampleDescription().replaceAll("<", "&#60;").replaceAll(">", "&#62;");
    htmlText += "</p>";

    //-------

    if (exists(eml.getCollectionName())) {
        subI++;
        htmlText += "<h3><span>3." + subI + " </span>" + getText("pdf.collections") + "</h3> ";
        htmlText += "<p>";
        htmlText += "<b>" + getText("pdf.collections.name") + "</b><br/>";
        htmlText += eml.getCollectionName().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
        htmlText += "<b>" + getText("pdf.collections.identifier") + "</b><br/>";
        htmlText += eml.getCollectionId().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
        htmlText += "<b>" + getText("pdf.collections.parent") + "</b><br/>";
        htmlText += eml.getParentCollectionId().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
        Map<String, String> metp = vocabManager.getI18nVocab(Constants.VOCAB_URI_PRESERVATION_METHOD, "es",
                false);
        if (exists(eml.getSpecimenPreservationMethod())) {
            htmlText += "<b>" + getText("pdf.collections.specimen") + "</b><br/>"; //***
            htmlText += metp
                    .get(eml.getSpecimenPreservationMethod().replaceAll("<", "&#60;").replaceAll(">", "&#62;"))
                    + "<br/>";
        }
        htmlText += "</p>";
    }

    if (exists(eml.getProject().getTitle())) {
        subI++;
        htmlText += "<h3><span>3." + subI + " </span>" + getText("pdf.project") + "</h3> ";
        htmlText += "<p>";
        htmlText += "<b>" + getText("pdf.project.title") + "</b><br/>";
        htmlText += eml.getProject().getTitle().replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
        if (exists(eml.getProject().getPersonnel())) {
            htmlText += "<b>" + getText("pdf.project.personnel.firstName") + "</b><br/>";
            htmlText += eml.getProject().getPersonnel().getFirstName() + " "
                    + eml.getProject().getPersonnel().getLastName() + "<br/>";
        }
        if (exists(eml.getProject().getPersonnel().getRole())) {
            htmlText += "<b>" + getText("pdf.project.personnel.role") + "</b><br/>";
            htmlText += roles.get(
                    eml.getProject().getPersonnel().getRole().replaceAll("<", "&#60;").replaceAll(">", "&#62;"))
                    + "<br/>";
        }
        if (exists(eml.getProject().getFunding())) {
            htmlText += "<b>" + getText("pdf.project.funding") + "</b><br/>";
            htmlText += eml.getProject().getFunding().replaceAll("<", "&#60;").replaceAll(">", "&#62;")
                    + "<br/>";
        }
        if (exists(eml.getProject().getStudyAreaDescription())) {
            htmlText += "<b>" + getText("pdf.project.studyAreaDescription.descriptorValue") + "</b><br/>";
            htmlText += eml.getProject().getStudyAreaDescription().getDescriptorValue().replaceAll("<", "&#60;")
                    .replaceAll(">", "&#62;") + "<br/>";
        }
        if (exists(eml.getProject().getDesignDescription())) {
            htmlText += "<b>" + getText("pdf.project.designDescription") + "</b><br/>";
            htmlText += eml.getProject().getDesignDescription().replaceAll("<", "&#60;").replaceAll(">",
                    "&#62;") + "<br/>";
        }
        htmlText += "</p>";
    }

    if (eml.getAssociatedParties().size() != 0) {
        if (exists(eml.getAssociatedParties().get(0))) {
            subI++;
            htmlText += "<h3><span>3." + subI + " </span>" + getText("pdf.associatedParties") + "</h3> ";
            htmlText += "<p>";
            for (int i = 0; i < eml.getAssociatedParties().size(); i++) {
                if (exists(eml.getAssociatedParties().get(i).getLastName())) {
                    htmlText += "<b>" + getText("pdf.associatedParties.name") + "</b><br/>";
                    htmlText += eml.getAssociatedParties().get(i).getFirstName() + " "
                            + eml.getAssociatedParties().get(i).getLastName().replaceAll("<", "&#60;")
                                    .replaceAll(">", "&#62;")
                            + "<br/>";
                }
                if (exists(eml.getAssociatedParties().get(i).getPosition())) {
                    htmlText += "<b>" + getText("pdf.associatedParties.position") + "</b><br/>";
                    htmlText += eml.getAssociatedParties().get(i).getPosition().replaceAll("<", "&#60;")
                            .replaceAll(">", "&#62;") + "<br/>";
                }
                if (exists(eml.getAssociatedParties().get(i).getOrganisation())) {
                    htmlText += "<b>" + getText("pdf.associatedParties.organisation") + "</b><br/>";
                    htmlText += eml.getAssociatedParties().get(i).getOrganisation().replaceAll("<", "&#60;")
                            .replaceAll(">", "&#62;") + "<br/>";
                }
                if (exists(eml.getAssociatedParties().get(i).getAddress().getAddress())) {
                    htmlText += "<b>" + getText("pdf.associatedParties.address.address") + "</b><br/>";
                    htmlText += eml.getAssociatedParties().get(i).getAddress().getAddress()
                            .replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
                }
                if (exists(eml.getAssociatedParties().get(i).getAddress().getCity())) {
                    htmlText += "<b>" + getText("pdf.associatedParties.city") + "</b><br/>";
                    htmlText += eml.getAssociatedParties().get(i).getAddress().getCity()
                            .replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
                }
                if (exists(eml.getAssociatedParties().get(i).getAddress().getPostalCode())) {
                    htmlText += "<b>" + getText("pdf.associatedParties.address.postalcode") + "</b><br/>";
                    htmlText += eml.getAssociatedParties().get(i).getAddress().getPostalCode()
                            .replaceAll("<", "&#60;").replaceAll(">", "&#62;") + "<br/>";
                }
                if (exists(eml.getAssociatedParties().get(i).getPhone())) {
                    htmlText += "<b>" + getText("pdf.associatedParties.phone") + "</b><br/>";
                    htmlText += eml.getAssociatedParties().get(i).getPhone().replaceAll("<", "&#60;")
                            .replaceAll(">", "&#62;") + "<br/>";
                }
                if (exists(eml.getAssociatedParties().get(i).getEmail())) {
                    htmlText += "<b>" + getText("pdf.associatedParties.email") + "</b><br/>";
                    htmlText += eml.getAssociatedParties().get(i).getEmail().replaceAll("<", "&#60;")
                            .replaceAll(">", "&#62;") + "<br/>";
                }
                if (exists(eml.getAssociatedParties().get(i).getHomepage())) {
                    htmlText += "<b>" + getText("pdf.associatedParties.homepage") + "</b><br/>"; //***
                    htmlText += eml.getAssociatedParties().get(i).getHomepage().replaceAll("<", "&#60;")
                            .replaceAll(">", "&#62;") + "<br/>";
                }
                htmlText += "<br/>";
            }
            htmlText += "</p>";
        }
    }

    htmlText += "</td>";
    htmlText += "</tr>";

    htmlText += "<tr class='centerLine'>";
    htmlText += "<td>";
    htmlText += "</td>";
    htmlText += "</tr>";

    htmlText += "</table>";
    htmlText += "<p class='nota'>" + getText("pdf.cert.dis") + "<a href='" + url + "/pdf.do?r="
            + resource.getShortname() + "&n" + "=" + dataCert[0] + "'>" + url + "/pdf.do?r="
            + resource.getShortname() + "&amp;n=" + dataCert[0] + "</a></p><p></p></body></html>";

    try {
        Image background = Image.getInstance(url + "/styles/certificado_bg1.png");
        float width = 498;
        float height = 174;
        pdfWriter.getDirectContentUnder().addImage(background, width, 0, 0, height, 50, 490);

        parseHTML(doc, htmlText, pdfWriter);

        Image background_1 = Image.getInstance(url + "/styles/certificado_footer.png");
        width = 498;
        height = 103;
        pdfWriter.getDirectContentUnder().addImage(background_1, width, 0, 0, height, 50, 20);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (BadElementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    doc.close();
}

From source file:org.h819.commons.file.MyPDFUtils.java

/**
 * ??/*from  ww  w  .  ja v  a2  s  .  com*/
 *
 * @param srcPdf         ?
 * @param destPdf        
 * @param waterMarkText  ?
 * @param waterMarkImage ?
 */
public static void addWaterMarkFile(File srcPdf, File destPdf, String waterMarkText, File waterMarkImage)
        throws IOException, DocumentException {

    if (waterMarkText == null && waterMarkImage == null)
        throw new FileNotFoundException(waterMarkText + " " + waterMarkImage + " all null.");

    if (srcPdf == null || !srcPdf.exists() || !srcPdf.isFile())
        throw new FileNotFoundException("pdf file :  '" + srcPdf + "' does not exsit.");

    if (!FilenameUtils.getExtension(srcPdf.getAbsolutePath()).toLowerCase().equals("pdf"))
        return;

    if (waterMarkImage != null) {
        if (!waterMarkImage.exists() || !waterMarkImage.isFile())
            throw new FileNotFoundException("img file :  '" + srcPdf + "' does not exsit.");

        if (!FilenameUtils.getExtension(waterMarkImage.getAbsolutePath()).toLowerCase().equals("png"))
            throw new FileNotFoundException("image file '" + srcPdf
                    + "'  not png.(???? pdf )");
    }

    PdfReader reader = getPdfReader(srcPdf);

    int n = reader.getNumberOfPages();
    PdfStamper stamper = getPdfStamper(srcPdf, destPdf);

    //
    //        HashMap<String, String> moreInfo = new HashMap<String, String>();
    //        moreInfo.put("Author", "H819 create");
    //        moreInfo.put("Producer", "H819 Producer");
    //        Key = CreationDate, Value = D:20070425182920
    //        Key = Producer, Value = TH-OCR 2000 (C++/Win32)
    //        Key = Author, Value = TH-OCR 2000
    //        Key = Creator, Value = TH-OCR PDF Writer

    // stamp.setMoreInfo(moreInfo);

    // text
    Phrase text = null;
    if (waterMarkText != null) {
        //
        Font bfont = getPdfFont();
        bfont.setSize(35);
        bfont.setColor(new BaseColor(192, 192, 192));
        text = new Phrase(waterMarkText, bfont);
    }
    // image watermark
    Image img = null;
    float w = 0;
    float h = 0;
    if (waterMarkImage != null) {
        img = Image.getInstance(waterMarkImage.getAbsolutePath());
        w = img.getScaledWidth();
        h = img.getScaledHeight();
        //  img.
        img.setRotationDegrees(45);

    }

    // transparency
    PdfGState gs1 = new PdfGState();
    gs1.setFillOpacity(0.5f);
    // properties
    PdfContentByte over;
    Rectangle pageSize;
    float x, y;
    // loop over every page
    for (int i = 1; i <= n; i++) {
        pageSize = reader.getPageSizeWithRotation(i);
        x = (pageSize.getLeft() + pageSize.getRight()) / 2;
        y = (pageSize.getTop() + pageSize.getBottom()) / 2;
        //  pdf pdf ???
        over = stamper.getOverContent(i);
        // ?
        // over = stamp.getUnderContent(i);
        // ?? over.beginText(); over.endText(); ?
        // ,?,:????
        over.saveState(); //??
        over.setGState(gs1);

        if (waterMarkText != null && waterMarkImage != null) { // 
            if (i % 2 == 1) {
                ColumnText.showTextAligned(over, Element.ALIGN_CENTER, text, x, y, 45);
            } else
                over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
        } else if (waterMarkText != null) { //?

            ColumnText.showTextAligned(over, Element.ALIGN_CENTER, text, x, y, 45);
            //?? ,?, :?????
            // ...

        } else { //?
            over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
        }

        over.restoreState();//???
    }

    stamper.close();
    reader.close();

}

From source file:org.inspira.condominio.pdf.DocumentoEstadoDeCuenta.java

private void bakeContent(String path, String imgResString) throws IOException, DocumentException {
    File outFile = new File(path);
    outFile.getParentFile().mkdirs();//from   w  w w  .j  a v  a 2 s  . c  o  m
    PdfWriter.getInstance(documento, new FileOutputStream(outFile));
    documento.open();
    documento.add(new Paragraph(
            "Ciudad de Mxico, "
                    + DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()).format(new Date()),
            new Font(FontFamily.HELVETICA, 18, Font.NORMAL, new BaseColor(0x000000))));
    Paragraph intro = new Paragraph(new Phrase("Comprobante de estado de cuenta", F_NORMAL));
    intro.setAlignment(Paragraph.ALIGN_RIGHT);
    intro.setSpacingBefore(10f);
    documento.add(intro);
    Image image = Image.getInstance(imgResString);
    PdfPTable table = new PdfPTable(1);
    table.setTotalWidth(image.getScaledWidth());
    table.setLockedWidth(true);
    PdfPCell cell = new PdfPCell();
    cell.setBorder(0);
    //cell.setCellEvent(new ImageBackgroundEvent(image));
    cell.setFixedHeight(image.getScaledHeight());
    table.addCell(cell);
    documento.add(table);
    Paragraph p1 = new Paragraph("Estado de cuenta: ".concat(idEdoCta), F_NORMAL);
    p1.setSpacingBefore(5f);
    p1.setSpacingAfter(25f);
    p1.setAlignment(Paragraph.ALIGN_CENTER);
    documento.add(p1);
    documento.add(new Paragraph("Pagos", F_NORMAL));
    agregaTablaDePagos();
    Paragraph pNotas = new Paragraph("Notas: ".concat(notas), F_NORMAL);
    pNotas.setSpacingAfter(12f);
    pNotas.setSpacingAfter(2f);
    documento.add(pNotas);
    Paragraph pAdeudos = new Paragraph("Adeudos", F_NORMAL);
    pAdeudos.setSpacingBefore(25f);
    documento.add(pAdeudos);
    agregaTablaDeAdeudos();
    documento.add(new Paragraph(
            "Recuerde que puede consultar su estado de pagos y adeudos desde la aplicacin mvil o directamente con su administrador.",
            F_NORMAL));
    Paragraph hechoPor = new Paragraph("Elabor:", F_NORMAL);
    hechoPor.setSpacingBefore(30f);
    hechoPor.setSpacingAfter(15f);
    documento.add(hechoPor);
    Paragraph nombreDelAdmin = new Paragraph(admin, F_NORMAL);
    nombreDelAdmin.setAlignment(Paragraph.ALIGN_CENTER);
    documento.add(nombreDelAdmin);
    Paragraph nombreDeCondominio = new Paragraph(condominio, F_NORMAL);
    nombreDeCondominio.setAlignment(Paragraph.ALIGN_CENTER);
    documento.add(nombreDeCondominio);
}