Example usage for com.lowagie.text Image getInstance

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

Introduction

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

Prototype

public static Image getInstance(Image image) 

Source Link

Document

gets an instance of an Image

Usage

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

License:Open Source License

public boolean createPDF(String title, OutputStream out) throws ClientException {
    try {/*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.nuxeo.ecm.platform.ui.web.component.seam.NuxeoITextImageProvider.java

License:Open Source License

@Override
public Image getImage(String src, HashMap h, ChainedProperties cprops, DocListener doc) {
    if (!src.startsWith("http")) {
        // add base url
        String base = VirtualHostHelper.getServerURL(request, false);
        if (base != null && base.endsWith("/")) {
            base = base.substring(0, base.length() - 1);
        }//www. j  av  a  2  s  .c  om
        if (base != null) {
            src = base + src;
        }
    }
    // pass jsession id for authentication propagation
    String uriPath = URIUtils.getURIPath(src);
    src = uriPath + ";jsessionid=" + DocumentModelFunctions.extractJSessionId(request);
    URI uri = URI.create(src);
    String uriQuery = uri.getQuery();
    if (uriQuery != null && uriQuery.length() > 0) {
        src = src + '?' + uriQuery;
    }
    try {
        return Image.getInstance(src);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (BadElementException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.component.seam.UIImage.java

License:Open Source License

@Override
public void createITextObject(FacesContext context) throws IOException, DocumentException {
    value = valueBinding(context, "value", value);

    // instance() doesn't work here - we need a new instance
    org.jboss.seam.ui.graphicImage.Image seamImage = new org.jboss.seam.ui.graphicImage.Image();
    try {//from  ww w  .ja v a 2 s  .  c  o m
        if (value instanceof BufferedImage) {
            seamImage.setBufferedImage((BufferedImage) value);
        } else {
            seamImage.setInput(value);
        }
    } catch (Exception e) {
        log.error("Cannot resolve image for value " + value, e);
        return;
    }

    for (UIComponent cmp : this.getChildren()) {
        if (cmp instanceof ImageTransform) {
            ImageTransform imageTransform = (ImageTransform) cmp;
            imageTransform.applyTransform(seamImage);
        }
    }

    byte[] data = seamImage.getImage();
    if (data == null) {
        log.error("Cannot resolve image for value " + value);
        return;
    }
    image = Image.getInstance(data);

    rotation = (Float) valueBinding(context, "rotation", rotation);
    if (rotation != 0) {
        image.setRotationDegrees(rotation);
    }

    height = (Float) valueBinding(context, "height", height);
    width = (Float) valueBinding(context, "width", width);
    if (height > 0 || width > 0) {
        image.scaleAbsolute(width, height);
    }

    int alignmentValue = 0;

    alignment = (String) valueBinding(context, "alignment", alignment);
    if (alignment != null) {
        alignmentValue = (ITextUtils.alignmentValue(alignment));
    }

    wrap = (Boolean) valueBinding(context, "wrap", wrap);
    if (wrap != null && wrap.booleanValue()) {
        alignmentValue |= Image.TEXTWRAP;
    }

    underlying = (Boolean) valueBinding(context, "underlying", underlying);
    if (underlying != null && underlying.booleanValue()) {
        alignmentValue |= Image.UNDERLYING;
    }

    image.setAlignment(alignmentValue);

    alt = (String) valueBinding(context, "alt", alt);
    if (alt != null) {
        image.setAlt(alt);
    }

    indentationLeft = (Float) valueBinding(context, "indentationLeft", indentationLeft);
    if (indentationLeft != null) {
        image.setIndentationLeft(indentationLeft);
    }

    indentationRight = (Float) valueBinding(context, "indentationRight", indentationRight);
    if (indentationRight != null) {
        image.setIndentationRight(indentationRight);
    }

    spacingBefore = (Float) valueBinding(context, "spacingBefore", spacingBefore);
    if (spacingBefore != null) {
        image.setSpacingBefore(spacingBefore);
    }

    spacingAfter = (Float) valueBinding(context, "spacingAfter", spacingAfter);
    if (spacingAfter != null) {
        image.setSpacingAfter(spacingAfter);
    }
    widthPercentage = (Float) valueBinding(context, "widthPercentage", widthPercentage);
    if (widthPercentage != null) {
        image.setWidthPercentage(widthPercentage);
    }

    initialRotation = (Float) valueBinding(context, "initialRotation", initialRotation);
    if (initialRotation != null) {
        image.setInitialRotation(initialRotation);
    }

    dpi = (String) valueBinding(context, "dpi", dpi);
    if (dpi != null) {
        int[] dpiValues = ITextUtils.stringToIntArray(dpi);
        image.setDpi(dpiValues[0], dpiValues[1]);
    }

    applyRectangleProperties(context, image);

    scalePercent = (String) valueBinding(context, "scalePercent", scalePercent);
    if (scalePercent != null) {
        float[] scale = ITextUtils.stringToFloatArray(scalePercent);
        if (scale.length == 1) {
            image.scalePercent(scale[0]);
        } else if (scale.length == 2) {
            image.scalePercent(scale[0], scale[1]);
        } else {
            throw new RuntimeException("scalePercent must contain one or two scale percentages");
        }
    }
}

From source file:org.opencms.pdftools.CmsPdfUserAgent.java

License:Open Source License

/**
 * @see org.xhtmlrenderer.swing.NaiveUserAgent#getImageResource(java.lang.String)
 *///from w ww  .  j av a2  s  . c  o m
@SuppressWarnings("unchecked")
@Override
public ImageResource getImageResource(String uri) {

    ImageResource resource = null;
    resource = (ImageResource) _imageCache.get(uri);
    if (resource == null) {
        byte[] imageData = readImage(uri);
        if (imageData != null) {
            try {
                Image image = Image.getInstance(imageData);
                scaleToOutputResolution(image);
                resource = new ImageResource(uri, new ITextFSImage(image));
                _imageCache.put(uri, resource);
            } catch (Exception e) {
                LOG.error("Problem with getting image resource " + uri, e);
            }
        }
    }

    if (resource != null) {
        resource = new ImageResource(resource.getImageUri(),
                (FSImage) ((ITextFSImage) resource.getImage()).clone());
    } else {
        resource = new ImageResource(uri, null);
    }
    return resource;
}

From source file:org.opensignature.opensignpdf.PDFSigner.java

License:Open Source License

/**
 * @param mySign/*from  ww  w . ja va2 s. c  om*/
 * @param session
 * @param reason
 * @param signCertKeyObject
 * @param certs
 * @param stamper
 * @throws IOException
 * @throws DocumentException
 * @throws NoSuchAlgorithmException
 * @throws TokenException
 * @throws ExceptionConverter
* @throws NoSuchProviderException 
 */
private void createSignatureAppearance(MyPkcs11 mySign, Session session, String reason, Key signCertKeyObject,
        X509Certificate[] certs, PdfStamperOSP stamper, boolean signatureVisible, Calendar cal)
        throws IOException, DocumentException, NoSuchAlgorithmException, TokenException, ExceptionConverter,
        NoSuchProviderException {

    logger.info("[createSignatureAppearance.in]:: ");

    byte[] signatureBytes = new byte[128];

    PdfSignatureAppearanceOSP sap = stamper.getSignatureAppearance();

    sap.setCrypto(null, certs, null, PdfSignatureAppearance.WINCER_SIGNED);
    sap.setReason(reason);

    if (signatureVisible) {
        if ("countersigner".equals(typeSignatureSelected)) {
            sap.setCertified(0);
            sap.setVisibleSignature(fieldName);
        } else {
            sap.setCertified(0);
            if ((fieldName != null) && (!"".equals(fieldName))) {
                sap.setVisibleSignature(fieldName);
            } else {
                sap.setVisibleSignature(new com.lowagie.text.Rectangle(llx, lly, urx, ury), 1, null);
            }
        }

    }

    //aggiunta di grafico per la firma
    if ("true".equals(graphicSignSelected)) {
        sap.setSignatureGraphic(Image.getInstance(fileImgfirma));
        sap.setRender(2);
    } else {
        sap.setRender(0);
    }
    sap.setExternalDigest(new byte[128], new byte[20], "RSA");

    PdfDictionary dic = new PdfDictionary();
    dic.put(PdfName.FT, PdfName.SIG);
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKLite"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));
    if (cal != null) {
        dic.put(PdfName.M, new PdfDate(cal));
    } else {
        dic.put(PdfName.M, new PdfNull());
    }
    dic.put(PdfName.NAME, new PdfString(PdfPKCS7.getSubjectFields((X509Certificate) certs[0]).getField("CN")));
    dic.put(PdfName.REASON, new PdfString(reason));

    sap.setCryptoDictionary(dic);

    HashMap exc = new HashMap();
    exc.put(PdfName.CONTENTS, new Integer(0x5002));
    sap.preClose(exc);

    byte[] content = IOUtils.streamToByteArray(sap.getRangeStream());
    byte[] hash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1", "BC").digest(content);

    // costruzione degli authenticated attributes
    ASN1EncodableVector signedAttributes = buildSignedAttributes(hash, cal);
    byte[] bytesForSecondHash = IOUtils.toByteArray(new DERSet(signedAttributes));

    byte[] secondHash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1").digest(bytesForSecondHash);

    // -- Generatting the signature
    signatureBytes = mySign.sign(session, secondHash, signCertKeyObject);

    byte[] encodedPkcs7 = null;
    try {

        // Create the set of Hash algorithms
        DERConstructedSet digestAlgorithms = new DERConstructedSet();

        // Creo manualmente la sequenza di digest algos
        ASN1EncodableVector algos = new ASN1EncodableVector();
        //algos.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1
        //SHA256
        algos.add(new DERObjectIdentifier("2.16.840.1.101.3.4.2.1"));
        algos.add(new DERNull());
        digestAlgorithms.addObject(new DERSequence(algos));

        // Create the contentInfo.
        ASN1EncodableVector ev = new ASN1EncodableVector();
        ev.add(new DERObjectIdentifier("1.2.840.113549.1.7.1")); // PKCS7SignedData

        DERSequence contentinfo = new DERSequence(ev);

        // Get all the certificates
        //
        ASN1EncodableVector v = new ASN1EncodableVector();
        for (int c = 0; c < certs.length; c++) {
            ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(certs[c].getEncoded()));
            v.add(tempstream.readObject());
        }

        DERSet dercertificates = new DERSet(v);

        // Create signerinfo structure.
        //
        ASN1EncodableVector signerinfo = new ASN1EncodableVector();

        // Add the signerInfo version
        //
        signerinfo.add(new DERInteger(1));

        v = new ASN1EncodableVector();
        v.add(CertUtil.getIssuer(certs[0]));
        v.add(new DERInteger(certs[0].getSerialNumber()));
        signerinfo.add(new DERSequence(v));

        // Add the digestAlgorithm
        v = new ASN1EncodableVector();
        //v.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1
        //SHA-256
        v.add(new DERObjectIdentifier("2.16.840.1.101.3.4.2.1"));
        v.add(new DERNull());
        signerinfo.add(new DERSequence(v));

        // add the authenticated attribute if present
        signerinfo.add(new DERTaggedObject(false, 0, new DERSet(signedAttributes)));

        // Add the digestEncryptionAlgorithm
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier("1.2.840.113549.1.1.1"));// RSA
        v.add(new DERNull());
        signerinfo.add(new DERSequence(v));

        // Add the encrypted digest
        signerinfo.add(new DEROctetString(signatureBytes));

        // Add unsigned attributes (timestamp)
        if (serverTimestamp != null && !"".equals(serverTimestamp.toString())) {
            byte[] timestampHash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1", "BC")
                    .digest(signatureBytes);
            ASN1EncodableVector unsignedAttributes = buildUnsignedAttributes(timestampHash, serverTimestamp,
                    usernameTimestamp, passwordTimestamp);
            if (unsignedAttributes != null) {
                signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unsignedAttributes)));
            }
        }

        // Finally build the body out of all the components above
        ASN1EncodableVector body = new ASN1EncodableVector();
        body.add(new DERInteger(1)); // pkcs7 version, always 1
        body.add(digestAlgorithms);
        body.add(contentinfo);
        body.add(new DERTaggedObject(false, 0, dercertificates));

        // Only allow one signerInfo
        body.add(new DERSet(new DERSequence(signerinfo)));

        // Now we have the body, wrap it in it's PKCS7Signed shell
        // and return it
        //
        ASN1EncodableVector whole = new ASN1EncodableVector();
        whole.add(new DERObjectIdentifier("1.2.840.113549.1.7.2"));// PKCS7_SIGNED_DATA
        whole.add(new DERTaggedObject(0, new DERSequence(body)));

        encodedPkcs7 = IOUtils.toByteArray(new DERSequence(whole));

    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }

    PdfDictionary dic2 = new PdfDictionary();

    byte out[] = new byte[0x5000 / 2];
    System.arraycopy(encodedPkcs7, 0, out, 0, encodedPkcs7.length);

    dic2.put(PdfName.CONTENTS, new PdfString(out).setHexWriting(true));
    sap.close(dic2);

    logger.info("[createSignatureAppearance.retorna]:: ");

}

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;
            }/*from ww w .j  a v a 2s . co m*/

            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.oscarehr.common.service.PdfRecordPrinter.java

License:Open Source License

public void printPhotos(String contextPath, List<org.oscarehr.common.model.Document> photos)
        throws DocumentException {
    writer.setStrictImageSequence(true);

    if (photos.size() > 0) {
        Font obsfont = new Font(getBaseFont(), FONTSIZE, Font.UNDERLINE);
        Paragraph p = new Paragraph();
        p.setAlignment(Paragraph.ALIGN_LEFT);
        Phrase phrase = new Phrase(LEADING, "\n\n", getFont());
        p.add(phrase);/*from  w ww .j  a v  a 2s  .  c  o  m*/
        phrase = new Phrase(LEADING, "Photos:", obsfont);
        p.add(phrase);
        getDocument().add(p);
    }

    for (org.oscarehr.common.model.Document doc : photos) {
        Image img = null;
        try {
            //             String location = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR").trim() + doc.getDocfilename();
            String location = EDocUtil.getDocumentPath(doc.getDocfilename());
            logger.info("adding image " + location);
            img = Image.getInstance(location);
        } catch (IOException e) {
            MiscUtils.getLogger().error("error:", e);
            continue;
        }
        img.scaleToFit(getDocument().getPageSize().getWidth() - getDocument().leftMargin()
                - getDocument().rightMargin(), getDocument().getPageSize().getHeight());

        Chunk chunk = new Chunk(img, getDocument().getPageSize().getWidth() - getDocument().leftMargin()
                - getDocument().rightMargin(), getDocument().getPageSize().getHeight());

        Paragraph p = new Paragraph();
        p.add(img);
        p.add(new Phrase("Description:" + doc.getDocdesc(), getFont()));
        getDocument().add(p);

    }
}

From source file:org.oscarehr.common.service.PdfRecordPrinter.java

License:Open Source License

public void printDiagrams(List<EFormValue> diagrams) throws DocumentException {
    writer.setStrictImageSequence(true);

    EFormValueDao eFormValueDao = (EFormValueDao) SpringUtils.getBean("EFormValueDao");

    if (diagrams.size() > 0) {
        Font obsfont = new Font(getBaseFont(), FONTSIZE, Font.UNDERLINE);
        Paragraph p = new Paragraph();
        p.setAlignment(Paragraph.ALIGN_LEFT);
        Phrase phrase = new Phrase(LEADING, "\n\n", getFont());
        p.add(phrase);//  w  w  w  . j  a v a2s .co m
        phrase = new Phrase(LEADING, "Diagrams:", obsfont);
        p.add(phrase);
        getDocument().add(p);
    }

    for (EFormValue value : diagrams) {
        //this is a form from our group, and our appt
        String imgPath = OscarProperties.getInstance().getProperty("eform_image");
        EFormValue imageName = eFormValueDao.findByFormDataIdAndKey(value.getFormDataId(), "image");
        EFormValue drawData = eFormValueDao.findByFormDataIdAndKey(value.getFormDataId(), "DrawData");
        EFormValue subject = eFormValueDao.findByFormDataIdAndKey(value.getFormDataId(), "subject");

        String image = imgPath + File.separator + imageName.getVarValue();
        logger.debug("image for eform is " + image);
        GraphicalCanvasToImage convert = new GraphicalCanvasToImage();
        File tempFile = null;
        try {
            tempFile = File.createTempFile("graphicImg", ".png");
            FileOutputStream fos = new FileOutputStream(tempFile);
            convert.convertToImage(image, drawData.getVarValue(), "PNG", fos);
            logger.debug("converted image is " + tempFile.getName());
            fos.close();
        } catch (IOException e) {
            logger.error("Error", e);
            if (tempFile != null) {
                tempFile.delete();
            }
            continue;
        }

        Image img = null;
        try {
            logger.info("adding diagram " + tempFile.getAbsolutePath());
            img = Image.getInstance(tempFile.getAbsolutePath());
        } catch (IOException e) {
            logger.error("error:", e);
            continue;
        }
        img.scaleToFit(getDocument().getPageSize().getWidth() - getDocument().leftMargin()
                - getDocument().rightMargin(), getDocument().getPageSize().getHeight());
        Paragraph p = new Paragraph();
        p.add(img);
        p.add(new Phrase("Subject:" + subject.getVarValue(), getFont()));
        getDocument().add(p);

        tempFile.deleteOnExit();
    }

}

From source file:org.oss.pdfreporter.pdf.Page.java

License:Open Source License

private Image getImage(IImage image) throws BadElementException, IOException {
    if (image != null) {
        return Image.getInstance((Image) image.getPeer());
    }//from  w  w  w  .  ja v a2s .c o  m
    return null;
    //      Image pdfImage = Image.getInstance((Image)image.getPeer());
    //      return  Image.getInstance(pdfImage);
}

From source file:org.oss.pdfreporter.pdf.Page.java

License:Open Source License

@Override
public void draw(IImage image, float x, float y, float width, float height, ScaleMode mode)
        throws DocumentException {
    try {/*from w w w . j av a2  s .co  m*/
        Image pdfImage = null;
        switch (mode) {
        case NONE:
            pdfImage = getImage(image);
            PdfTemplate t = delegate.getPdfWriter().getDirectContent().createTemplate(width, height);
            t.addImage(pdfImage, pdfImage.getWidth(), 0, 0, pdfImage.getHeight(), 0,
                    height - pdfImage.getHeight());
            pdfImage = Image.getInstance(t);
            break;
        case SCALE:
            pdfImage = getImage(image);
            pdfImage.scaleAbsolute(width, height);
            break;
        case SIZE:
            pdfImage = getImage(image);
            pdfImage.scaleToFit(width, height);
            break;
        }
        pdfImage.setAbsolutePosition(x, y);
        delegate.addImage(pdfImage);
    } catch (Exception e) {
        throw new DocumentException(e);
    }

}