Example usage for com.lowagie.text Image scaleToFit

List of usage examples for com.lowagie.text Image scaleToFit

Introduction

In this page you can find the example usage for com.lowagie.text Image scaleToFit.

Prototype

public void scaleToFit(float fitWidth, float fitHeight) 

Source Link

Document

Scales the image so that it fits a certain width and height.

Usage

From source file:org.apache.maven.doxia.module.itext.ITextSink.java

License:Apache License

/**
 * If the <code>name</code> is a relative link, the internal link will used a System property
 * <code>itext.basedir</code>, or the class loader.
 * {@inheritDoc}/*from   w  w  w. j  a v  a2  s. c o m*/
 */
public void figureGraphics(String name) {
    String urlName = null;
    File nameFile = null;
    if ((name.toLowerCase(Locale.ENGLISH).startsWith("http://"))
            || (name.toLowerCase(Locale.ENGLISH).startsWith("https://"))) {
        urlName = name;
    } else {
        if (System.getProperty("itext.basedir") != null) {
            try {
                nameFile = new File(System.getProperty("itext.basedir"), name);
                urlName = nameFile.toURI().toURL().toString();
            } catch (MalformedURLException e) {
                getLog().error("MalformedURLException: " + e.getMessage(), e);
            }
        } else {
            if (getClassLoader() != null) {
                if (getClassLoader().getResource(name) != null) {
                    urlName = getClassLoader().getResource(name).toString();
                }
            } else {
                if (ITextSink.class.getClassLoader().getResource(name) != null) {
                    urlName = ITextSink.class.getClassLoader().getResource(name).toString();
                }
            }
        }
    }

    if (urlName == null) {
        String msg = "No image '" + name
                + "' found in the class loader. Try to call setClassLoader(ClassLoader) before.";
        logMessage("imageNotFound", msg);

        return;
    }

    if (nameFile != null && !nameFile.exists()) {
        String msg = "No image '" + nameFile + "' found in your system, check the path.";
        logMessage("imageNotFound", msg);

        return;
    }

    boolean figureCalled = figureDefined;
    if (!figureCalled) {
        figure();
    }

    float width = 0;
    float height = 0;
    try {
        Image image = Image.getInstance(new URL(urlName));
        image.scaleToFit(ITextUtil.getDefaultPageSize().width() / 2,
                ITextUtil.getDefaultPageSize().height() / 2);
        width = image.plainWidth();
        height = image.plainHeight();
    } catch (BadElementException e) {
        getLog().error("BadElementException: " + e.getMessage(), e);
    } catch (MalformedURLException e) {
        getLog().error("MalformedURLException: " + e.getMessage(), e);
    } catch (IOException e) {
        getLog().error("IOException: " + e.getMessage(), e);
    }

    writeAddAttribute(ElementTags.URL, urlName);
    writeAddAttribute(ElementTags.ALIGN, ElementTags.ALIGN_MIDDLE);
    writeAddAttribute(ElementTags.PLAINWIDTH, String.valueOf(width));
    writeAddAttribute(ElementTags.PLAINHEIGHT, String.valueOf(height));

    actionContext.setAction(SinkActionContext.FIGURE_GRAPHICS);

    if (!figureCalled) {
        figure_();
    }
}

From source file:org.cgiar.ccafs.ap.summaries.projects.pdf.ProjectSummaryPDF.java

License:Open Source License

/**
 * Entering the project outputs in the summary
 *//*  w ww .j av a  2s .c  o  m*/
private void addProjectOutputs(String number) {

    // **********************************************************************************
    // *************************** Overview By Mog *************************************
    // **********************************************************************************
    try {
        Paragraph overview_title = new Paragraph();
        overview_title.setFont(HEADING2_FONT);
        overview_title.add(number + ". " + this.getText("summaries.project.projectOutput"));
        overview_title.add(Chunk.NEWLINE);
        overview_title.add(Chunk.NEWLINE);

        document.newPage();
        document.add(overview_title);

        overview_title = new Paragraph();
        overview_title.setFont(HEADING3_FONT);
        overview_title.add(number + ".1 " + this.getText("summaries.project.overviewbymogs"));
        document.add(overview_title);

    } catch (DocumentException e) {
        LOG.error("There was an error trying to add the project title to the project summary pdf", e);
    }

    int[] years = { midOutcomeYear,
            project.isReporting() ? this.currentReportingYear - 1 : this.currentReportingYear - 1,
            project.isReporting() ? this.currentReportingYear : this.currentPlanningYear,
            project.isReporting() ? this.currentReportingYear + 1 : this.currentReportingYear + 1 };

    Paragraph paragraph = new Paragraph();

    List<IPElement> mogs = project.getOutputs();
    try {
        if (mogs.isEmpty()) {
            paragraph.add(this.getText("summaries.project.empty"));
            document.add(paragraph);

        } else {
            // year
            PdfPTable table;
            for (int a = 0; a < years.length; a++) {
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_HEADER_FONT);
                paragraph.add(this.getText("summaries.project.overviewbymogs.text") + "- " + years[a]);
                table = new PdfPTable(1);
                table.setLockedWidth(true);
                table.setTotalWidth(480);
                this.addTableHeaderCell(table, paragraph);
                // Mog
                for (int b = 0; b < mogs.size(); b++) {
                    this.addOverview(table, mogs.get(b), years[a]);
                }
                paragraph = new Paragraph();
                paragraph.add(Chunk.NEWLINE);
                document.add(paragraph);
                document.add(table);
            }

            // Leason regardins
            paragraph = new Paragraph();
            paragraph.add(Chunk.NEWLINE);
            paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
            paragraph.setFont(BODY_TEXT_BOLD_FONT);
            if (!project.isReporting()) {
                paragraph.add(this.getText("summaries.project.output.lessonRegarding"));
            } else {
                paragraph.add(this.getText("summaries.project.overviewbymogs.reporting.lesson"));
            }
            paragraph.setFont(BODY_TEXT_FONT);
            if (project.getComponentLesson("outputs") != null) {
                paragraph.add(this.messageReturn(project.getComponentLesson("outputs").getLessons()));
            } else {
                paragraph.add(this.messageReturn(null));
            }
            paragraph.add(Chunk.NEWLINE);
            paragraph.add(Chunk.NEWLINE);
            document.add(paragraph);
        }

    } catch (DocumentException e) {
        LOG.error("There was an error trying to add the project title to the project summary pdf", e);
    }

    // **********************************************************************************
    // *************************** Deliverables.****************************************
    // **********************************************************************************

    int counter = 1;
    try {
        document.newPage();
        paragraph = new Paragraph();
        paragraph.setFont(HEADING3_FONT);
        paragraph.add(number + ".2 " + this.getText("summaries.project.deliverable.title"));
        document.add(paragraph);
        paragraph = new Paragraph();

        List<Deliverable> listDeliverables = project.getDeliverables();
        if (listDeliverables.isEmpty()) {
            paragraph.add(this.getText("summaries.project.empty"));
            document.add(paragraph);
        } else {
            paragraph.add(Chunk.NEWLINE);
            document.add(paragraph);
            for (Deliverable deliverable : listDeliverables) {
                if (!project.isReporting()) {
                    if (deliverable.getYear() == config.getPlanningCurrentYear()) {
                        this.addDelivable(deliverable, counter);
                        counter++;

                    }
                }
            }
        }

        // **********************************************************************************
        // *************************** Next users.****************************************
        // **********************************************************************************

        if (project.isReporting()) {

            counter = 1;
            document.newPage();
            paragraph = new Paragraph();
            paragraph.setFont(HEADING3_FONT);
            paragraph.add(number + ".3 " + this.getText("summaries.project.reporting.nextuser.title"));
            document.add(paragraph);

            PdfPTable table;

            if (project.getNextUsers().isEmpty()) {

                paragraph = new Paragraph();
                paragraph.add(this.messageReturn(null));
                paragraph.add(Chunk.NEWLINE);
                document.add(paragraph);

            } else {
                paragraph = new Paragraph();
                paragraph.add(Chunk.NEWLINE);
                document.add(paragraph);

                for (ProjectNextUser projectNextUser : project.getNextUsers()) {

                    paragraph = new Paragraph();
                    paragraph.setFont(TABLE_HEADER_FONT);
                    paragraph.setAlignment(Element.ALIGN_LEFT);

                    table = new PdfPTable(1);
                    table.setLockedWidth(true);
                    table.setTotalWidth(480);

                    paragraph.add(this.getText("summaries.project.reporting.nextuser",
                            new String[] { String.valueOf(counter) }));
                    this.addTableHeaderCell(table, paragraph);

                    // Next users key
                    paragraph = new Paragraph();
                    paragraph.setFont(TABLE_BODY_BOLD_FONT);
                    paragraph.add(this.getText("summaries.project.reporting.nextuser.currentPeriod"));
                    paragraph.setFont(TABLE_BODY_FONT);

                    if (projectNextUser != null) {
                        paragraph.add(this.messageReturn(projectNextUser.getKeyNextUser()));
                    } else {
                        paragraph.add(this.messageReturn(null));
                    }
                    this.addTableBodyCell(table, paragraph, Element.ALIGN_LEFT, 1);

                    // Strategies
                    paragraph = new Paragraph();
                    paragraph.setFont(TABLE_BODY_BOLD_FONT);
                    paragraph.add(this.getText("summaries.project.reporting.nextuser.strategies"));
                    paragraph.setFont(TABLE_BODY_FONT);

                    if (projectNextUser != null) {
                        paragraph.add(this.messageReturn(projectNextUser.getStrategies()));
                    } else {
                        paragraph.add(this.messageReturn(null));
                    }
                    this.addTableBodyCell(table, paragraph, Element.ALIGN_LEFT, 1);

                    // reported
                    paragraph = new Paragraph();
                    paragraph.setFont(TABLE_BODY_BOLD_FONT);
                    paragraph.add(this.getText("summaries.project.reporting.nextuser.reported"));
                    paragraph.setFont(TABLE_BODY_FONT);

                    if (projectNextUser != null) {
                        paragraph.add(this.messageReturn(projectNextUser.getReportedDeliverables()));
                    } else {
                        paragraph.add(this.messageReturn(null));
                    }
                    this.addTableBodyCell(table, paragraph, Element.ALIGN_LEFT, 1);

                    // lessons
                    paragraph = new Paragraph();
                    paragraph.setFont(TABLE_BODY_BOLD_FONT);
                    paragraph.add(this.getText("summaries.project.reporting.nextuser.lessons"));
                    paragraph.setFont(TABLE_BODY_FONT);

                    if (projectNextUser != null) {
                        paragraph.add(this.messageReturn(projectNextUser.getLessonsImplications()));
                    } else {
                        paragraph.add(this.messageReturn(null));
                    }
                    this.addTableBodyCell(table, paragraph, Element.ALIGN_LEFT, 1);

                    counter++;
                    document.add(table);
                    paragraph = new Paragraph();
                    paragraph.add(Chunk.NEWLINE);
                    document.add(paragraph);
                }
            }

            // **********************************************************************************
            // *************************** Project HighLights****************************************
            // **********************************************************************************
            counter = 1;
            document.newPage();
            paragraph = new Paragraph();
            paragraph.setFont(HEADING3_FONT);
            paragraph.add(number + ".4 " + this.getText("summaries.project.reporting.highlight.principal"));
            document.add(paragraph);

            paragraph = new Paragraph();
            paragraph.add(Chunk.NEWLINE);
            document.add(paragraph);

            for (ProjectHighligths projectHighLigth : project.getHighlights()) {
                table = new PdfPTable(2);
                table.setLockedWidth(true);
                table.setTotalWidth(480);

                paragraph = new Paragraph();
                paragraph.setFont(TABLE_HEADER_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight",
                        new String[] { String.valueOf(counter) }));
                this.addTableHeaderCellColspan(table, paragraph, 2);

                // title
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.title"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    paragraph.add(this.messageReturn(projectHighLigth.getTitle()));
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableColSpanCell(table, paragraph, Element.ALIGN_LEFT, 1, 2);

                // author
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.author"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    paragraph.add(this.messageReturn(projectHighLigth.getAuthor()));
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableBodyCell(table, paragraph, Element.ALIGN_LEFT, 1);

                // subject
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.subject"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    paragraph.add(this.messageReturn(projectHighLigth.getSubject()));
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableBodyCell(table, paragraph, Element.ALIGN_LEFT, 1);

                // publisher
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.publisher"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    paragraph.add(this.messageReturn(projectHighLigth.getPublisher()));
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableBodyCell(table, paragraph, Element.ALIGN_LEFT, 1);

                // year
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.year"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    paragraph.add(this.messageReturn(String.valueOf(projectHighLigth.getYear())));
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableBodyCell(table, paragraph, Element.ALIGN_LEFT, 1);

                // project highlight types
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.types"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    for (ProjectHighligthsTypes projectHighLigthTypes : projectHighLigth
                            .getProjectHighligthsTypeses()) {
                        paragraph.add(this.messageReturn("\n" + ProjectHighlightsType
                                .getEnum(String.valueOf(projectHighLigthTypes.getIdType())).getDescription()));
                    }
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableBodyCell(table, paragraph, Element.ALIGN_LEFT, 1);

                // project images
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add("Image");

                if (projectHighLigth != null) {
                    Image global;
                    try {
                        if (projectHighLigth.getPhoto() != null) {
                            String urlImage = config.getDownloadURL() + "/" + this.getHighlightsImagesUrlPath()
                                    + projectHighLigth.getPhoto();
                            urlImage = urlImage.replace(" ", "%20");
                            global = Image.getInstance(urlImage);

                        } else {
                            global = null;
                        }

                        if (global != null) {

                            float documentWidth = document.getPageSize().getWidth() - document.leftMargin()
                                    - document.rightMargin();
                            float documentHeight = document.getPageSize().getHeight() - document.topMargin()
                                    - document.bottomMargin();
                            global.scaleToFit((float) (documentWidth * 0.4), global.getHeight());
                            global.setAlignment(Element.ALIGN_CENTER);

                            this.addTableBodyCell(table, global, Element.ALIGN_LEFT, 1);

                        }

                    } catch (MalformedURLException e) {

                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();

                    }

                } else {
                    paragraph.add(this.messageReturn(null));
                }

                // project start date
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.startDate"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    paragraph.add(this.messageReturn(String.valueOf(projectHighLigth.getStartDate())));
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableBodyCell(table, paragraph, Element.ALIGN_LEFT, 1);

                // project end date
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.endDate"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    paragraph.add(this.messageReturn(String.valueOf(projectHighLigth.getEndDate())));
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableBodyCell(table, paragraph, Element.ALIGN_LEFT, 1);

                // Its Global
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.itsglobal"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    if (projectHighLigth.isIsGlobal()) {
                        paragraph.add("Yes");
                    } else {
                        paragraph.add("No");
                    }
                    ;
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableColSpanCell(table, paragraph, Element.ALIGN_LEFT, 1, 2);

                // Country
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.country"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null && projectHighLigth.getProjectHighligthsCountries() != null) {
                    for (ProjectHighligthsCountry country : projectHighLigth.getProjectHighligthsCountries()) {
                        paragraph.add(locationManager.getCountry(country.getIdCountry()).getName() + "\n");
                    }
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableBodyCell(table, paragraph, Element.ALIGN_LEFT, 1);
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.keywords"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    paragraph.add(this.messageReturn(projectHighLigth.getKeywords()));
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableColSpanCell(table, paragraph, Element.ALIGN_LEFT, 1, 2);

                // description
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.description"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    paragraph.add(this.messageReturn(projectHighLigth.getDescription()));
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableColSpanCell(table, paragraph, Element.ALIGN_LEFT, 1, 2);

                // Introduction / Objectives
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.introduction"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    paragraph.add(this.messageReturn(projectHighLigth.getObjectives()));
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableColSpanCell(table, paragraph, Element.ALIGN_LEFT, 1, 2);

                // Results
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.results"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    paragraph.add(this.messageReturn(projectHighLigth.getResults()));
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableColSpanCell(table, paragraph, Element.ALIGN_LEFT, 1, 2);

                // Partners
                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.partners"));
                paragraph.setFont(TABLE_BODY_FONT);
                if (projectHighLigth != null) {
                    paragraph.add(this.messageReturn(projectHighLigth.getPartners()));
                } else {
                    paragraph.add(this.messageReturn(null));
                }
                this.addTableColSpanCell(table, paragraph, Element.ALIGN_LEFT, 1, 2);

                // Links

                paragraph = new Paragraph();
                paragraph.setFont(TABLE_BODY_BOLD_FONT);
                paragraph.add(this.getText("summaries.project.reporting.highlight.links"));
                paragraph.setFont(TABLE_BODY_FONT);
                paragraph.add(this.messageReturn(projectHighLigth.getLinks()));

                this.addTableColSpanCell(table, paragraph, Element.ALIGN_LEFT, 1, 2);

                document.add(table);
                document.newPage();
            }

        }
    } catch (DocumentException e) {
        LOG.error("There was an error trying to add the project title to the project summary pdf", e);
    }
}

From source file:org.goodoldai.jeff.report.pdf.PDFImageChunkBuilder.java

License:Open Source License

/**
 * This method transforms an image explanation chunk into a PDF report
 * piece and writes this piece into the provided output stream which is, in 
 * this case, an instance of com.lowagie.text.Document. The method first
 * collects all general chunk data (context, rule, group, tags) and inserts 
 * them into the report, and then retrieves the chunk content. Since the 
 * content is, in this case, an ImageData instance, the image it relates to 
 * (caption and URL) gets inserted into the report. If the image caption is 
 * missing, it doesn't get inserted into the report.
 *
 * @param echunk image explanation chunk that needs to be transformed
 * @param stream output stream to which the transformed chunk will be
 * written as output (in this case com.lowagie.text.Document)
 * @param insertHeaders denotes if chunk headers should be inserted into the
 * report (true) or not (false)//www. j  a va2 s  .co  m
 *
 * @throws org.goodoldai.jeff.explanation.ExplanationException if any of the arguments are
 * null, if the entered chunk is not an ImageExplanationChunk instance or 
 * if the entered output stream type is not com.lowagie.text.Document
 */
public void buildReportChunk(ExplanationChunk echunk, Object stream, boolean insertHeaders) {
    if (echunk == null) {
        throw new ExplanationException("The entered chunk must not be null");
    }

    if (stream == null) {
        throw new ExplanationException("The entered stream must not be null");
    }

    if (!(echunk instanceof ImageExplanationChunk)) {
        throw new ExplanationException("The entered chunk must be an ImageExplanationChunk instance");
    }

    if (!(stream instanceof com.lowagie.text.Document)) {
        throw new ExplanationException("The entered stream must be a com.lowagie.text.Document instance");
    }

    com.lowagie.text.Document doc = ((com.lowagie.text.Document) stream);

    //Insert general chunk data
    if (insertHeaders)
        PDFChunkUtility.insertChunkHeader(echunk, doc);

    try {
        //Insert content - in this case an image
        ImageData imdata = (ImageData) (echunk.getContent());

        //Get image data
        Image img = Image.getInstance(getClass().getResource(imdata.getURL()));

        //Scale the image in order to fit the page
        img.scaleToFit(doc.getPageSize().getRight(doc.leftMargin() + doc.rightMargin()),
                doc.getPageSize().getTop(doc.topMargin() + doc.bottomMargin()));

        //Add image
        doc.add(img);

        //If a caption is present, insert it below the image
        if ((imdata.getCaption() != null) && (!imdata.getCaption().equals(""))) {
            doc.add(new Paragraph("IMAGE: " + imdata.getCaption()));
        }
    } catch (NullPointerException e) {
        throw new ExplanationException(
                "The image '" + ((ImageData) (echunk.getContent())).getURL() + "' could not be found");
    } catch (Exception e) {
        throw new ExplanationException(e.getMessage());
    }

}

From source file:org.goodoldai.jeff.report.pdf.RTFImageChunkBuilder.java

License:Open Source License

/**
 * This method transforms an image explanation chunk into a PDF report
 * piece and writes this piece into the provided output stream which is, in 
 * this case, an instance of com.lowagie.text.Document. The method first
 * collects all general chunk data (context, rule, group, tags) and inserts 
 * them into the report, and then retrieves the chunk content. Since the 
 * content is, in this case, an ImageData instance, the image it relates to 
 * (caption and URL) gets inserted into the report. If the image caption is 
 * missing, it doesn't get inserted into the report.
 *
 * @param echunk image explanation chunk that needs to be transformed
 * @param stream output stream to which the transformed chunk will be
 * written as output (in this case com.lowagie.text.Document)
 * @param insertHeaders denotes if chunk headers should be inserted into the
 * report (true) or not (false)/* w  w w  .j  av a 2s  .  c  o m*/
 *
 * @throws org.goodoldai.jeff.explanation.ExplanationException if any of the arguments are
 * null, if the entered chunk is not an ImageExplanationChunk instance or 
 * if the entered output stream type is not com.lowagie.text.Document
 */
public void buildReportChunk(ExplanationChunk echunk, Object stream, boolean insertHeaders) {
    if (echunk == null) {
        throw new ExplanationException("The entered chunk must not be null");
    }

    if (stream == null) {
        throw new ExplanationException("The entered stream must not be null");
    }

    if (!(echunk instanceof ImageExplanationChunk)) {
        throw new ExplanationException("The entered chunk must be an ImageExplanationChunk instance");
    }

    if (!(stream instanceof com.lowagie.text.Document)) {
        throw new ExplanationException("The entered stream must be a com.lowagie.text.Document instance");
    }

    com.lowagie.text.Document doc = ((com.lowagie.text.Document) stream);

    //Insert general chunk data
    if (insertHeaders)
        RTFChunkUtility.insertChunkHeader(echunk, doc);

    try {
        //Insert content - in this case an image
        ImageData imdata = (ImageData) (echunk.getContent());

        //Get image data
        Image img = Image.getInstance(getClass().getResource(imdata.getURL()));

        //Scale the image in order to fit the page
        img.scaleToFit(doc.getPageSize().getRight(doc.leftMargin() + doc.rightMargin()),
                doc.getPageSize().getTop(doc.topMargin() + doc.bottomMargin()));

        //Add image
        doc.add(img);

        //If a caption is present, insert it below the image
        if ((imdata.getCaption() != null) && (!imdata.getCaption().equals(""))) {
            doc.add(new Paragraph("IMAGE: " + imdata.getCaption()));
        }
    } catch (NullPointerException e) {
        throw new ExplanationException(
                "The image '" + ((ImageData) (echunk.getContent())).getURL() + "' could not be found");
    } catch (Exception e) {
        throw new ExplanationException(e.getMessage());
    }

}

From source file:org.inbio.modeling.core.manager.impl.ExportManagerImpl.java

License:Open Source License

private void addImageSection(Document d, String mapName, Long currentSessionId)
        throws BadElementException, MalformedURLException, IOException, DocumentException {

    Image mapImage = Image.getInstance(mapsHome + mapName + "_T_" + currentSessionId + ".png");
    mapImage.scaleToFit(550, 413);
    mapImage.setAlignment(Image.ALIGN_LEFT);

    // scale//from   ww w . j  a v  a 2s.c o m
    Image scaleImage = Image.getInstance(mapsHome + "scale.jpg");
    scaleImage.scaleToFit(30, 150);
    scaleImage.setAlignment(Image.ALIGN_RIGHT);

    Paragraph images = new Paragraph();
    images.setAlignment(Paragraph.ALIGN_RIGHT);

    //upper scale leyend
    images.add(new Chunk(this.getI18nString("pdfReport.scaleUpper") + "\n\n\n\n\n\n\n",
            new Font(Font.COURIER, 8, Font.BOLDITALIC)));
    // Map
    images.add(new Chunk(mapImage, 1F, 1F));
    // Scale
    images.add(new Chunk(scaleImage, 1F, 1F));
    // lower scale leyend
    images.add(new Chunk("\n" + this.getI18nString("pdfReport.scaleLower") + "\n",
            new Font(Font.COURIER, 8, Font.BOLDITALIC)));

    d.add(images);
}

From source file:org.jaffa.modules.printing.services.FormPrintEngineIText.java

License:Open Source License

/** Print an iText image */
private void printImage(Image image, PdfContentByte cb, float x1, float y1, float x2, float y2, int alignment,
        int fitMethod, float rotate) throws DocumentException {
    if (image != null) {
        float boxWidth = Math.abs(x2 - x1) + 1;
        float boxHeight = Math.abs(y2 - y1) + 1;
        log.debug("Print Image (Size w=" + image.getPlainWidth() + ",h=" + image.getPlainHeight()
                + ") wthin BOX (w=" + boxWidth + ",h=" + boxHeight + ") FitMethod = " + fitMethod);

        // Clip the image based on the bounding box
        if (fitMethod == FIT_METHOD_CLIP) {
            if ((boxWidth < image.getPlainWidth()) || (boxHeight < image.getPlainHeight())) {
                // @TODO - Clip image
                log.warn("IMAGE CLIPPING REQUIRED, but not implemented - default to 'SCALE'...");
                fitMethod = FIT_METHOD_SCALE;
            }//from   ww w. j  a v a  2 s .c om
        }
        // Stretch/shrink both the X/Y to fit the bounding box
        if (fitMethod == FIT_METHOD_FILL) {
            log.debug("Scale image to fill box");
            image.scaleToFit(x2 - x1, y2 - y1);
        }
        // Stretch/shrink preserving the aspect ratio to fit the bounding box
        if (fitMethod == FIT_METHOD_SCALE) {
            float multipler = Math.min(boxWidth / image.getPlainWidth(), boxHeight / image.getPlainHeight());
            log.debug("Need to scale image by " + (Math.floor(multipler * 10000) / 100) + "%");
            image.scalePercent(multipler * 100);
        }
        log.debug("Print image at (" + x1 + "," + y1 + ")");
        image.setAbsolutePosition(x1, y1);
        image.setRotationDegrees(rotate);
        cb.addImage(image);
        //Phrase text = new Phrase(new Chunk(image, 0, 0));
        //ColumnText ct = new ColumnText(cb);
        //ct.setSimpleColumn(text, x1, y1, x2, y2, 10, alignment);
        //ct.go();
    }
}

From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java

License:Open Source License

/**
 * This method is for setting the properties of watermark Image.
 * /*w  w  w. j a v a  2  s .c  o m*/
 * @param pdfContentByte
 * @param pageWidth
 * @param pageHeight
 * @param watermarkBean
 */
private void decoratePdfWatermarkImage(PdfContentByte pdfContentByte, int pageWidth, int pageHeight,
        WatermarkBean watermarkBean) {
    PdfGState pdfGState = new PdfGState();
    final float OPACITY = 0.3f;
    float absPosX;
    float absPosY;
    try {
        if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_IMAGE)) {
            Image watermarkImage = Image.getInstance(watermarkBean.getFileImage());
            if (watermarkImage != null) {
                pdfGState.setFillOpacity(OPACITY);
                pdfContentByte.setGState(pdfGState);
                float height = watermarkImage.getPlainHeight();
                float width = watermarkImage.getPlainWidth();
                int diagonal = (int) Math.sqrt((pageWidth * pageWidth) + (pageHeight * pageHeight));
                int pivotPoint = (diagonal - (int) width) / 2;
                float angle = (float) Math.atan((float) pageHeight / pageWidth);
                absPosX = (float) (pivotPoint * pageWidth) / diagonal;
                absPosY = (float) (pivotPoint * pageHeight) / diagonal;
                watermarkImage.setAbsolutePosition(absPosX, absPosY);
                if ((pageWidth / 2) < width) {
                    watermarkImage.scaleToFit(pageWidth / 2, pageHeight / 2);
                } else {
                    watermarkImage.scaleToFit(width, height);
                }
                pdfContentByte.addImage(watermarkImage);
            }

        }

    } catch (BadElementException badElementException) {

        LOG.error("WatermarkDecoratorImpl  Error found: " + badElementException.getMessage());
    } catch (DocumentException documentException) {

        LOG.error("WatermarkDecoratorImpl Error found: " + documentException.getMessage());
    }

}

From source file:org.mapfish.print.PDFUtils.java

License:Open Source License

/**
 * Gets an iText image with a cache that uses PdfTemplates to re-use the same
 * bitmap content multiple times in order to reduce the file size.
 *//*  w w w.  ja  v a  2s  .com*/
public static Image getImage(RenderingContext context, URI uri, float w, float h)
        throws IOException, DocumentException {
    //Check the image is not already used in the PDF file.
    //
    //This part is not protected against multi-threads... worst case, a single image can
    //be twice in the PDF, if used more than one time. But since only one !map
    //block is dealed with at a time, this should not happen
    Map<URI, PdfTemplate> cache = context.getTemplateCache();
    PdfTemplate template = cache.get(uri);
    if (template == null) {
        Image content = getImageDirect(context, uri);
        content.setAbsolutePosition(0, 0);
        final PdfContentByte dc = context.getDirectContent();
        synchronized (context.getPdfLock()) { //protect against parallel writing on the PDF file
            template = dc.createTemplate(content.getPlainWidth(), content.getPlainHeight());
            template.addImage(content);
        }
        cache.put(uri, template);
    }

    //fix the size/aspect ratio of the image in function of what is specified by the user
    if (w == 0.0f) {
        if (h == 0.0f) {
            w = template.getWidth();
            h = template.getHeight();
        } else {
            w = h / template.getHeight() * template.getWidth();
        }
    } else {
        if (h == 0.0f) {
            h = w / template.getWidth() * template.getHeight();
        }
    }

    final Image result = Image.getInstance(template);
    result.scaleToFit(w, h);
    return result;
}

From source file:org.nuxeo.dam.pdf.export.PDFCreator.java

License:Open Source License

public boolean createPDF(String title, OutputStream out) throws ClientException {
    try {/*from  ww w  .  j a va 2  s . co m*/
        Document document = new Document();
        PdfWriter.getInstance(document, out);

        document.addTitle(title);
        document.addAuthor(Functions.principalFullName(currentUser));
        document.addCreator(Functions.principalFullName(currentUser));

        document.open();

        document.add(new Paragraph("\n\n\n\n\n\n\n\n\n\n"));
        Font titleFont = new Font(Font.HELVETICA, 36, Font.BOLD);
        Paragraph titleParagraph = new Paragraph(title, titleFont);
        titleParagraph.setAlignment(Element.ALIGN_CENTER);
        document.add(titleParagraph);
        Font authorFont = new Font(Font.HELVETICA, 20);
        Paragraph authorParagraph = new Paragraph("By " + Functions.principalFullName(currentUser), authorFont);
        authorParagraph.setAlignment(Element.ALIGN_CENTER);
        document.add(authorParagraph);

        document.newPage();

        boolean foundOnePicture = false;
        for (DocumentModel doc : docs) {
            if (!doc.hasSchema(PICTURE_SCHEMA)) {
                continue;
            }
            foundOnePicture = true;

            PictureResourceAdapter picture = doc.getAdapter(PictureResourceAdapter.class);
            Blob blob = picture.getPictureFromTitle(ORIGINAL_JPEG_VIEW);
            Rectangle pageSize = document.getPageSize();
            if (blob != null) {
                Paragraph imageTitle = new Paragraph(doc.getTitle(), font);
                imageTitle.setAlignment(Paragraph.ALIGN_CENTER);
                document.add(imageTitle);

                Image image = Image.getInstance(blob.getByteArray());
                image.scaleToFit(pageSize.getWidth() - 20, pageSize.getHeight() - 100);
                image.setAlignment(Image.MIDDLE);
                Paragraph imageParagraph = new Paragraph();
                imageParagraph.add(image);
                imageParagraph.setAlignment(Paragraph.ALIGN_MIDDLE);
                document.add(imageParagraph);

                document.newPage();
            }
        }
        if (foundOnePicture) {
            document.close();
            return true;
        }
    } catch (Exception e) {
        throw ClientException.wrap(e);
    }
    return false;
}

From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java

License:Open Source License

private void handleGroup(PipelineContext pipelineContext, GroupContext groupContext, List<Element> statements,
        FunctionLibrary functionLibrary, PdfReader reader) throws DocumentException, IOException {

    final NodeInfo contextNode = (NodeInfo) groupContext.contextNodeSet.get(groupContext.contextPosition - 1);
    final Map<String, ValueRepresentation> variableToValueMap = new HashMap<String, ValueRepresentation>();

    variableToValueMap.put("page-count", new Int64Value(reader.getNumberOfPages()));
    variableToValueMap.put("page-number", new Int64Value(groupContext.pageNumber));
    variableToValueMap.put("page-height", new FloatValue(groupContext.pageHeight));

    // Iterate through statements
    for (final Element currentElement : statements) {

        // Check whether this statement applies to the current page
        final String elementPage = currentElement.attributeValue("page");
        if ((elementPage != null) && !Integer.toString(groupContext.pageNumber).equals(elementPage))
            continue;

        final NamespaceMapping namespaceMapping = new NamespaceMapping(
                Dom4jUtils.getNamespaceContextNoDefault(currentElement));

        final String elementName = currentElement.getName();
        if (elementName.equals("group")) {
            // Handle group

            final GroupContext newGroupContext = new GroupContext(groupContext);

            final String ref = currentElement.attributeValue("ref");
            if (ref != null) {
                final NodeInfo newContextNode = (NodeInfo) XPathCache.evaluateSingle(
                        groupContext.contextNodeSet, groupContext.contextPosition, ref, namespaceMapping,
                        variableToValueMap, functionLibrary, null, null,
                        (LocationData) currentElement.getData());

                if (newContextNode == null)
                    continue;

                newGroupContext.contextNodeSet = Collections.singletonList((Item) newContextNode);
                newGroupContext.contextPosition = 1;
            }//w w w.  j a va2  s .c  om

            final String offsetXString = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-x"));
            if (offsetXString != null) {
                newGroupContext.offsetX = groupContext.offsetX + Float.parseFloat(offsetXString);
            }

            final String offsetYString = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-y"));
            if (offsetYString != null) {
                newGroupContext.offsetY = groupContext.offsetY + Float.parseFloat(offsetYString);
            }

            final String fontPitch = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement,
                    currentElement.attributeValue("font-pitch"));
            if (fontPitch != null)
                newGroupContext.fontPitch = Float.parseFloat(fontPitch);

            final String fontFamily = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement,
                    currentElement.attributeValue("font-family"));
            if (fontFamily != null)
                newGroupContext.fontFamily = fontFamily;

            final String fontSize = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, currentElement.attributeValue("font-size"));
            if (fontSize != null)
                newGroupContext.fontSize = Float.parseFloat(fontSize);

            handleGroup(pipelineContext, newGroupContext, Dom4jUtils.elements(currentElement), functionLibrary,
                    reader);

        } else if (elementName.equals("repeat")) {
            // Handle repeat

            final String nodeset = currentElement.attributeValue("nodeset");
            final List iterations = XPathCache.evaluate(groupContext.contextNodeSet,
                    groupContext.contextPosition, nodeset, namespaceMapping, variableToValueMap,
                    functionLibrary, null, null, (LocationData) currentElement.getData());

            final String offsetXString = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-x"));
            final String offsetYString = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-y"));
            final float offsetIncrementX = (offsetXString == null) ? 0 : Float.parseFloat(offsetXString);
            final float offsetIncrementY = (offsetYString == null) ? 0 : Float.parseFloat(offsetYString);

            for (int iterationIndex = 1; iterationIndex <= iterations.size(); iterationIndex++) {

                final GroupContext newGroupContext = new GroupContext(groupContext);

                newGroupContext.contextNodeSet = iterations;
                newGroupContext.contextPosition = iterationIndex;

                newGroupContext.offsetX = groupContext.offsetX + (iterationIndex - 1) * offsetIncrementX;
                newGroupContext.offsetY = groupContext.offsetY + (iterationIndex - 1) * offsetIncrementY;

                handleGroup(pipelineContext, newGroupContext, Dom4jUtils.elements(currentElement),
                        functionLibrary, reader);
            }
        } else if (elementName.equals("field")) {

            final String fieldNameStr = currentElement.attributeValue("acro-field-name");

            if (fieldNameStr != null) {
                final String value = currentElement.attributeValue("value") == null
                        ? currentElement.attributeValue("ref")
                        : currentElement.attributeValue("value");
                // Get value from instance

                final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet,
                        groupContext.contextPosition, value, namespaceMapping, variableToValueMap,
                        functionLibrary, null, null, (LocationData) currentElement.getData());
                final String fieldName = XPathCache.evaluateAsString(groupContext.contextNodeSet,
                        groupContext.contextPosition, fieldNameStr, namespaceMapping, variableToValueMap,
                        functionLibrary, null, null, (LocationData) currentElement.getData());
                groupContext.acroFields.setField(fieldName, text);

            } else {
                // Handle field

                final String leftAttribute = currentElement.attributeValue("left") == null
                        ? currentElement.attributeValue("left-position")
                        : currentElement.attributeValue("left");
                final String topAttribute = currentElement.attributeValue("top") == null
                        ? currentElement.attributeValue("top-position")
                        : currentElement.attributeValue("top");

                final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, leftAttribute);
                final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, topAttribute);

                final String size = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, currentElement.attributeValue("size"));
                final String value = currentElement.attributeValue("value") == null
                        ? currentElement.attributeValue("ref")
                        : currentElement.attributeValue("value");

                final FontAttributes fontAttributes = getFontAttributes(currentElement, pipelineContext,
                        groupContext, variableToValueMap, contextNode);

                // Output value
                final BaseFont baseFont = BaseFont.createFont(fontAttributes.fontFamily, BaseFont.CP1252,
                        BaseFont.NOT_EMBEDDED);
                groupContext.contentByte.beginText();
                {
                    groupContext.contentByte.setFontAndSize(baseFont, fontAttributes.fontSize);

                    final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX;
                    final float yPosition = groupContext.pageHeight
                            - (Float.parseFloat(topPosition) + groupContext.offsetY);

                    // Get value from instance
                    final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet,
                            groupContext.contextPosition, value, namespaceMapping, variableToValueMap,
                            functionLibrary, null, null, (LocationData) currentElement.getData());

                    // Iterate over characters and print them
                    if (text != null) {
                        int len = Math.min(text.length(),
                                (size != null) ? Integer.parseInt(size) : Integer.MAX_VALUE);
                        for (int j = 0; j < len; j++)
                            groupContext.contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER,
                                    text.substring(j, j + 1),
                                    xPosition + ((float) j) * fontAttributes.fontPitch, yPosition, 0);
                    }
                }
                groupContext.contentByte.endText();
            }
        } else if (elementName.equals("barcode")) {
            // Handle barcode

            final String leftAttribute = currentElement.attributeValue("left");
            final String topAttribute = currentElement.attributeValue("top");

            final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, leftAttribute);
            final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, topAttribute);

            //                final String size = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("size"));
            final String value = currentElement.attributeValue("value") == null
                    ? currentElement.attributeValue("ref")
                    : currentElement.attributeValue("value");
            final String type = currentElement.attributeValue("type") == null ? "CODE39"
                    : currentElement.attributeValue("type");
            final float height = currentElement.attributeValue("height") == null ? 10.0f
                    : Float.parseFloat(currentElement.attributeValue("height"));

            final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX;
            final float yPosition = groupContext.pageHeight
                    - (Float.parseFloat(topPosition) + groupContext.offsetY);
            final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet,
                    groupContext.contextPosition, value, namespaceMapping, variableToValueMap, functionLibrary,
                    null, null, (LocationData) currentElement.getData());

            final FontAttributes fontAttributes = getFontAttributes(currentElement, pipelineContext,
                    groupContext, variableToValueMap, contextNode);
            final BaseFont baseFont = BaseFont.createFont(fontAttributes.fontFamily, BaseFont.CP1252,
                    BaseFont.NOT_EMBEDDED);

            final Barcode barcode = createBarCode(type);
            barcode.setCode(text);
            barcode.setBarHeight(height);
            barcode.setFont(baseFont);
            barcode.setSize(fontAttributes.fontSize);
            final Image barcodeImage = barcode.createImageWithBarcode(groupContext.contentByte, null, null);
            barcodeImage.setAbsolutePosition(xPosition, yPosition);
            groupContext.contentByte.addImage(barcodeImage);
        } else if (elementName.equals("image")) {
            // Handle image

            // Read image
            final Image image;
            {
                final String hrefAttribute = currentElement.attributeValue("href");
                final String inputName = ProcessorImpl.getProcessorInputSchemeInputName(hrefAttribute);
                if (inputName != null) {
                    // Read the input
                    final ByteArrayOutputStream os = new ByteArrayOutputStream();
                    readInputAsSAX(pipelineContext, inputName,
                            new BinaryTextXMLReceiver(null, os, true, false, null, false, false, null, false));

                    // Create the image
                    image = Image.getInstance(os.toByteArray());
                } else {
                    // Read and create the image
                    final URL url = URLFactory.createURL(hrefAttribute);

                    // Use ConnectionResult so that header/session forwarding takes place
                    final ConnectionResult connectionResult = new Connection().open(
                            NetUtils.getExternalContext(), new IndentedLogger(logger, ""), false,
                            Connection.Method.GET.name(), url, null, null, null, null,
                            Connection.getForwardHeaders());

                    if (connectionResult.statusCode != 200) {
                        connectionResult.close();
                        throw new OXFException("Got invalid return code while loading image: "
                                + url.toExternalForm() + ", " + connectionResult.statusCode);
                    }

                    // Make sure things are cleaned-up not too late
                    pipelineContext.addContextListener(new PipelineContext.ContextListener() {
                        public void contextDestroyed(boolean success) {
                            connectionResult.close();
                        }
                    });

                    // Here we decide to copy to temp file and load as a URL. We could also provide bytes directly.
                    final String tempURLString = NetUtils.inputStreamToAnyURI(
                            connectionResult.getResponseInputStream(), NetUtils.REQUEST_SCOPE);
                    image = Image.getInstance(URLFactory.createURL(tempURLString));
                }
            }

            final String fieldNameStr = currentElement.attributeValue("acro-field-name");
            if (fieldNameStr != null) {
                // Use field as placeholder

                final String fieldName = XPathCache.evaluateAsString(groupContext.contextNodeSet,
                        groupContext.contextPosition, fieldNameStr, namespaceMapping, variableToValueMap,
                        functionLibrary, null, null, (LocationData) currentElement.getData());
                final float[] positions = groupContext.acroFields.getFieldPositions(fieldName);

                if (positions != null) {
                    final Rectangle rectangle = new Rectangle(positions[1], positions[2], positions[3],
                            positions[4]);

                    // This scales the image so that it fits in the box (but the aspect ratio is not changed)
                    image.scaleToFit(rectangle.getWidth(), rectangle.getHeight());

                    final float yPosition = positions[2] + rectangle.getHeight() - image.getScaledHeight();
                    image.setAbsolutePosition(
                            positions[1] + (rectangle.getWidth() - image.getScaledWidth()) / 2, yPosition);

                    // Add image
                    groupContext.contentByte.addImage(image);
                }

            } else {
                // Use position, etc.
                final String leftAttribute = currentElement.attributeValue("left");
                final String topAttribute = currentElement.attributeValue("top");
                final String scalePercentAttribute = currentElement.attributeValue("scale-percent");
                final String dpiAttribute = currentElement.attributeValue("dpi");

                final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, leftAttribute);
                final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, topAttribute);

                final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX;
                final float yPosition = groupContext.pageHeight
                        - (Float.parseFloat(topPosition) + groupContext.offsetY);

                final String scalePercent = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, scalePercentAttribute);
                final String dpi = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, dpiAttribute);

                // Set image parameters
                image.setAbsolutePosition(xPosition, yPosition);
                if (scalePercent != null) {
                    image.scalePercent(Float.parseFloat(scalePercent));
                }
                if (dpi != null) {
                    final int dpiInt = Integer.parseInt(dpi);
                    image.setDpi(dpiInt, dpiInt);
                }

                // Add image
                groupContext.contentByte.addImage(image);
            }
        } else {
            // NOP
        }
    }
}