Example usage for com.lowagie.text Image scalePercent

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

Introduction

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

Prototype

public void scalePercent(float percent) 

Source Link

Document

Scale the image to a certain percentage.

Usage

From source file:net.bull.javamelody.PdfJavaInformationsReport.java

License:Apache License

private void writeSummary(JavaInformations javaInformations) throws BadElementException, IOException {
    addCell(getString("Host") + ':');
    currentTable.addCell(new Phrase(javaInformations.getHost(), boldCellFont));
    addCell(getString("memoire_utilisee") + ':');
    final MemoryInformations memoryInformations = javaInformations.getMemoryInformations();
    final long usedMemory = memoryInformations.getUsedMemory();
    final long maxMemory = memoryInformations.getMaxMemory();
    final Phrase memoryPhrase = new Phrase(
            integerFormat.format(usedMemory / 1024 / 1024) + ' ' + getString("Mo") + DIVIDE
                    + integerFormat.format(maxMemory / 1024 / 1024) + ' ' + getString("Mo") + BAR_SEPARATOR,
            cellFont);/* w w  w . j  ava2s.  co  m*/
    final Image memoryImage = Image
            .getInstance(Bar.toBarWithAlert(memoryInformations.getUsedMemoryPercentage()), null);
    memoryImage.scalePercent(50);
    memoryPhrase.add(new Chunk(memoryImage, 0, 0));
    currentTable.addCell(memoryPhrase);
    if (javaInformations.getSessionCount() >= 0) {
        addCell(getString("nb_sessions_http") + ':');
        addCell(integerFormat.format(javaInformations.getSessionCount()));
    }
    addCell(getString("nb_threads_actifs") + "\n(" + getString("Requetes_http_en_cours") + "):");
    addCell(integerFormat.format(javaInformations.getActiveThreadCount()));
    if (!noDatabase) {
        addCell(getString("nb_connexions_actives") + ':');
        addCell(integerFormat.format(javaInformations.getActiveConnectionCount()));
        addCell(getString("nb_connexions_utilisees") + "\n(" + getString("ouvertes") + "):");
        final int usedConnectionCount = javaInformations.getUsedConnectionCount();
        final int maxConnectionCount = javaInformations.getMaxConnectionCount();
        if (maxConnectionCount <= 0) {
            addCell(integerFormat.format(usedConnectionCount));
        } else {
            final Phrase usedConnectionCountPhrase = new Phrase(integerFormat.format(usedConnectionCount)
                    + DIVIDE + integerFormat.format(maxConnectionCount) + BAR_SEPARATOR, cellFont);
            final Image usedConnectionCountImage = Image
                    .getInstance(Bar.toBarWithAlert(javaInformations.getUsedConnectionPercentage()), null);
            usedConnectionCountImage.scalePercent(50);
            usedConnectionCountPhrase.add(new Chunk(usedConnectionCountImage, 0, 0));
            currentTable.addCell(usedConnectionCountPhrase);
        }
    }
    if (javaInformations.getSystemLoadAverage() >= 0) {
        addCell(getString("Charge_systeme") + ':');
        addCell(decimalFormat.format(javaInformations.getSystemLoadAverage()));
    }
}

From source file:net.bull.javamelody.PdfJavaInformationsReport.java

License:Apache License

private void writeDetails(JavaInformations javaInformations) throws BadElementException, IOException {
    addCell(getString("OS") + ':');
    final Phrase osPhrase = new Phrase("", cellFont);
    final String osIconName = HtmlJavaInformationsReport.getOSIconName(javaInformations.getOS());
    final String separator = "   ";
    if (osIconName != null) {
        final Image osImage = PdfDocumentFactory.getImage("servers/" + osIconName);
        osImage.scalePercent(40);
        osPhrase.add(new Chunk(osImage, 0, 0));
        osPhrase.add(separator);/*from w  ww .ja v  a  2  s . co  m*/
    }
    osPhrase.add(javaInformations.getOS() + " (" + javaInformations.getAvailableProcessors() + ' '
            + getString("coeurs") + ')');
    currentTable.addCell(osPhrase);
    addCell(getString("Java") + ':');
    addCell(javaInformations.getJavaVersion());
    addCell(getString("JVM") + ':');
    final Phrase jvmVersionPhrase = new Phrase(javaInformations.getJvmVersion(), cellFont);
    if (javaInformations.getJvmVersion().contains("Client")) {
        jvmVersionPhrase.add(separator);
        final Image alertImage = PdfDocumentFactory.getImage("alert.png");
        alertImage.scalePercent(50);
        jvmVersionPhrase.add(new Chunk(alertImage, 0, -2));
    }
    currentTable.addCell(jvmVersionPhrase);
    addCell(getString("PID") + ':');
    addCell(javaInformations.getPID());
    if (javaInformations.getUnixOpenFileDescriptorCount() >= 0) {
        writeFileDescriptorCounts(javaInformations);
    }
    final String serverInfo = javaInformations.getServerInfo();
    if (serverInfo != null) {
        writeServerInfo(serverInfo);
        addCell(getString("Contexte_webapp") + ':');
        addCell(javaInformations.getContextPath());
    }
    addCell(getString("Demarrage") + ':');
    addCell(I18N.createDateAndTimeFormat().format(javaInformations.getStartDate()));
    addCell(getString("Arguments_JVM") + ':');
    addCell(javaInformations.getJvmArguments());
    if (javaInformations.getSessionCount() >= 0) {
        addCell(getString("httpSessionsMeanAge") + ':');
        addCell(integerFormat.format(javaInformations.getSessionMeanAgeInMinutes()));
    }
    writeTomcatInformations(javaInformations.getTomcatInformationsList());
    addCell(getString("Gestion_memoire") + ':');
    writeMemoryInformations(javaInformations.getMemoryInformations());
    if (javaInformations.getFreeDiskSpaceInTemp() >= 0) {
        // on considre que l'espace libre sur le disque dur est celui sur la partition du rpertoire temporaire
        addCell(getString("Free_disk_space") + ':');
        addCell(integerFormat.format(javaInformations.getFreeDiskSpaceInTemp() / 1024 / 1024) + ' '
                + getString("Mo"));
    }
    writeDatabaseVersionAndDataSourceDetails(javaInformations);
    if (javaInformations.isDependenciesEnabled()) {
        addCell(getString("Dependencies") + ':');
        addCell(getFormattedString("nb_dependencies", javaInformations.getDependenciesList().size()) + " ;\n"
                + javaInformations.getDependencies());
    }
    addCell("");
    addCell("");
}

From source file:net.bull.javamelody.PdfSessionInformationsReport.java

License:Apache License

private Image getCountryImage(String country) throws BadElementException, IOException {
    assert country != null;
    Image image = imagesByCountry.get(country);
    if (image == null) {
        final String fileName = "flags/" + country + ".gif";
        if (getClass().getResource(Parameters.getResourcePath(fileName)) == null) {
            return null;
        }/*from  w w  w .j ava 2 s. c o  m*/
        image = PdfDocumentFactory.getImage(fileName);
        image.scalePercent(40);
        imagesByCountry.put(country, image);
    }
    return image;
}

From source file:nl.knaw.dans.common.lang.pdf.ExtendedHtmlWorker.java

License:Apache License

public void startElement(String tag, HashMap h) {
    if (!tagsSupported.containsKey(tag))
        return;/*from   ww w  .java  2 s  .  com*/
    try {
        style.applyStyle(tag, h);
        String follow = (String) FactoryProperties.followTags.get(tag);
        if (follow != null) {
            HashMap prop = new HashMap();
            prop.put(follow, null);
            cprops.addToChain(follow, prop);
            return;
        }
        FactoryProperties.insertStyle(h);
        if (tag.equals("a")) {
            cprops.addToChain(tag, h);
            if (currentParagraph == null)
                currentParagraph = new Paragraph();
            stack.push(currentParagraph);
            currentParagraph = new Paragraph();
            return;
        }
        if (tag.equals("br")) {
            if (currentParagraph == null)
                currentParagraph = new Paragraph();
            currentParagraph.add(factoryProperties.createChunk("\n", cprops));
            return;
        }
        if (tag.equals("font") || tag.equals("span")) {
            cprops.addToChain(tag, h);
            return;
        }
        if (tag.equals("img")) {
            String src = (String) h.get("src");
            if (src == null)
                return;
            cprops.addToChain(tag, h);
            Image img = null;
            if (interfaceProps != null) {
                ImageProvider ip = (ImageProvider) interfaceProps.get("img_provider");
                if (ip != null)
                    img = ip.getImage(src, h, cprops, document);
                if (img == null) {
                    HashMap images = (HashMap) interfaceProps.get("img_static");
                    if (images != null) {
                        Image tim = (Image) images.get(src);
                        if (tim != null)
                            img = Image.getInstance(tim);
                    } else {
                        if (!src.startsWith("http")) { // relative src references only
                            String baseurl = (String) interfaceProps.get("img_baseurl");
                            if (baseurl != null) {
                                src = baseurl + src;
                                img = Image.getInstance(src);
                            }
                        }
                    }
                }
            }
            if (img == null) {
                if (!src.startsWith("http")) {
                    String path = cprops.getProperty("image_path");
                    if (path == null)
                        path = "";
                    src = new File(path, src).getPath();
                }
                img = Image.getInstance(src);
            }
            String align = (String) h.get("align");
            String width = (String) h.get("width");
            String height = (String) h.get("height");
            String before = cprops.getProperty("before");
            String after = cprops.getProperty("after");
            if (before != null)
                img.setSpacingBefore(Float.parseFloat(before));
            if (after != null)
                img.setSpacingAfter(Float.parseFloat(after));
            float wp = lengthParse(width, (int) img.getWidth());
            float lp = lengthParse(height, (int) img.getHeight());
            if (wp > 0 && lp > 0)
                img.scalePercent(wp > lp ? lp : wp);
            else if (wp > 0)
                img.scalePercent(wp);
            else if (lp > 0)
                img.scalePercent(lp);
            img.setWidthPercentage(0);
            if (align != null) {
                endElement("p");
                int ralign = Image.MIDDLE;
                if (align.equalsIgnoreCase("left"))
                    ralign = Image.LEFT;
                else if (align.equalsIgnoreCase("right"))
                    ralign = Image.RIGHT;
                img.setAlignment(ralign);
                Img i = null;
                boolean skip = false;
                if (interfaceProps != null) {
                    i = (Img) interfaceProps.get("img_interface");
                    if (i != null)
                        skip = i.process(img, h, cprops, document);
                }
                if (!skip)
                    document.add(img);
                cprops.removeChain(tag);
            } else {
                cprops.removeChain(tag);
                if (currentParagraph == null)
                    currentParagraph = FactoryProperties.createParagraph(cprops);
                currentParagraph.add(new Chunk(img, 0, 0));
            }
            return;
        }
        endElement("p");
        if (tag.equals("h1") || tag.equals("h2") || tag.equals("h3") || tag.equals("h4") || tag.equals("h5")
                || tag.equals("h6")) {
            if (!h.containsKey("size")) {
                int v = 7 - Integer.parseInt(tag.substring(1));
                h.put("size", Integer.toString(v));
            }
            cprops.addToChain(tag, h);
            return;
        }
        if (tag.equals("ul")) {
            if (pendingLI)
                endElement("li");
            skipText = true;
            cprops.addToChain(tag, h);
            com.lowagie.text.List list = new com.lowagie.text.List(false, 10);
            list.setListSymbol("\u2022");
            String indent = ((String) h.get("indent"));
            if (indent != null && indent.matches("[0-9]+")) {
                list.setSymbolIndent(Integer.valueOf(indent));
            }
            stack.push(list);
            return;
        }
        if (tag.equals("ol")) {
            if (pendingLI)
                endElement("li");
            skipText = true;
            cprops.addToChain(tag, h);
            com.lowagie.text.List list = new com.lowagie.text.List(true, 10);
            String type = ((String) h.get("type"));
            if (type != null && type.toLowerCase().equals("a")) {
                list.setLettered(true);
                list.setNumbered(false);
                list.setLowercase(type.equals("a"));
            }
            String indent = ((String) h.get("indent"));
            if (indent != null && indent.matches("[0-9]+")) {
                list.setSymbolIndent(Integer.valueOf(indent));
            }
            stack.push(list);
            return;
        }
        if (tag.equals("li")) {
            if (pendingLI)
                endElement("li");
            skipText = false;
            pendingLI = true;
            cprops.addToChain(tag, h);
            stack.push(FactoryProperties.createListItem(cprops));
            return;
        }
        if (tag.equals("div") || tag.equals("body")) {
            cprops.addToChain(tag, h);
            return;
        }
        if (tag.equals("pre")) {
            if (!h.containsKey("face")) {
                h.put("face", "Courier");
            }
            cprops.addToChain(tag, h);
            isPRE = true;
            return;
        }
        if (tag.equals("p")) {
            cprops.addToChain(tag, h);
            currentParagraph = FactoryProperties.createParagraph(h);
            return;
        }
        if (tag.equals("tr")) {
            if (pendingTR)
                endElement("tr");
            skipText = true;
            pendingTR = true;
            cprops.addToChain("tr", h);
            return;
        }
        if (tag.equals("td") || tag.equals("th")) {
            if (pendingTD)
                endElement(tag);
            skipText = false;
            pendingTD = true;
            cprops.addToChain("td", h);
            stack.push(new IncCell(tag, cprops));
            return;
        }
        if (tag.equals("table")) {
            cprops.addToChain("table", h);
            IncTable table = new IncTable(h);
            stack.push(table);
            tableState.push(new boolean[] { pendingTR, pendingTD });
            pendingTR = pendingTD = false;
            skipText = true;
            return;
        }
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

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

License:Open Source License

private void addProjectLocations() {
    Paragraph title = new Paragraph("3. " + this.getText("summaries.projectLocation.title"), HEADING3_FONT);
    Paragraph cell;/*  w  w  w . j  a  v a  2  s  . co m*/
    StringBuffer projectLocations = new StringBuffer();
    List<Location> locationList = (project.getLocations());
    PdfPTable table;
    try {
        document.newPage();
        document.add(title);

        if (project.isGlobal()) {
            Image global = Image.getInstance(config.getBaseUrl() + "/images/summaries/global-map.png");
            global.scalePercent(60f);
            global.setAlignment(Element.ALIGN_CENTER);
            document.add(global);
        } else if (locationList.isEmpty()) {
            cell = new Paragraph();
            cell.setFont(BODY_TEXT_FONT);
            cell.add(this.getText("summaries.project.empty"));
            document.add(cell);
        } else {
            table = new PdfPTable(4);

            // Set table widths
            table.setLockedWidth(true);
            table.setTotalWidth(480);
            table.setWidths(new int[] { 4, 4, 4, 5 });
            table.setHeaderRows(1);

            // Headers
            cell = new Paragraph(this.getText("summaries.projectLocation.table.level"), TABLE_HEADER_FONT);
            this.addTableHeaderCell(table, cell);

            cell = new Paragraph(this.getText("summaries.projectLocation.table.latitude"), TABLE_HEADER_FONT);
            this.addTableHeaderCell(table, cell);

            cell = new Paragraph(this.getText("summaries.projectLocation.table.longitude"), TABLE_HEADER_FONT);
            this.addTableHeaderCell(table, cell);

            cell = new Paragraph(this.getText("summaries.projectLocation.table.name"), TABLE_HEADER_FONT);
            this.addTableHeaderCell(table, cell);
            double answer = 0;
            OtherLocation otherLocation;

            for (Location location : locationList) {
                answer = 0;
                projectLocations = new StringBuffer();
                // Level
                if (location.isCountry()) {
                    projectLocations.append("Country");
                } else if (location.isRegion()) {
                    projectLocations.append("Region");
                } else if (location.isClimateSmartVillage()) {
                    projectLocations.append("CSV");
                } else if (location.isOtherLocation()) {
                    otherLocation = (OtherLocation) location;
                    projectLocations.append(otherLocation.getType().getName());
                }

                cell = new Paragraph();
                cell.setFont(TABLE_BODY_FONT);
                cell.add(projectLocations.toString());
                this.addTableBodyCell(table, cell, Element.ALIGN_CENTER, 1);

                // Latitude
                projectLocations = new StringBuffer();
                if (location.isOtherLocation()) {
                    otherLocation = (OtherLocation) location;

                    answer = otherLocation.getGeoPosition().getLatitude();

                    cell = new Paragraph();
                    cell.setFont(TABLE_BODY_FONT);
                    if (answer != 0) {
                        cell.add(String.valueOf(answer));
                    } else {
                        cell.add("Not applicable");
                    }
                    this.addTableBodyCell(table, cell, Element.ALIGN_CENTER, 1);

                    // Longitude
                    answer = otherLocation.getGeoPosition().getLatitude();
                    cell = new Paragraph();
                    cell.setFont(TABLE_BODY_FONT);
                    if (answer != 0) {
                        cell.add(String.valueOf(answer));
                    } else {
                        cell.add("Not applicable");
                    }
                    this.addTableBodyCell(table, cell, Element.ALIGN_CENTER, 1);

                } else {

                    // Latitude
                    cell = new Paragraph();
                    cell.setFont(TABLE_BODY_FONT);
                    cell.add("Not applicable");
                    this.addTableBodyCell(table, cell, Element.ALIGN_CENTER, 1);

                    cell = new Paragraph();
                    cell.setFont(TABLE_BODY_FONT);
                    // Longitude
                    cell.add("Not applicable");
                    this.addTableBodyCell(table, cell, Element.ALIGN_CENTER, 1);
                }

                // Name
                cell = new Paragraph();
                cell.setFont(TABLE_BODY_FONT);
                projectLocations = new StringBuffer();
                projectLocations.append(location.getName());
                cell.add(projectLocations.toString());
                this.addTableBodyCell(table, cell, Element.ALIGN_CENTER, 1);
            }
            title = new Paragraph();

            title.add(Chunk.NEWLINE);
            title.add(Chunk.NEWLINE);
            document.add(title);
            document.add(table);

            if (!project.isReporting()) {
                // Lesson regarding locations
                Paragraph locationsBlock = new Paragraph();
                locationsBlock.setAlignment(Element.ALIGN_JUSTIFIED);
                locationsBlock.add(Chunk.NEWLINE);
                locationsBlock.add(Chunk.NEWLINE);
                locationsBlock.setFont(BODY_TEXT_BOLD_FONT);
                locationsBlock.add(this.getText("summaries.project.location.lessonRegarding"));
                locationsBlock.setFont(BODY_TEXT_FONT);
                if (project.getComponentLesson("locations") != null) {
                    locationsBlock
                            .add(this.messageReturn(project.getComponentLesson("locations").getLessons()));
                } else {
                    locationsBlock.add(this.messageReturn(null));
                }
                document.add(locationsBlock);
            }
        }

    } catch (DocumentException e) {
        LOG.error("There was an error trying to add the project locations to the project summary pdf", e);
    } catch (MalformedURLException e) {
        LOG.error("There was an error trying to add the project focuses to the project summary pdf", e);
        e.printStackTrace();
    } catch (IOException e) {
        LOG.error("There was an error trying to add the project focuses to the project summary pdf", e);
        e.printStackTrace();
    }

}

From source file:org.dgl.imgstopdf.Main.java

public static void main(String[] args) {
    Document document = new Document();
    ArrayList<String> input;
    String output = ".\\out.pdf";
    try {//from  w w  w . j a  v a  2 s.  c om
        FileOutputStream fos = new FileOutputStream(output);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, fos);
        Image image;
        JFileChooser fc = new JFileChooser(".\\");
        fc.setMultiSelectionEnabled(true);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("IMAGES", "jpg", "jpeg", "gif", "png",
                "bmp");
        fc.setFileFilter(filter);
        int userOption = fc.showOpenDialog(null);
        if (userOption == JFileChooser.APPROVE_OPTION) {
            input = new ArrayList<String>();
            for (File f : fc.getSelectedFiles()) {
                input.add(f.getAbsolutePath());
            }
            if (fc.getSelectedFile() != null) {
                input.add(fc.getSelectedFile().getAbsolutePath());
            }
        } else {
            return;
        }
        if (input.size() == 0) {
            return;
        }
        pdfWriter.open();
        document.open();
        for (Object fileName : input.toArray()) {
            image = Image.getInstance((String) fileName);
            float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin())
                    / image.getWidth()) * 100;
            image.scalePercent(scaler);
            document.add(image);
        }
        document.close();
        pdfWriter.close();
        JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ex.toString(), "", JOptionPane.ERROR_MESSAGE);
    }
}

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;
            }/* ww  w . j  ava2s. co  m*/
        }
        // 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.jbpm.designer.web.server.TransformerServlet.java

License:Apache License

public void scalePDFImage(Document document, Image image) {
    float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin())
            / image.getWidth()) * 100;/*from   w  ww. jav  a  2  s .  c  om*/

    image.scalePercent(scaler);
}

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.ja v a 2  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
        }
    }
}

From source file:org.sigmah.server.report.renderer.itext.ItextChartRenderer.java

License:Open Source License

public void render(DocWriter writer, Document doc, PivotChartElement element) {

    try {/*from w w  w.  j ava  2s  . c o m*/
        doc.add(ThemeHelper.elementTitle(element.getTitle()));
        ItextRendererHelper.addFilterDescription(doc, element.getContent().getFilterDescriptions());

        float width = doc.getPageSize().getWidth() - doc.rightMargin() - doc.leftMargin();
        float height = (doc.getPageSize().getHeight() - doc.topMargin() - doc.bottomMargin()) / 3f;

        if (writer instanceof PdfWriter) {

            // We can render the chart directly as vector graphics
            // in the PDF file

            PdfWriter pdfWriter = (PdfWriter) writer;
            PdfContentByte cb = pdfWriter.getDirectContent();
            Graphics2D g2d = cb.createGraphics(width, height);
            chartRenderer.render(element, false, g2d, (int) width, (int) height, 72);
            g2d.dispose();

        } else {

            // For RTF/Html we embed as a GIF

            width = width / 72f * RESOLUTION;
            height = height / 72f * RESOLUTION;

            BufferedImage chartImage = chartRenderer.renderImage(element, false, (int) width, (int) height,
                    RESOLUTION);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(chartImage, "GIF", baos);

            Image image = Image.getInstance(baos.toByteArray());
            image.scalePercent(72f / RESOLUTION * 100f);

            doc.add(image);

        }

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