Example usage for com.lowagie.text Rectangle Rectangle

List of usage examples for com.lowagie.text Rectangle Rectangle

Introduction

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

Prototype

public Rectangle(float llx, float lly, float urx, float ury) 

Source Link

Document

Constructs a Rectangle -object.

Usage

From source file:org.opentestsystem.delivery.testreg.rest.view.PdfReportPageEventHelper.java

License:Open Source License

public PdfReportPageEventHelper(final PdfWriter writer) {
    template = writer.getDirectContent().createTemplate(100, 100);
    template.setBoundingBox(new Rectangle(-20, -20, 100, 100));
    try {//w w  w.j  a  va  2 s .  c  om
        helv = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1257, BaseFont.NOT_EMBEDDED);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

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  w w w .j  ava2 s. com*/

            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.casemgmt.service.PageNumberStamper.java

License:Open Source License

/**
 * Initializes template and base font// ww  w .j  a v a 2 s . com
 * 
 * @param writer
 * @param document
 */
public void onOpenDocument(PdfWriter writer, Document document) {
    total = writer.getDirectContent().createTemplate(100, 100);
    total.setBoundingBox(new Rectangle(-40, -40, 100, 100));
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfLogicalPageDrawable.java

License:Open Source License

protected void drawHyperlink(final RenderNode box, final String target, final String window,
        final String title) {
    if (box.isNodeVisible(getDrawArea()) == false) {
        return;//w  w w . j a  v  a 2 s  .c om
    }

    final PdfAction action = createActionForLink(target);

    final AffineTransform affineTransform = getGraphics().getTransform();
    final float translateX = (float) affineTransform.getTranslateX();

    final float leftX = translateX + (float) (StrictGeomUtility.toExternalValue(box.getX()));
    final float rightX = translateX + (float) (StrictGeomUtility.toExternalValue(box.getX() + box.getWidth()));
    final float lowerY = (float) (globalHeight
            - StrictGeomUtility.toExternalValue(box.getY() + box.getHeight()));
    final float upperY = (float) (globalHeight - StrictGeomUtility.toExternalValue(box.getY()));

    if (action != null) {
        final PdfAnnotation annotation = new PdfAnnotation(writer, leftX, lowerY, rightX, upperY, action);
        writer.addAnnotation(annotation);
    } else if (StringUtils.isEmpty(title) == false) {
        final Rectangle rect = new Rectangle(leftX, lowerY, rightX, upperY);
        final PdfAnnotation commentAnnotation = PdfAnnotation.createText(writer, rect, "Tooltip", title, false,
                null);
        commentAnnotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL,
                writer.getDirectContent().createAppearance(rect.getWidth(), rect.getHeight()));
        writer.addAnnotation(commentAnnotation);
    }
}

From source file:org.posterita.core.PDFReportPageEventHelper.java

License:Open Source License

public void onOpenDocument(PdfWriter writer, Document document) {
    SimpleDateFormat sdf = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1);
    dateAndTime = sdf.format(Calendar.getInstance().getTime());

    table = new PdfPTable(2);
    tpl = writer.getDirectContent().createTemplate(100, 100);
    tpl.setBoundingBox(new Rectangle(-20, -20, 100, 100));

}

From source file:org.revager.export.PDFCellEventExtRef.java

License:Open Source License

@Override
public void cellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] canvas) {
    PdfContentByte cb = canvas[PdfPTable.LINECANVAS];

    // cb.reset();

    Rectangle attachmentRect = new Rectangle(rect.getLeft() - 25, rect.getTop() - 25,
            rect.getRight() - rect.getWidth() - 40, rect.getTop() - 10);

    String fileDesc = file.getName() + " (" + translate("File Attachment") + ")";

    try {/*  ww  w.j  a va 2  s. c  om*/
        PdfAnnotation attachment = PdfAnnotation.createFileAttachment(writer, attachmentRect, fileDesc, null,
                file.getAbsolutePath(), file.getName());
        writer.addAnnotation(attachment);
    } catch (IOException e) {
        /*
         * just do not add a reference if the file was not found or another
         * error occured.
         */
    }

    // cb.setColorStroke(new GrayColor(0.8f));
    // cb.roundRectangle(rect.getLeft() + 4, rect.getBottom(),
    // rect.getWidth() - 8, rect.getHeight() - 4, 4);

    cb.stroke();
}

From source file:org.tn5250jlpr.SCS2PDF.java

License:Open Source License

private void scs_D2() throws Exception {

    byte byte0 = bk.getNextByte();
    byte function = bk.getNextByte();

    switch (function) {
    case SCS_D2_SIC:
        int ic = bk.getNextByte();
        System.out.println(" Set initial conditions " + ic);
        break;//  w  w  w  . j a v a2  s. c o  m
    case SCS_D2_SPSU:
        int pf = 0;
        byte0 -= 2; // length include length + function + xxxxx so we offset
                    // length by 2 to skip over them
        for (int spsulen = 0; spsulen < byte0; spsulen++) {
            if (spsulen == 1)
                pf = bk.getNextByte();
            else
                bk.getNextByte();
        }
        System.out.println(" Set print setup " + pf);
        break;
    case SCS_D2_SJM:
        int st = 0;
        int pr = 0;

        st = bk.getNextByte(); // State
                               //    0 - state off
                               //    1 - Activate. begin justification

        if (byte0 == 4)
            pr = bk.getNextByte(); // Percent Rule
                                   //  0,50 or 100
        System.out.println(" Set justification mode state: " + st + " percent: " + pr);
        break;
    case SCS_D2_SEA:
        byte0 -= 2; // length include length + function + xxxxx so we offset
                    // length by 2 to skip over them
        System.out.print(" Set exception actions - ignored for now - : ");
        for (int seaulen = 0; seaulen < byte0; seaulen++) {
            System.out.print(bk.getNextByte() + " ");
        }
        System.out.println();
        break;

    case SCS_D2_SLS:
        lineSpacing = bk.getNextByte();
        System.out.println(" Set line spacing: " + lineSpacing);
        break;

    case SCS_D2_SHM:

        int lm = (bk.getNextByte() & 0xff) << 8 | bk.getNextByte() & 0xff;
        int rm = 0;
        if (byte0 == 06)
            rm = (bk.getNextByte() & 0xff) << 8 | bk.getNextByte() & 0xff;

        leftMargin = (float) lm / 1440;
        if (rm != 0)
            rightMargin = (float) rm / 1440;

        //            document.setMargins(getPointFromInches(leftMargin),
        //                                 getPointFromInches(rightMargin),
        //                                    document.topMargin(),
        //                                    document.bottomMargin());

        System.out.println(" Set horizontal margins: left " + leftMargin + " " + getPointFromInches(leftMargin)
                + " right: " + rightMargin);
        break;
    case SCS_D2_SVM:
        int topM = (bk.getNextByte() & 0xff) << 8 | bk.getNextByte() & 0xff;
        int botM = 0;
        if (byte0 == 06)
            botM = (bk.getNextByte() & 0xff) << 8 | bk.getNextByte() & 0xff;

        topMargin = (float) topM / 1440;
        if (botM != 0)
            bottomMargin = (float) botM / 1440;

        document.setMargins(document.leftMargin(), document.rightMargin(), getPointFromInches(topMargin),
                getPointFromInches(bottomMargin));
        System.out.println(" Set vertical margins: top " + topMargin + " " + topM + " bottom: " + bottomMargin
                + " " + botM);
        break;

    case SCS_D2_SCG:
        int gcgid = (bk.getNextByte() & 0xff) << 8 | bk.getNextByte() & 0xff;
        int gcid = (bk.getNextByte() & 0xff) << 8 | bk.getNextByte() & 0xff;

        // note this may be the font controls that set the code page to
        //    be used for translation of the text.  for now we will ignore it
        //    See SCGL - note for me....
        System.out.println(" Set GCGID through GCID: GCGID ignored " + gcgid + " gcid: " + gcid);
        break;

    case SCS_D2_PPM:
        byte0 -= 2; // length include length + function + xxxxx so we offset
                    // length by 2 to skip over them
        System.out.print(" Page presentation media -ignored for now- : ");
        for (int pplen = 0; pplen < byte0; pplen++) {
            System.out.print(bk.getNextByte() + " ");
        }
        System.out.println();
        break;
    case SCS_D2_SPPS:
        int width = (bk.getNextByte() & 0xff) << 8 | bk.getNextByte() & 0xff;
        int height = (bk.getNextByte() & 0xff) << 8 | bk.getNextByte() & 0xff;

        pgWidth = (float) width / 1440;
        pgHeight = (float) height / 1440;

        //            bos.pause();
        document.setPageSize(
                new Rectangle(0.0f, 0.0f, getPointFromInches(pgWidth), getPointFromInches(pgHeight)));
        //            document.newPage();
        //            document.setPageSize(new Rectangle(0.0f,
        //                                                0.0f,
        //                                                getPointFromInches(pgHeight),
        //                                                getPointFromInches(pgWidth)));
        //            bos.resume();
        System.out.println(" Set Presentation Page Size: Width " + pgWidth + " Height: " + pgHeight);

        break;
    case SCS_D2_SSLD:
        float distance = (bk.getNextByte() & 0xff) << 8 | bk.getNextByte() & 0xff;

        // distance divided by 1440ths of an inch
        System.out.println(" Set Single Line Distance: " + distance + "/1440 = " + (distance / 1440));

        break;

    default:
        System.out.println(" Invalid D2 function " + function);
        byte0 -= 2; // length include length + function + xxxxx so we offset
                    // length by 2 to skip over them
        for (int len = 0; len < byte0; len++) {
            bk.getNextByte();
        }
        break;
    }
}

From source file:org.webpki.pdf.PDFSigner.java

License:Apache License

public byte[] addDocumentSignature(byte[] indoc, boolean certified) throws IOException {
    try {//  w  w w  .j av a 2 s.  co  m
        PdfReader reader = new PdfReader(indoc);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(8192);
        PdfStamper stp = PdfStamper.createSignature(reader, bout, '\0', null, true);

        for (Attachment file : attachments) {
            stp.addFileAttachment(file.description, file.data, "dummy", file.filename);
        }

        PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(null, signer.getCertificatePath(), null, PdfSignatureAppearance.WINCER_SIGNED);

        if (reason != null) {
            sap.setReason(reason);
        }
        if (location != null) {
            sap.setLocation(location);
        }

        if (enable_signature_graphics) {
            sap.setVisibleSignature(new Rectangle(100, 100, 400, 130), reader.getNumberOfPages(), null);
        }

        sap.setCertified(certified);

        //           sap.setExternalDigest (new byte[128], new byte[20], "RSA");
        sap.setExternalDigest(new byte[512], new byte[20], "RSA");
        sap.preClose();
        MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        byte buf[] = new byte[8192];
        int n;
        InputStream inp = sap.getRangeStream();
        while ((n = inp.read(buf)) > 0) {
            messageDigest.update(buf, 0, n);
        }
        byte hash[] = messageDigest.digest();
        PdfSigGenericPKCS sg = sap.getSigStandard();
        PdfLiteral slit = (PdfLiteral) sg.get(PdfName.CONTENTS);
        byte[] outc = new byte[(slit.getPosLength() - 2) / 2];
        PdfPKCS7 sig = sg.getSigner();
        sig.setExternalDigest(signer.signData(hash, AsymSignatureAlgorithms.RSA_SHA1), hash, "RSA");
        PdfDictionary dic = new PdfDictionary();
        byte[] ssig = sig.getEncodedPKCS7();
        System.arraycopy(ssig, 0, outc, 0, ssig.length);
        dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));
        sap.close(dic);

        return bout.toByteArray();
    } catch (NoSuchAlgorithmException nsae) {
        throw new IOException(nsae.getMessage());
    } catch (DocumentException de) {
        throw new IOException(de.getMessage());
    }
}

From source file:oscar.oscarReport.pageUtil.GenerateEnvelopesAction.java

License:Open Source License

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {//from   w w  w  . j a v a 2  s. com

    String[] demos = request.getParameterValues("demos");
    String providerNo = (String) request.getSession().getAttribute("user");

    //TODO: Change to be able to use other size envelopes
    Rectangle _10Envelope = new Rectangle(0, 0, 684, 297);
    float marginLeft = 252;
    float marginRight = 0;
    float marginTop = 144;
    float marginBottom = 0;
    Document document = new Document(_10Envelope, marginLeft, marginRight, marginTop, marginBottom);
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=\"envelopePDF-"
            + UtilDateUtilities.getToday("yyyy-mm-dd.hh.mm.ss") + ".pdf\"");

    try {
        PdfWriter.getInstance(document, response.getOutputStream());
        document.open();

        for (int i = 0; i < demos.length; i++) {
            DemographicData demoData = new DemographicData();
            Demographic d = demoData.getDemographic(demos[i]);
            String envelopeLabel = d.getFirstName() + " " + d.getLastName() + "\n" + d.getAddress() + "\n"
                    + d.getCity() + ", " + d.getProvince() + "\n" + d.getPostal();

            document.add(getEnvelopeLabel(envelopeLabel));
            document.newPage();
        }

    } catch (DocumentException de) {
        logger.error("", de);
    } catch (IOException ioe) {
        logger.error("", ioe);
    }
    document.close();

    return null;
}

From source file:papertoolkit.render.SheetRenderer.java

License:BSD License

/**
 * Uses the iText package to render a PDF file from scratch. iText is nice because we can write to a
 * Graphics2D context. Alternatively, we can use PDF-like commands.
 * //w w  w .j a  va 2s . c  o  m
 * @param destPDFFile
 */
public void renderToPDF(File destPDFFile) {
    try {
        final FileOutputStream fileOutputStream = new FileOutputStream(destPDFFile);

        final Rectangle pageSize = new Rectangle(0, 0, (int) Math.round(sheet.getWidth().getValueInPoints()),
                (int) Math.round(sheet.getHeight().getValueInPoints()));

        // create a document with these margins (worry about margins later)
        final Document doc = new Document(pageSize, 0, 0, 0, 0);
        final PdfWriter writer = PdfWriter.getInstance(doc, fileOutputStream);
        doc.open();

        final PdfContentByte topLayer = writer.getDirectContent();
        final PdfContentByte bottomLayer = writer.getDirectContentUnder();
        renderToPDFContentLayers(destPDFFile, topLayer, bottomLayer);

        doc.close();

        // save the pattern info to the same directory automatically
        savePatternInformation(); // do this automatically
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}